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

迈不过友情╰ 2023-02-15 10:26 41阅读 0赞
  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.”
    “;
    $http_code = curl_getinfo($ch ,CURLINFO_HTTP_CODE);
    curl_close($ch);
    fclose($fp);

  2. sftp 方式 , 22端口

    class Sftp
    {

    1. // 初始配置为NULL
    2. private $config = NULL;
    3. // 连接为NULL
    4. private $conn = NULL;
    5. // 初始化
    6. public function __construct($config)
    7. {
    8. $this->config = $config;
    9. $this->connect();
    10. }
  1. public function connect()
  2. {
  3. $this->conn = ssh2_connect($this->config['host'], $this->config['port']); //资源
  4. if( ssh2_auth_password($this->conn, $this->config['username'], $this->config['password']))
  5. {
  6. }else{
  7. echo "无法在服务器进行身份验证";
  8. }
  9. }
  10. // 传输数据 传输层协议,获得数据
  11. public function downftp($remote, $local)
  12. {
  13. $ressftp = ssh2_sftp($this->conn);
  14. return copy("ssh2.sftp://{$ressftp}".$remote, $local);
  15. }
  16. // 传输数据 传输层协议,写入ftp服务器数据
  17. public function upftp( $local,$remote, $file_mode = 0777)
  18. {
  19. $ressftp = ssh2_sftp($this->conn);
  20. return copy($local,"ssh2.sftp://{$ressftp}".$remote);
  21. }
  22. }
  23. $config = array(
  24. 'host' =>'192.168.1.115', //服务器
  25. 'port' => '22', //端口
  26. 'username' =>'user', //用户名
  27. 'password' =>'userpassword', //密码
  28. );
  29. $ftp = new Sftp($config);
  30. $localpath="D:/installed/phpstudy2016/WWW/php_homepage.txt"; //源文件地址
  31. $serverpath='/home/assasin/test/234.txt'; //上传sftp地址
  32. $st = $ftp->upftp($localpath,$serverpath); //上传指定文件
  33. if($st == true){
  34. echo "success";
  35. }else{
  36. echo "fail";
  37. }
  1. 依旧是sftp

    class SFTPConnection{

    1. private $connection;
    2. private $sftp;
    3. public function __construct($host, $port=22)
    4. {
    5. $this->connection = @ssh2_connect($host, $port);
    6. if (! $this->connection)
    7. throw new Exception("Could not connect to $host on port $port.");
    8. }
    9. public function login($username, $password)
    10. {
    11. if (! @ssh2_auth_password($this->connection, $username, $password))
    12. throw new Exception("Could not authenticate with username $username " .
    13. "and password $password.");
    14. $this->sftp = @ssh2_sftp($this->connection);
    15. if (! $this->sftp)
    16. throw new Exception("Could not initialize SFTP subsystem.");
    17. }
    18. public function uploadFile($local_file, $remote_file)
    19. {
    20. $sftp = $this->sftp;
    21. $stream = @fopen("ssh2.sftp://$sftp$remote_file", 'w');
    22. if (! $stream)
    23. throw new Exception("Could not open file: $remote_file");
    24. $data_to_send = @file_get_contents($local_file);
    25. if ($data_to_send === false)
    26. throw new Exception("Could not open local file: $local_file.");
    27. if (@fwrite($stream, $data_to_send) === false)
    28. throw new Exception("Could not send data from file: $local_file.");
    29. @fclose($stream);
    30. }

    }

    try
    {

    1. $sftp = new SFTPConnection("192.168.1.115", 22);
    2. $sftp->login("user", "userpassword");
    3. $sftp->uploadFile("D:/installed/phpstudy2016/WWW/php_homepage.txt", "/home/assasin/test/1234.xlsx");

    }
    catch (Exception $e)
    {

    1. echo $e->getMessage() . "\n";

    }

  2. 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()

  3. 方式二

    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()

  4. 该死的,封装一下啦

    -- coding:utf-8 --

    import paramiko
    import uuid

    class SSHConnection(object):

    1. def __init__(self, host='192.168.2.103', port=22, username='root',pwd='123456'):
    2. self.host = host
    3. self.port = port
    4. self.username = username
    5. self.pwd = pwd
    6. self.__k = None
    7. def connect(self):
    8. transport = paramiko.Transport((self.host,self.port))
    9. transport.connect(username=self.username,password=self.pwd)
    10. self.__transport = transport
    11. def close(self):
    12. self.__transport.close()
    13. def upload(self,local_path,target_path):
    14. # 连接,上传
    15. # file_name = self.create_file()
    16. sftp = paramiko.SFTPClient.from_transport(self.__transport)
    17. # 将location.py 上传至服务器 /tmp/test.py
    18. sftp.put(local_path, target_path)
    19. def download(self,remote_path,local_path):
    20. sftp = paramiko.SFTPClient.from_transport(self.__transport)
    21. sftp.get(remote_path,local_path)
    22. def cmd(self, command):
    23. ssh = paramiko.SSHClient()
    24. ssh._transport = self.__transport
    25. # 执行命令
    26. stdin, stdout, stderr = ssh.exec_command(command)
    27. # 获取命令结果
    28. result = stdout.read()
    29. print (str(result,encoding='utf-8'))
    30. 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 条评论,41人围观)

还没有评论,来说两句吧...

相关阅读