Question

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!

Was it helpful?

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.

OTHER TIPS

I recently published a project that allows PHP to obtain and interact with a real Bash shell (as root if requested), it solves the limitations of exec() and shell_exec(). Get it here: https://github.com/merlinthemagic/MTS

After downloading you would simply use the following code:

$shell    = \MTS\Factories::getDevices()->getLocalHost()->getShell('bash', true);
$timeout = 3600000; // how many miliseconds will it take to capture 20000 packets?
$return1  = $shell->exeCmd('tcpdump -c 20000 -i eth1 -s 0 -w /tmp/tmp.pcap', false, $timeout);
//the return will be a string containing the return of the command
echo $return1;

Then pick up the /tmp/tmp.pcap for processing.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top