我必须通过ssh连接到服务器,但要访问它我需要先连接到另一个ssh服务器。我使用标准密码访问它们。
所以我的步骤是:
ssh root@serverdomain1.com
然后当在serverdomain1中连接时,我在终端中执行:
ssh myuseraccount@serverdomain2.com
在php中,我尝试使用ssh2_exec('ssh serverdomain2.com');但没有结果。然后我也尝试了ss2_tunnel($ connection,...)。但没有任何效果。
这不起作用:
$ssh = ssh2_connect('serverdomain1.com', 22);
if (ssh2_auth_password($ssh, $user,$pass)) {
$stream = ssh_exec($ssh, "ssh serverdomain2.com");
stream_set_blocking($stream, true);
$stream_out = ssh2_fetch_stream($stream, SSH2_STREAM_STDIO);
echo stream_get_contents($stream_out); // <== doesn't work!!!
}
这也不起作用:
$ssh = ssh2_connect('serverdomain1.com', 22);
if (ssh2_auth_password($ssh, $user,$pass)) {
$tunnel = ssh2_tunnel($ssh, 'serverdomain2.com', 22);
if (!$tunnel) {
echo('no tunnel<br/>');
}
else {
fwrite($tunnel, "echo 1\n");
while (!feof($tunnel)) {
echo fgets($tunnel, 128);
}
}
}
隧道的回声结果: “SSH-2.0-OpenSSH_6.6.1p1 Ubuntu-2ubuntu2.4协议不匹配。”
如何使用PHP中的SSH2进行此操作?
答案 0 :(得分:1)
我最近发布了一个项目,允许PHP在需要时通过SSH获取真正的Bash shell并与之交互。在此处获取:https://github.com/merlinthemagic/MTS
该项目允许您使用ssh保持从服务器到服务器的弹跳。
下载后,您只需使用以下代码:
//first you get a shell on the first server:
$shellObj = \MTS\Factories::getDevices()->getRemoteHost('ip_address1')->setConnectionDetail('username1', 'password1')->getShell();
//then build on that first shell, the following way.
\MTS\Factories::getDevices()->getRemoteHost('ip_address2')->setConnectionDetail('username2', 'password2')->getShell($shellObj);
//any command executed on the shell will run only on the second host you connected to.
$return1 = $shellObj->exeCmd("hostname");
echo $return1;//hostname of the second host you connected to
//
答案 1 :(得分:0)
这是我使用ssh2访问服务器的工作代码。希望它会有所帮助!
<?php
$host = 'SERVER_HOST_ADDR';
$port = SERVER_PORT;
$username = 'SERVER_USERNAME';
$password = 'SERVER_PASSWORD';
$remoteDir = './home/'; //DIR_PATH
$localDir = '/var/www/html/'; //LOCAL_DIR_PATH
// Make our connection
$connection = ssh2_connect($host);
// Authenticate
if (!ssh2_auth_password($connection, $username, $password)) {
throw new Exception('Unable to connect.');
}
// Create our SFTP resource
if (!$sftp = ssh2_sftp($connection)) {
throw new Exception('Unable to create SFTP connection.');
}
/**
* Now that we have our SFTP resource, we can open a directory resource
* to get us a list of files. Here we will use the $sftp resource in
* our address string as I previously mentioned since our ssh2://
* protocol allows it.
*/
$files = array();
$dirHandle = opendir("ssh2.sftp://$sftp/$remoteDir");
// Properly scan through the directory for files, ignoring directory indexes (. & ..)
while (false !== ($file = readdir($dirHandle))) {
if ($file != '.' && $file != '..') {
$files[] = $file;
}
}
echo "<pre>";print_r($files);
?>