前言
- 如何使用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");
|