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");
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值