我在 php 的 ssh2 上玩得很开心。(!)
我正在通过 ssh 连接到本地主机(运行 ubuntu)进行测试。我已经成功连接并使用我的用户名(不是 root )进行身份验证,并且一些命令(如“ls”返回一些信息,这是有希望的。肯定会有所作为。
接下来我希望能够执行的是发出“su”命令,然后提供 root 密码。
没有报错,返回了一个资源,但是流里好像没有数据。 (我有点期待“密码:”提示)。我无法直接使用 root 密码进行身份验证,因为 ssh 已禁用该密码。
您认为“su”会返回一些文本是否有任何原因?
我应该期待“密码:”提示返回吗?
这是我的代码:
function changeServerPassword( $ip, $port, $sshUser, $sshPassword, $rootPassword, $newRootPassword, $newSSHPassword = false) {
// login to server using $sshUser and $sshPassword
// su as root and enter $rootPassword
// if any of the above steps fail, return with appropriate error message
if (!function_exists("ssh2_connect")) die("function ssh2_connect doesn't exist");
// log in
// Do I have to make sure that port is a number?
if(!($con = ssh2_connect($ip, $port))){
echo "fail: unable to establish connection\n";
} else {
// try to authenticate with username root, password secretpassword
if(!ssh2_auth_password($con, $sshUser, $sshPassword)) {
echo "fail: unable to authenticate\n";
} else {
// alright, we're in!
echo "okay: logged in...<br />";
//
if (!($stream = ssh2_exec($con, "su"))) {
echo "fail: unable to execute command\n";
} else {
echo $stream."<br />";
// collect returning data from command
stream_set_blocking($stream, true);
echo "after stream_set_blocking<br />";
$data = "";
while ($buf = fread($stream,4096)) {
$data .= $buf;
}
echo "data len: " . strlen($data) . "<br />";
echo $data."<br />";
fclose($stream);
}
}
}
}
借自http://kevin.vanzonneveld.net/techblog/article/make_ssh_connections_with_php/ 尊重。
我得到的输出是:
okay: logged in...
Resource id #3
after stream_set_blocking
data len: 0
在此先感谢您的帮助:)
乔
最佳答案
您应该尝试最新的 SVN 版本 phpseclib - a pure PHP SSH implementation - 反而。以下是您如何使用它执行 su 操作:
<?php
include('Net/SSH2.php');
$ssh = new Net_SSH2('localhost', 22);
$ssh->login('username', 'password');
$ssh->read('[prompt]');
$ssh->write("su - user\n");
$ssh->read('Password:');
$ssh->write("Password\n");
echo $ssh->read('[prompt]');
?>
关于php ssh2_exec 不执行 'su' 命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5732990/