Search code examples
phpshellexecutetcpdump

php execute command tcpdump


I know to execute the command should be root, and I find the popen() in php maybe help me to do it. But my code does not work, I do not know the reason......

My code is:

    $sucommand = "su --login root -c tcpdump -c 20000 -s 0 -w $filename &";
    $rootpasswd = "password";
    $fp = @popen($sucommand,"w");
    @fputs($fp,$rootpasswd);
    @pclose($fp);

Is something I typed wrong?

My php file is in Linux server, and I change all file owner in the directory to apache (and mode 0777).

Add: If I should use sudo, what should I concerned? I use php coding.

Any suggestion appreciated!


Solution

  • You can use sudo with -S option to pass password from command line itself.

    [suku@suku-ld ~]$ echo 'YOURSUDOPASSWORD' | sudo -S tcpdump -c 20000 -i eth1 -s 0 -w tmp
    tcpdump: listening on eth1, link-type EN10MB (Ethernet), capture size 65535 bytes
    

    [ADDED] : How to add a user to sudores list?

    suku@ubuntu-vm:~$ which tcpdump 
    /usr/sbin/tcpdump
    

    Execute the command visudo and enter either of following:

    apache  ALL=/usr/sbin/tcpdump
    apache  ALL=NOPASSWD:/usr/sbin/tcpdump
    

    If you use the first one, then when you execute the script with sudo command, it will prompt for apache user's password. But with the second one, it will not even prompt for a sudo password.

    Note: I recommend the first one to use.

    Note : I am assuming you are running your web server with the user apache. If not, change the user name accordingly.