php – Unable to execute commands with super user privileges using PHP ssh2_exec().

Unable to execute commands with super user privileges using PHP ssh2_exec()…. here is a solution to the problem.

Unable to execute commands with super user privileges using PHP ssh2_exec().

Commands cannot be executed with super user privileges using PHP ssh2_exec().

If I want to create a folder

test_folder in /var/www on a remote Linux machine, the code below and ssh command seems correct, but I can’t create the folder because I don’t have super user privileges. What confuses me is that I’ve included username and password credentials, but I still can’t execute the command.

$con = new SSH2SFTP($addr,
    new SSH2Password($user, $pass),
    22); 
$cmd = "sudo mkdir -p /var/www/test_folder";    
$stream = ssh2_exec($con, $cmd); 
stream_set_blocking($stream, true);
fclose($stream); 

Any help would be appreciated. Thank you.

Solution

Your method is mostly correct, but suppose you enter linux commands after connecting to a remote machine via ssh. The first time you use “sudo”, you still need to enter your password.

Therefore, you can modify the command as follows:

$cmd = "echo '" . $pass . "' | sudo -S " . $cmd;

Your code will look like this:

$con = new SSH2SFTP($addr,
    new SSH2Password($user, $pass),
    22); 
$cmd = "mkdir -p /var/www/test_folder"; 
$cmd = "echo '" . $pass . "' | sudo -S " . $cmd;
$stream = ssh2_exec($con, $cmd); 
stream_set_blocking($stream, true);
fclose($stream); 

Hope this helps.

Related Problems and Solutions