由于工作需要将一个在linux端运行的软件可视化,打算基于web的形式将其可视化。带来的问题是如何跨平台无缝衔接web和linux中的软件,有幸的看到一个方法,利用ssh2技术即可实现我的需求。
下面提供我的案例:
首先在linux端安装ssh2包,然后在需要执行linux命令,运行linux端程序的页面加入以下代码:
$host='*******';//服务器的ip
$user='****';//用户名
$passwd='******';//密码
// 链接远程服务器
$connection = ssh2_connect($host, 22);
if (!$connection) die('connection to '.$host.':22 failed');
echo 'connection OK
';
// 获取验证方式并打印
$auth_methods = ssh2_auth_none($connection, $user);
print_r( $auth_methods.'
');
if (in_array('password', $auth_methods ))
{
// 通过password方式登录远程服务器
if (ssh2_auth_password($connection, $user, $passwd))
{
echo $user.' login OK
';
$stream = ssh2_exec($connection, "命令1&&命令2"); // 一条一条地执行linux命令
stream_set_blocking($stream, true); // 获取执行pwd后的内容
if ($stream === FALSE) die("pwd failed");
echo stream_get_contents($stream).'
';
}
else
{
die( $user.' login Failed
');
}
}
?>
亲测有效。
相关推荐: