Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot execute commands with super user previleges using PHP ssh2_exec()

Tags:

linux

php

ssh

Cannot execute commands with super user previleges using PHP ssh2_exec()

If I want to create a folder test_folder inside /var/www on a remote Linux box, the code and ssh command below seems to be correct but, I am unable to create a folder due to lack of super user previlege. The thing I am confused about it is that I have already included the username and password credentials and I am still unable to 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. Thanks.


1 Answers

Your approach is mostly correct, but imagine you are entering the linux command after you ssh into the remote machine. You still need to enter the password the first time you use 'sudo'.

Therefore, you can modify the command as follows:

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

Your code will be 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 it helps.

like image 102
sagunms Avatar answered Dec 05 '25 20:12

sagunms



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!