大白兔联盟

文章搜索
搜索
当前位置:首页 > 前沿技术 > 编程技术 > 文章详情

php实现ssh远程连接服务器并操作服务器

大白兔    2023-4-24  308  0评论

前言

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

免责声明

本站提供的一切软件、教程和内容信息仅限用于学习和研究目的;不得将上述内容用于商业或者非法用途,否则,一切后果请用户自负。本站信息来自网络收集整理,版权争议与本站无关。您必须在下载后的24个小时之内,从您的电脑或手机中彻底删除上述内容。如果您喜欢该程序和内容,请支持正版,购买注册,得到更好的正版服务。我们非常重视版权问题,如有侵权请邮件与我们联系处理。敬请谅解!

挤眼 亲亲 咆哮 开心 想想 可怜 糗大了 委屈 哈哈 小声点 右哼哼 左哼哼 疑问 坏笑 赚钱啦 悲伤 耍酷 勾引 厉害 握手 耶 嘻嘻 害羞 鼓掌 馋嘴 抓狂 抱抱 围观 威武 给力
提交评论

清空信息
关闭评论