| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118 | <?php/** * Suco_ssh 工厂类 * Created by PhpStorm. * User: vanshao * Date: 2018/11/15 * Time: 上午11:47 */namespace App\Libs;class Ssh{    /**     * ssh 用户名     * @var integer     */    protected static $_root;    /**     * ssh 密码     * @var string     */    protected static $_pwd;    protected static $_port = 22;    /**     * ssh IP     * @var string     */    protected static $_ip;    protected static $_connection;    /**     * @param $_ip     * @param $_root     * @param $_pwd     * @return bool     */    public static function factory($_ip, $_root, $_pwd)    {        if (empty($_ip) || empty($_root) || empty($_pwd)) {            return false;        }        self::$_connection = ssh2_connect($_ip, self::$_port);        if (!ssh2_auth_password(self::$_connection, $_root, $_pwd)) {            return false;        }        return true;    }//    protected static $sftp_resource;////    public static function sftp()//    {//        self::$sftp_resource = ssh2_sftp(self::$_connection);//    }////    public static function sftp_mkdir($dir)//    {//        return ssh2_sftp_mkdir(self::$sftp_resource, $dir);//    }    /**     * 远程执行命令     * @param $cmd     * @return bool|string     */    public static function exec($cmd)    {        $ret = ssh2_exec(self::$_connection, $cmd);        // 获取结果        stream_set_blocking($ret, true);        // 返回结果        return stream_get_contents($ret);    }    /**     * 本地复制到运程     * @param $local_file     * @param $remote_file     * @return bool     */    public static function send($local_file, $remote_file)    {        return ssh2_scp_send(self::$_connection, $local_file, $remote_file);    }    /**     * 远程复制到本地     * @param $remote_file     * @param $local_file     * @return bool     */    public static function receive($remote_file, $local_file)    {        return ssh2_scp_recv(self::$_connection, $remote_file, $local_file);    }    public static function dir_exists($dir)    {        $cmd = sprintf('if [ -d "%s" ]; then echo 1; else echo 0; fi', $dir);        return substr(self::exec($cmd), 0, 1);    }    public static function mkdir($dir)    {        $cmd = sprintf('mkdir -p %s', $dir);        return substr(self::exec($cmd), 0, 1);    }}
 |