php ssh 管理服务器,php 利用ssh执行远程或本地liunx服务器命令

/**

* 利用ssh执行 远程或本地liunx服务器命令

* 虽然可以用 shee_exec来执行本地机命令 但却无法选择用哪个用户来执行 此函数可解决此类问题

* $host ssh 主机名 可以为ip 或 域名

* $port ssh 端口

* $ssh_username ssh 登录用户名

* $ssh_password ssh 登录密码

* $command 要执行的liunx命令

* 反回值行结果和错误信息

*/

function ssh_exec($host, $port = 22, $ssh_username, $ssh_password, $command) {

$con = ssh2_connect($host, $port);

$auth_methods = ssh2_auth_none($con, $ssh_username);

if (in_array('password', $auth_methods)) {//是否允许使用密码登陆

$auth_methods = ssh2_auth_password($con, $ssh_username, $ssh_password);

}

$stdout_stream = ssh2_exec($con, $command);

$err_stream = ssh2_fetch_stream($stdout_stream, SSH2_STREAM_STDERR);

stream_set_blocking($stdout_stream, true); //阻塞执行

stream_set_blocking($err_stream, true);

$result_stdout = stream_get_contents($stdout_stream);

$result_error = stream_get_contents($err_stream);

fclose($stdout_stream);

fclose($err_stream);

return array('result' => $result_stdout, 'error' => $result_error);

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值