Monday, May 16, 2011

PHP run command as ROOT


This post is for fun only.

In PHP, If we want to run any command as ROOT, like chown, chmod, how can we do that? In shell, we can use 'su' to run a command with ROOT privilege. For example, to change the mode of a file created by other users, we must have root privilege:

su --login root --command 'chmod 644 /absolute path/changeme.txt'

You will be asked to enter the ROOT password.

So, how can we complete the whole process in PHP code? In PHP manual, there is a function called 'popen'. According to the manual, popen opens a pipe to a process executed by forking the command given by command. It returns a file pointer identical to that returned by fopen() and this pointer may be used with fgets(), fgetss(), and fwrite().

This means, we can do read/write operation on the returned value by popen, same as what we do with the fopen. So, the way to let PHP run a command with ROOT privilege:

$su = "su --login root --command 'chmod 644 /absolute path/changeme.txt'";
$rootPassword = "password";
$fp = @popen($su, "w");
  
//now, we must give the password
@fputs($fp, $rootPassword);
@pclose($fp);

That is it! have fun!

No comments: