|
第二种方法:外壳
同样道理,你也可以为如下的代码编写函数或者一个类。不过,本文仅仅提供基本观念:
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__"' );
上一页 [1] [2] [3] [4] 下一页 |