php 使用秘钥登录sftp

话不多说,直接上代码!

<?php

class Sftp
{
    // 初始配置为NULL
    private $config =NULL ;

    // 连接为NULL
    private $conn = NULL;

    // 是否使用秘钥登陆
    private $use_pubkey_file= true;

    //sftp resource
    private $ressftp = NULL;

    // 初始化
    public function init($config){
        $this->config = $config ;
    }
    // 连接ssh ,连接有两种方式(1) 使用密码
    // (2) 使用秘钥
    public function connect(){
        $methods['hostkey'] = $this->use_pubkey_file ? 'ssh-rsa' : [] ;
        $this->conn = ssh2_connect($this->config['host'], $this->config['port'], $methods);
        //(1) 使用秘钥的时候
        if($this->use_pubkey_file){
            // 用户认证协议
            $rc = ssh2_auth_pubkey_file($this->conn,$this->config['user'],$this->config['pubkey_file'],$this->config['privkey_file'],$this->config['passphrase']);
            $this->ressftp = ssh2_sftp($this->conn);
        }else{
            //(2) 使用登陆用户名字和登陆密码
            $rc = ssh2_auth_password( $this->conn, $this->config['user'],$this->config['passwd']);
            $this->ressftp = ssh2_sftp($this->conn);
        }
        return $rc ;
    }

    // 文件上传
    public function upftp( $local,$remote, $file_mode = 0777)
    {
        return copy($local,"ssh2.sftp://{$this->ressftp}".$remote);
        // return ssh2_scp_send($this->ressftp,$local,$remote,$file_mode); 
    }
    //创建目录
    public function ssh2_sftp_mchkdir($path)  //使用创建目录循环
    {
        ssh2_sftp_mkdir($this->ressftp, $path,0777,true);
    }
    //判段目录是否存在
    public function ssh2_dir_exits($dir){
        return file_exists("ssh2.sftp://{$this->ressftp}".$dir);
    }
}

调用代码

$handle = new Sftp();
$handle->init($config);
$handle->connect();
$re = $handle->ssh2_dir_exits($serverPath);

//如果目录存在直接上传
if($re){
    $handle->upftp("$localPath",$serverPath.$date);
}else{
    $handle->ssh2_sftp_mchkdir($serverPath);
    $handle->upftp("$localPath",$serverPath.$date);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值