【问题标题】:PHP Connect over ssh with public key and switch user to execute commandsPHP 使用公钥通过 ssh 连接并切换用户以执行命令
【发布时间】:2014-01-30 19:21:28
【问题描述】:

晚上好,

目前我正在开发一个使用 PHP 的脚本。 PHP 使用带有公钥的“ssh2_connect”作为连接远程主机的命令。此外,我使用 ssh2_exec 通过 user_a 执行一些命令。我想切换到 user_b 来执行 antoher 命令和 可选择返回 user_a。

$connection = ssh2_connect('192.168.2.100', 22, array('hostkey'=>'ssh-rsa'));

if (ssh2_auth_pubkey_file($connection, 'user_a', './ssh/id_rsa.pub', './ssh/id_rsa'))
{
  echo "Public Key Authentication Successful\n<br />";
}
else
{
  die('Public Key Authentication Failed');
}



if(!($stream = ssh2_exec($connection, "sudo su user_b ; cd ~ ; ls -la" )) )
{
    echo "fail: unable to execute command\n";
}
else
{

    stream_set_blocking( $stream, true );

    echo stream_get_contents($stream);

}



ssh2_exec($connection, 'exit');
unset($connection);

问题是正常命令运行良好,但切换用户超时返回(sudo 文件已编辑)...我已经尝试使用 fwrite 发送命令。 ; 有什么解决方案可以通过一些命令(自己的 php 代码)来解决这个问题,还是使用http://phpseclib.sourceforge.net/ 更好?

【问题讨论】:

  • sudo 会提示输入密码。由于您没有发送一个,因此连接将等待一个,直到超时。

标签: php ssh switch-statement


【解决方案1】:

所以你可能会这样做:

echo password | sudo su user_b ; cd ~ ; ls -la

这样做的缺点是它会出现在您的 bash 历史记录中。

这是一种使用 phpseclib 进行操作的方法,它不会出现在你的 bash 历史记录中,而不会出现在你的 bash 历史记录中:

这里有一种使用phpseclib/交互模式获取sudo密码的方法:

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

$rsa = new Crypt_RSA();
$rsa->loadKey('./ssh/id_rsa');

$ssh = new Net_SSH2('192.168.2.100');
if ($ssh->login('user_r', $rsa)) {
    echo "Public Key Authentication Successful\n<br />";
} else {
    die('Public Key Authentication Failed');
}

echo $ssh->read('username@username:~$');
$ssh->write("sudo su user_b\n");
$output = $ssh->read('#[pP]assword[^:]*:|username@username:~\$#', NET_SSH2_READ_REGEX);
echo $output;
if (preg_match('#[pP]assword[^:]*:#', $output)) {
    $ssh->write("password\n");
    echo $ssh->read('username@username:~$');
}

$ssh->write("cd ~\n");
echo $ssh->read('username@username:~$');

$ssh->write("ls -la\n");
echo $ssh->read('username@username:~$');
?>

如果您不关心 bash 历史记录,以下是使用 phpseclib 的方法:

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

$rsa = new Crypt_RSA();
$rsa->loadKey('./ssh/id_rsa');

$ssh = new Net_SSH2('192.168.2.100');
if ($ssh->login('user_r', $rsa)) {
    echo "Public Key Authentication Successful\n<br />";
} else {
    die('Public Key Authentication Failed');
}

echo $ssh->exec("sudo su user_b ; cd ~ ; ls -la");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-08-24
    • 2023-04-05
    • 1970-01-01
    • 2011-05-21
    • 2013-06-08
    • 2019-04-15
    • 2012-01-13
    相关资源
    最近更新 更多