how can I run a perl script which needs root?

2019-07-30 15:02发布

I need to execute a perl script located in /root/scripts/ from php using ssh from another computer or from the same computer. The thing is that I just don't know how to make php log into roots account to excecute only that file.

As user$ I can't access /root/scripts/, so I can't call it using excec or system. I have tried using ssh to log into sudo su, and when I give my password it hangs.

I leave the code here:

<?php
include('Net/SSH2.php');


$ssh = new Net_SSH2('IP');
if (!$ssh->login('user', 'password')) {
exit('Login Failed');
}else{
echo ("login suscess");
}
echo $ssh->read(']$');

echo $ssh->write("sudo su\n");

echo $ssh->read('user:');
//the code normally runs if I dont write the lines below

$ssh->write('password\n');//here I try to get ssh the root pass but php wont respond after this
echo $ssh->read('user]#');//normally this would work to show the root prompt  but I don't know what happens


?>

I hope you can help me out here.

2条回答
Rolldiameter
2楼-- · 2019-07-30 15:54

Usually you would tell sudo that the webserver user can execute the script without need to authenticate with a password. You'll have to add a line like the following in /etc/sudoers:

www-data ALL=(ALL:ALL) NOPASSWD: /root/scripts/script.pl

This would let the www-data user execute script.pl via sudo without having to enter a password.

Then execute the script from PHP using

exec('sudo /root/scripts/script.pl');
查看更多
smile是对你的礼貌
3楼-- · 2019-07-30 15:57
  1. Echo'ing out $ssh->write() calls doesn't really do much.

  2. sudo needs a password. Here's an example on phpseclib's site of how to handle that: http://phpseclib.sourceforge.net/ssh/examples.html#sudo

查看更多
登录 后发表回答