【python】基于paramiko库的远程文件服务器FTP文件下载与上传

该博客介绍了如何使用Python的Paramiko库通过SSH协议进行远程文件服务器的文件上传和下载操作。首先讲解了模块的功能,包括执行SSH命令和文件传输。接着详细展示了File2Scp类的实现,包括构造方法、启动和关闭程序、上传目录和文件、创建目标路径等方法。最后提供了上传文件和下载文件的具体示例,方便读者理解和应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

【python】基于paramiko库的远程文件服务器FTP文件下载与上传

模块作用:

1、通过ssh协议远程执行命令
2、文件上传下载

安装
pip install paramiko
二次封装

File2Scp.py

import paramiko
import os
import stat
import datetime as dt

_XFER_FILE = 'FILE'
_XFER_DIR = 'DIR'

class File2Scp(object):
    # 构造方法
    def __init__(self):
        # 超类调用
        super(File2Scp, self).__init__()

        # 赋值参数[字典]
        self.arg  = {
   
   'ip':'填ip','user':'用户名','password':'123','port':22}
        # 赋值参数[FTP]
        self.sftp = None

        # 调试日志
        # print(self.arg)

    # 启动程序
    def startup(self):
        if self.sftp:
            print('connect success...')
        tmp_str = 'start connect...user name:' + self.arg['user'] + ' password:' + self.arg['password'] + ' IP:' + \
                  self.arg['ip'] + ' port:' + str(self.arg['port'])
        print(tmp_str)
        try:
            transport = paramiko.Transport((self.arg['ip'], self.arg['port']))
            transport.connect(
                username=self.arg['user'], password=self.arg['password'])
            self.sftp = paramiko.SFTPClient.from_transport(transport)
            print('connect success ' + self.arg['ip'])
        except Exception as e:
            print('connect success: ' + str(e))

    # 关闭程序
    def shutdown(self):
        # 关闭FTP
        if self.sftp:
            self.sftp.close(
### 使用Paramiko通过SSH执行命令下载文件 为了实现不依赖于FTP协议的远程文件下载,可以利用Python中的`paramiko`建立SSH连接并执行Linux命令来传输文件。具体来说,可以通过调用`exec_command()`方法运行诸如`cat`、`base64`编码解码等指令读取远端服务器上的文件内容,并将其保存到本地。 下面是一个完整的例子展示怎样使用`paramiko`获取远程主机上指定路径下的文本文件: ```python import paramiko from base64 import b64decode, b64encode def get_remote_file(hostname, port, username, password, remote_path): """Connects via SSH and retrieves a file from the server.""" client = paramiko.SSHClient() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) try: # Connect to the host client.connect(hostname=hostname, port=int(port), username=username, password=password) # Use cat command to read the content of the file on the remote machine. stdin, stdout, stderr = client.exec_command(f'cat {remote_path}') output = stdout.read().decode('utf-8') return output finally: client.close() if __name__ == '__main__': hostname = 'your.server.com' port = 22 username = 'user' password = 'pass' remote_filepath = '/path/to/remote/file.txt' result = get_remote_file( hostname=hostname, port=port, username=username, password=password, remote_path=remote_filepath ) with open('/local/path/to/save', 'w') as f: f.write(result) ``` 对于二进制文件,则建议先对其进行Base64编码再传回客户端处理,这样能有效防止数据损坏。以下是针对非纯ASCII字符集(比如图片或其他类型的二进制文件)的操作方式: ```python ... stdin, stdout, stderr = client.exec_command(f'base64 {remote_binary_path}') output = stdout.read().decode('ascii') decoded_data = b64decode(output.encode()) with open(local_binary_save_path, "wb") as binary_file: binary_file.write(decoded_data) ... ``` 上述脚本展示了如何安全有效地从远程机器拉取不同类型的数据而无需设置额外的服务如SFTP或SCP[^1]。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值