我想使用 system/pipe 命令来执行具有特殊字符的命令。下面是示例代码。 通过系统/管道执行命令后,它通过改变特殊字符来改变命令。 我很惊讶地看到系统命令正在更改作为命令传递的文本。
run(char *cmd)
{
FILE *in;
extern FILE *popen();
char buff[2048]= {0,};
if(!(in = popen(cmd, "r")))
{
exit(1);
}
while(fgets(buff, sizeof(buff), in)!=NULL)
{
printf("%s", buff);
}
pclose(in);
}
main()
{
char cmd[2048]={0,};
sprintf(cmd,"echo \"'http://1.2.3.4/files-spaces-specialchars-
ascii/%23@%23@@!@!@!@%23%23$$$$$$$ASA(()
(!FreemakeAudioConverterSetup.exe'\" >>/tmp/logger 2>&1");
printf("this is CMD:[%s]\n",cmd);
system("echo "" > /tmp/logger"); /* to clear file containt */
system(cmd);
run(cmd);
}
输出
[terminal]$ ./a.out
this is CMD:[echo "'http://1.2.3.4/files-spaces-specialchars-ascii/%23@%23@@!@!@!@%23$$$$$$$ASA(()(!FreemakeAudioConverterSetup.exe'" >>/tmp/logger 2>&1]
[terminal]$ cat /tmp/logger
'http://1.2.3.4/files-spaces-specialchars-ascii/%23@%23@@!@!@!@%23538853885388(()(!FreemakeAudioConverterSetup.exe'
'http://1.2.3.4/files-spaces-specialchars-ascii/%23@%23@@!@!@!@%23538953895389(()(!FreemakeAudioConverterSetup.exe'
[terminal]$
如上所示,通过系统/管道命令执行后,原始命令 URL 发生了变化。
有开发者的意见吗?
最佳答案
更正代码,因此它可以干净地编译结果:
注意:我还添加了对 perror()
的调用,因此如果对 popen()
的调用失败,用户会被正确通知发生了什么。
#include <stdio.h>
#include <stdlib.h>
void run(char *cmd)
{
FILE *in;
extern FILE *popen();
char buff[2048]= {'\0'};
if(!(in = popen(cmd, "r")))
{
perror( "popen for read failed" );
exit(1);
}
while(fgets(buff, sizeof(buff), in)!=NULL)
{
printf("%s", buff);
}
pclose(in);
}
int main( void )
{
char cmd[2048]={'\0'};
sprintf(cmd, "%s", "echo \"'http://1.2.3.4/files-spaces-specialchars-"
"ascii/%23@%23@@!@!@!@%23%23$$$$$$$ASA(()"
"(!FreemakeAudioConverterSetup.exe'\" >>/tmp/logger 2>&1");
printf("this is CMD:[%s]\n",cmd);
system("echo "" > /tmp/logger"); /* to clear file containt */
system(cmd);
run(cmd);
}
然后运行该代码会产生:
this is CMD:[echo "'http://1.2.3.4/files-spaces-specialchars-ascii/%23@%23@@!@!@!@%23%23$$$$$$$ASA(()(!FreemakeAudioConverterSetup.exe'" >>/tmp/logger 2>&1]
和 cat /tmp/logger
结果:
cat/tmp/记录器
'http://1.2.3.4/files-spaces-specialchars-ascii/%23@%23@@!@!@!@%23%23193951939519395(()(!FreemakeAudioConverterSetup.exe'
'http://1.2.3.4/files-spaces-specialchars-ascii/%23@%23@@!@!@!@%23%23193961939619396(()(!FreemakeAudioConverterSetup.exe'
关于c++ - 系统/管道调用更改传递给执行的命令中的特殊字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38037813/