如何使用phpseclib以root权限运行ubuntu命令
问题描述:
我使用phpseclib从php调用ssh命令。如何使用phpseclib以root权限运行ubuntu命令
$ip = 'ip_address';
$login = 'user';
$password = 'password';
$ssh = new SSH2($ip);
$ssh->login($login, $password);
在下面的例子一切正常(因为我不需要权限):
$command = 'ip addr flush dev eth1';
$result = $ssh->exec($command); // result = 'Failed to send flush request: Operation not permitted'
我尝试使用sudo苏登录:在下面的例子中发生
$command = 'ifconfig';
$result = $ssh->exec($command); // result = 'eth0 ..., eth1 etc.'
问题:
$result = $ssh->read('$'); // result = '..... [email protected]:~$'
$result = $ssh->write("sudo su\n"); //result = true
$result = $ssh->read(':'); // result = 'sudo su\n [sudo] password for user:'
$result = $ssh->write($password."\n"); // result = true
$result = $ssh->read('#'); //result = '[email protected]:/home/user#
看来t帽子一切都没问题(我在根),但:
$command = 'ip addr flush dev eth1';
$result = $ssh->exec($command); // result = 'Failed to send flush request: Operation not permitted'
问题在哪里?先谢谢你!
答
我用下面的代码http://mrbluecoat.blogspot.com/2014/03/running-sudo-commands-with-phpseclib.html:
$ssh->read('/.*@.*[$|#]/', NET_SSH2_READ_REGEX);
$ssh->write("sudo YOUR COMMAND HERE\n");
$ssh->setTimeout(10);
$output = $ssh->read('/.*@.*[$|#]|.*[pP]assword.*/', NET_SSH2_READ_REGEX);
if (preg_match('/.*[pP]assword.*/', $output)) {
$ssh->write($sudo_password."\n");
$ssh->read('/.*@.*[$|#]/', NET_SSH2_READ_REGEX);
}
和它的作品!
+0
应该不需要执行'$ ssh-> setTimeout(10)'。 – neubert
答
您需要为root用户组添加httpd进程(apache,php)。子进程可以使用root perm运行。
尝试在sudoers文件中添加自己,然后只需键入sudo,然后按命令(不需要插入密码) –
'su'已经是suid二进制文件。没有必要运行'sudo',因为它总是以root身份运行。 –
我在终端上试过这样的东西:'adduser user sudo',结果是: '用户'用户'已经是'sudo''的成员。接下来,我只在终端中使用'su',结果是:'密码: su:认证失败' – Krzychu