将SSH与PHP相连接 确保传输数据的安全
username root, password secretpassword
if(!ssh2_auth_password($con, "root", "secretpassword")) { echo "fail: unable to authenticate\n"; } else { // allright, we''re in! echo "okay: logged in...\n"; // execute a command if(!($stream = ssh2_exec($con, "ls -al" )) ){ echo "fail: unable to execute command\n"; } else{ // collect returning data from command stream_set_blocking( $stream, true ); $data = ""; while( $buf = fread($stream,4096) ){ $data .= $buf; } fclose($stream); } } 同样道理,你也可以为如下的代码编写函数或者一个类。不过,本文仅仅提供基本观念: if (!function_exists("ssh2_connect")) die("function ssh2_connect doesn''t exist") // log in at server1.example.com on port 22 if(!($con = ssh2_connect("server1.example.com", 22))){ echo "fail: unable to establish connection\n"; } else { // try to authenticate with username root, password secretpassword if(!ssh2_auth_password($con, "root", "secretpassword")) { echo "fail: unable to authenticate\n"; } else { // allright, we''re in! echo "okay: logged in...\n"; // create a shell if(!($shell = ssh2_shell($con, ''vt102'', null, 80, 40, SSH2_TERM_UNIT_CHARS))){ echo "fail: unable to establish shell\n"; } else{ stream_set_blocking( $shell, true ); // send a command fwrite($shell,"ls -al\n"); sleep(1); // & collect returning data $data = ""; while( $buf = fread($shell,,4096) ){ $data .= $buf; } fclose($shell); } } } 小提示: 有时服务器忙碌,或者一个连接出错,缓冲区没有数据,PHP脚本就会停止从一个命令输出(即使命令并没有完成!)中收集数据。你可以为此进行如下的操作: ssh2_exec($con, ''ls -al; echo "__COMMAND_FINISHED__"'' ); $time_start = time(); $data = ""; while( true ){ $data .= fread($stream, 4096); if(strpos($data,"__COMMAND_FINISHED__") !== false){ echo "okay: command finished\n"; break; } if( (time()-$time_start) > 10 ){ echo "fail: timeout of 10 seconds has been reached\n"; break; } } 在上面的例子中,你最好将stream_set_blocking设为false。 通过SSH发送文件 ssh2_scp_send($con, "/tmp/source.dat", "/tmp/dest.dat", 0644); 如果不能正常工作 请检查如下的几个方面: 依照本文检查你操作的每一步 在服务器端,在sshd_config 中必须启用“PasswordAuthentication yes”。在大多数服务器上默认值是yes,不过有些情况下,你可能需要将下面的一行加入到文件中,即亲自动手打开这个功能: /etc/ssh/sshd_config: # Change to yes to enable tunnelled clear text passwords PasswordAuthentication yes 如果作了改变,就需要重新启动SSH: /etc/init.d/ssh restart |
凌众科技专业提供服务器租用、服务器托管、企业邮局、虚拟主机等服务,公司网站:http://www.lingzhong.cn 为了给广大客户了解更多的技术信息,本技术文章收集来源于网络,凌众科技尊重文章作者的版权,如果有涉及你的版权有必要删除你的文章,请和我们联系。以上信息与文章正文是不可分割的一部分,如果您要转载本文章,请保留以上信息,谢谢! |