方法一(推荐)privatefunctionrunSSH($cmdstr)
{
//服务器信息
$host='172.18.0.1';
$user='root';
$passwd='yB1TYzIZhWrn19zV';
//链接远程服务器
$connection=@ssh2_connect($host,22);
if(!$connection){
return'';
die('Connectionfailed.');
}
//可否通过密码连接
$auth_methods=ssh2_auth_none($connection,$user);
if(!in_array('password',$auth_methods)){
return'';
die('Unabletologintoremoteserverbypassword.');
}
//验证密码
if(!ssh2_auth_password($connection,$user,$passwd)){
return'';
die('Passworderror.');
}
$stream=ssh2_exec($connection,$cmdstr);
stream_set_blocking($stream,true);
$str=stream_get_contents($stream);
fclose($stream);
return$str;
}
方法二//服务器信息
$host='10.10.10.10';
$user='root';
$passwd='dD*********JWv07G';
//链接远程服务器
$connection=@ssh2_connect($host,22);
if(!$connection){
die('Connectionfailed.');
}
//可否通过密码连接
$auth_methods=ssh2_auth_none($connection,$user);
if(!in_array('password',$auth_methods)){
die('Unabletologintoremoteserverbypassword.');
}
//验证密码
if(!ssh2_auth_password($connection,$user,$passwd)){
die('Passworderror.');
}
$shell=ssh2_shell($connection,'xterm');
//由于一些模糊的原因,在命令之后,您需要睡眠以确保命令已经到达服务器并正在运行
//上面是其它人测试时加的,我测试后发现不睡眠也可以取到信息,这里标记一下
//sleep(2);
fwrite($shell,'ls-al'.PHP_EOL);
//sleep(5);
while($line=fgets($shell)){
echo$line.'
';
}