php实现ssh远程连接服务器并操作服务器
# 前言* 如何使用php执行本地命令这个肯定大部分会php的朋友都知道,比如:exec函数、shell_exec函数等,但是如果我想执行远程服务器的命令呢?
## 代码
```
class CustomSsh{
protected $host;
protected $port = 22;
protected $password;
protected $publicKey;
protected $privateKey;
protected $session;
protected $username;
public function __construct(array $config,$connect_type='password'){
$this->host = $config['host'];
$this->port = $config['port']??22;
$this->password = $config['password']??'';
$this->publicKey = $config['publicKey'] ?? '';
$this->privateKey = $config['privateKey'] ?? '';
$this->username = $config['username'] ?? '';
$this->session = ssh2_connect($this->host, $this->port);
if($connect_type == 'password'){
ssh2_auth_password($this->session, $this->username, $this->password);
}else{
ssh2_auth_pubkey_file($this->session,$this->username,$this->publicKey,$this->privateKey);
}
}
public function execute($cmd){
if($cmd == ""){
return false;
}
$stream = ssh2_exec($this->session, $cmd);
stream_set_blocking($stream, true);
$content =stream_get_contents($stream);
return trim($content);
}
//接收文件
public function recvFile($remote_file,$local_file){
return ssh2_scp_recv($this->session, $remote_file, $local_file);
}
//发送文件
public function sendFile($local_file,$remote_file){
return ssh2_scp_send($this->session, $local_file, $remote_file);
}
public function __destruct(){
ssh2_disconnect($this->session);
}
}
$config = [
'host' => '',
'port' => '',
'publicKey' => "",
'privateKey' => "",
'username' => ""
];
$customSsh = new CustomSsh($config,'publicKey');
echo $customSsh->execute("cd /data/web/ && ls -la");
$customSsh->recvFile("/a.txt","/a.txt");
``` smile1110 发表于 2023-4-23 18:40
不错,可惜大家都是用浏览器插件连接ssh。
什么插件嘞 不错,可惜大家都是用浏览器插件连接ssh。 多谢分享,学习。 忘川川 发表于 2023-4-23 21:39
什么插件嘞
我们都用大马! 感谢分享 多谢分享!! 以前的马 就可以操作
感谢分享 受益匪浅
页:
[1]
2