php或python使用ftp,sftp实现上传文件至远程服务器

1. ftp方式,必须开放21端口 yum install vsftp -y 即可 传到/home/xxxx目录

$fp = fopen ($localfile, "r");
// $arr_ip = gethostbyname(www.111cn.net);
$arr_ip = '192.168.1.115';
// echo $arr_ip;
$ftp = "ftp://".$arr_ip.'/home/assasin/test/'.$localfile; 
$ch = curl_init();
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_USERPWD, 'user:userpassword');
curl_setopt($ch, CURLOPT_URL, $ftp);
curl_setopt($ch, CURLOPT_PUT, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_INFILE, $fp);
curl_setopt($ch, CURLOPT_INFILESIZE, filesize($localfile));
$http_result = curl_exec($ch);
$error = curl_error($ch);
echo $error."<br>";
$http_code = curl_getinfo($ch ,CURLINFO_HTTP_CODE);
curl_close($ch);
fclose($fp);

2. sftp 方式 , 22端口 

class Sftp
{

    // 初始配置为NULL
    private $config = NULL;
    // 连接为NULL
    private $conn = NULL;
    // 初始化
    public function __construct($config)
    {
        $this->config = $config;
        $this->connect();
    }


    public function connect()
    {

        $this->conn = ssh2_connect($this->config['host'], $this->config['port']); //资源
        if( ssh2_auth_password($this->conn, $this->config['username'], $this->config['password']))
        {
			
        }else{
            echo "无法在服务器进行身份验证";
        }

    }

    // 传输数据 传输层协议,获得数据
    public function downftp($remote, $local)
    {
        $ressftp = ssh2_sftp($this->conn);
        return copy("ssh2.sftp://{$ressftp}".$remote, $local);
    }

    // 传输数据 传输层协议,写入ftp服务器数据
    public function upftp( $local,$remote, $file_mode = 0777)
    {
        $ressftp = ssh2_sftp($this->conn);
        return copy($local,"ssh2.sftp://{$ressftp}".$remote); 
    }

}




$config = array(
    'host' =>'192.168.1.115', //服务器
    'port' => '22', //端口
    'username' =>'user', //用户名
    'password' =>'userpassword', //密码
);

$ftp = new Sftp($config);
$localpath="D:/installed/phpstudy2016/WWW/php_homepage.txt"; //源文件地址
$serverpath='/home/assasin/test/234.txt'; //上传sftp地址
$st = $ftp->upftp($localpath,$serverpath); //上传指定文件
if($st == true){
    echo "success";

}else{
    echo "fail";
}

3. 依旧是sftp

class SFTPConnection{
    private $connection;
    private $sftp;

    public function __construct($host, $port=22)
    {
        $this->connection = @ssh2_connect($host, $port);
        if (! $this->connection)
            throw new Exception("Could not connect to $host on port $port.");
    }

    public function login($username, $password)
    {
        if (! @ssh2_auth_password($this->connection, $username, $password))
            throw new Exception("Could not authenticate with username $username " .
                                "and password $password.");

        $this->sftp = @ssh2_sftp($this->connection);
        if (! $this->sftp)
            throw new Exception("Could not initialize SFTP subsystem.");
    }

    public function uploadFile($local_file, $remote_file)
    {
        $sftp = $this->sftp;
        $stream = @fopen("ssh2.sftp://$sftp$remote_file", 'w');

        if (! $stream)
            throw new Exception("Could not open file: $remote_file");

        $data_to_send = @file_get_contents($local_file);
        if ($data_to_send === false)
            throw new Exception("Could not open local file: $local_file.");

        if (@fwrite($stream, $data_to_send) === false)
            throw new Exception("Could not send data from file: $local_file.");

        @fclose($stream);
    }
}

try
{
    $sftp = new SFTPConnection("192.168.1.115", 22);
    $sftp->login("user", "userpassword");
    $sftp->uploadFile("D:/installed/phpstudy2016/WWW/php_homepage.txt", "/home/assasin/test/1234.xlsx");
}
catch (Exception $e)
{
    echo $e->getMessage() . "\n";
}

3. python实现 方式一

import paramiko
 # 获取Transport实例
transport = paramiko.Transport('192.168.1.115',22)
 # 建立连接
transport.connect(username='user',password='userpassword')
 # 创建sftp对象,SFTPClient是定义怎么传输文件、怎么交互文件
sftp = paramiko.SFTPClient.from_transport(transport)
# 将本地20200605_Dailydata_KM.xlsx上传至服务器 /usr/local/ELK/123.xlsx 。文件上传并重命名为123.xlsx
sftp.put('D:/installed/phpstudy2016/WWW/php_homepage.txt','/usr/local/ELK/123.xlsx')
# 将服务器 /www/test.py 下载到本地 aaa.py。文件下载并重命名为aaa.py
sftp.get("/www/test.py", "E:/test/aaa.py")
# 关闭连接
transport.close()

4. 方式二

import paramiko
 
client = paramiko.SSHClient()   # 获取SSHClient实例
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect("192.168.1.115",  username="user", password="userpassword")  # 连接SSH服务端
transport = client.get_transport()   # 获取Transport实例
# 创建sftp对象,SFTPClient是定义怎么传输文件、怎么交互文件
sftp = paramiko.SFTPClient.from_transport(transport)
# 将本地 api.py 上传至服务器 /www/test.py。文件上传并重命名为test.py
sftp.put('D:/installed/phpstudy2016/WWW/php_homepage.txt','/usr/local/ELK/1234.xlsx')
# 将服务器 /www/test.py 下载到本地 aaa.py。文件下载并重命名为aaa.py
# sftp.get("/www/test.py", "E:/aaa.py")
# 关闭连接
client.close()

5. 该死的,封装一下啦

# -*- coding:utf-8 -*-
import paramiko
import uuid
 
class SSHConnection(object):
 
    def __init__(self, host='192.168.2.103', port=22, username='root',pwd='123456'):
        self.host = host
        self.port = port
        self.username = username
        self.pwd = pwd
        self.__k = None
 
    def connect(self):
        transport = paramiko.Transport((self.host,self.port))
        transport.connect(username=self.username,password=self.pwd)
        self.__transport = transport
 
    def close(self):
        self.__transport.close()
 
    def upload(self,local_path,target_path):
        # 连接,上传
        # file_name = self.create_file()
        sftp = paramiko.SFTPClient.from_transport(self.__transport)
        # 将location.py 上传至服务器 /tmp/test.py
        sftp.put(local_path, target_path)
 
    def download(self,remote_path,local_path):
        sftp = paramiko.SFTPClient.from_transport(self.__transport)
        sftp.get(remote_path,local_path)
 
    def cmd(self, command):
        ssh = paramiko.SSHClient()
        ssh._transport = self.__transport
        # 执行命令
        stdin, stdout, stderr = ssh.exec_command(command)
        # 获取命令结果
        result = stdout.read()
        print (str(result,encoding='utf-8'))
        return result
 
ssh = SSHConnection()
ssh.connect()
ssh.cmd("ls")
ssh.upload('s1.py','/tmp/ks77.py')
ssh.download('/tmp/test.py','kkkk',)
ssh.cmd("df")
ssh.close()


 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值