300字范文,内容丰富有趣,生活中的好帮手!
300字范文 > php写ssh命令行_php使用ssh2来操作服务器执行命令

php写ssh命令行_php使用ssh2来操作服务器执行命令

时间:2021-11-09 12:02:19

相关推荐

php写ssh命令行_php使用ssh2来操作服务器执行命令

方法一(推荐)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.'

';

}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。