system / pipe调用更改为执行而传递的命令中的特殊字符

时间:2016-06-26 11:00:30

标签: c++ c linux bash

我想使用system / pipe命令执行具有特殊字符的命令。下面是示例代码。 通过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]$

如上所示,通过system / pipe命令执行后,原始命令URL将发生变化。

开发者的任何输入?

1 个答案:

答案 0 :(得分:0)

纠正代码,因此它可以干净地编译结果:

注意:我还添加了对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 / logger

'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'