吾爱破解 - LCG - LSG |安卓破解|病毒分析|www.52pojie.cn

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

查看: 1953|回复: 15
收起左侧

[其他原创] php实现ssh远程连接服务器并操作服务器

  [复制链接]
fengxiaoxiao7 发表于 2023-4-23 16:15

前言

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

免费评分

参与人数 3吾爱币 +5 热心值 +3 收起 理由
scottlee1008 + 1 + 1 感谢发布原创作品,吾爱破解论坛因你更精彩!
smile1110 + 3 + 1 热心回复!
blindcat + 1 + 1 欢迎分析讨论交流,吾爱破解论坛有你更精彩!

查看全部评分

发帖前要善用论坛搜索功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。

忘川川 发表于 2023-4-23 21:39
smile1110 发表于 2023-4-23 18:40
不错,可惜大家都是用浏览器插件连接ssh。

什么插件嘞

点评

我们都用大马!  详情 回复 发表于 2023-4-24 03:55
smile1110 发表于 2023-4-23 18:40
apull 发表于 2023-4-23 19:30
smile1110 发表于 2023-4-24 03:55

我们都用大马!
头像被屏蔽
tl;dr 发表于 2023-4-24 05:49
提示: 作者被禁止或删除 内容自动屏蔽
scbzwv 发表于 2023-4-24 08:04
感谢分享
tcog 发表于 2023-4-24 08:25
多谢分享!!
wychashe 发表于 2023-4-24 08:29
以前的马 就可以操作
houzhifeng00 发表于 2023-4-24 11:02
感谢分享   受益匪浅
您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则 警告:本版块禁止灌水或回复与主题无关内容,违者重罚!

快速回复 收藏帖子 返回列表 搜索

RSS订阅|小黑屋|处罚记录|联系我们|吾爱破解 - LCG - LSG ( 京ICP备16042023号 | 京公网安备 11010502030087号 )

GMT+8, 2024-5-1 17:29

Powered by Discuz!

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表