Detailed explanation of how PHP uses ssh2 technology to achieve remote login and operate programs on the server

零到壹度
Release: 2023-03-21 22:20:01
Original
2271 people have browsed it

Since the work requires the visualization of a software running on the Linux side, I plan to visualize it based on the web. The problem that arises is how to seamlessly connect software in web and Linux across platforms. Fortunately, I saw a method that can achieve my needs using ssh2 technology.

My case is provided below:

First install the ssh2 package on the linux side, and then execute the linux command when needed , add the following code to the page running the Linux program:

<?php
$host=&#39;*******&#39;;//服务器的ip
$user=&#39;****&#39;;//用户名
$passwd=&#39;******&#39;;//密码
// 链接远程服务器
$connection = ssh2_connect($host, 22);
if (!$connection) die(&#39;connection to &#39;.$host.&#39;:22 failed&#39;);
echo &#39;connection OK<br/>&#39;;
// 获取验证方式并打印
$auth_methods = ssh2_auth_none($connection, $user);
print_r( $auth_methods.&#39;<br/>&#39;);
if (in_array(&#39;password&#39;, $auth_methods ))
{
// 通过password方式登录远程服务器
if (ssh2_auth_password($connection, $user, $passwd))
{
echo $user.&#39; login OK<br/>&#39;;
$stream = ssh2_exec($connection, "命令1&&命令2"); // 一条一条地执行linux命令
stream_set_blocking($stream, true); // 获取执行pwd后的内容
if ($stream === FALSE) die("pwd failed");
echo stream_get_contents($stream).&#39;<br/>&#39;;
}
else
{
die( $user.&#39; login Failed<br/>&#39;);
}
}
?>
Copy after login

Personal test is valid.

Related recommendations:

java remote login using ssh2 protocol

How to automatically execute after SSH2 remote login A script

The above is the detailed content of Detailed explanation of how PHP uses ssh2 technology to achieve remote login and operate programs on the server. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!