简体   繁体   English

如何将字符串参数传递给execve

[英]How to pass string argument to execve

How to pass a string argument as shown in the program below? 如下面程序所示,如何传递字符串参数?

The argument after -f should be a string in quotes. -f之后的参数应为带引号的字符串。 I tried to escape \\" but did not work. I also tried to use ' and \\' instead of \\" and again it did not work. 我试图转义\\“但没有用。我还尝试使用' and \\' instead of \\" ,再次它没有用。

#include <stdio.h>
#include <unistd.h>


int main(void)
{

    char *args[] =
    {
        "/usr/ws/bin/tshark", "-i", "/tmp/ts_pipe", "-w",
        "/tmp/output.pcap", "-f", "\"not src host 1.1.1.1\"", "2>", 
        "/tmp/error.log", NULL
    };

    char *envp[] =
    {
        "PATH=$PATH:/usr/wireshark/bin",
        "LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/lib32",
        0
    };

    execve(args[0], &args[0], envp);
    fprintf(stderr, "Oops!\n");
    return -1;
}

Just because you need quotes in the shell, for example, 例如,仅因为您需要在外壳中加引号,

tshark -f "not src host 1.1.1.1"

doesn't mean you need them in exec. 并不意味着您需要在exec中使用它们。 In fact, those quotes are telling the shell "this is one argument", so the shell will not split on spaces and will pass the string (without quotes) as one argument to the program. 实际上,这些引号告诉外壳程序“这是一个参数”,因此外壳程序不会在空格上分割,而是将字符串(不带引号)作为程序的一个参数传递。 So, in C, you would simply: 因此,在C语言中,您只需:

char *args[] = { "-f", "not src host 1.1.1.1" }

and pass that to exec. 并将其传递给执行程序。

While we're at it, redirections like 在进行此操作时,重定向之类的

2>errfile

are intercepted by the shell and not passed on to the command, so they won't work in exec. 被shell拦截并且没有传递给命令,因此它们在exec中不起作用。 You'll have to do the dup()s yourself, or else just pass a whole shell command to the shell (which is a security no-no). 您必须自己执行dup(),否则只需将整个shell命令传递给该shell(安全性为否)。

As explained in the comments, redirection will not work with execve , but you could try doing this: 如评论中所述,重定向将不适用于execve ,但是您可以尝试执行以下操作:

#include <stdio.h>
#include <unistd.h>

int main(void)
{

    char *args[] =
    {
        "/bin/sh", "-c",
        "/usr/ws/bin/tshark -i /tmp/ts_pipe -w "
        "/tmp/output.pcap -f \"not src host 1.1.1.1\" 2> " 
        "/tmp/error.log", NULL
    };

    char *envp[] =
    {
        "PATH=$PATH:/usr/wireshark/bin",
        "LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/lib32",
        0
    };

    execve(args[0], &args[0], envp);
    fprintf(stderr, "Oops!\n");
    return -1;
}

You are basically launching sh shell with -c option and passing it your whole command as an option. 您基本上是使用-c选项启动sh shell并将整个命令作为选项传递给它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM