Python连接sftp指定端口并下载文件脚本

目标:

python如何实现连接sftp指定端口并下载.gz文件到指定目录,再解压后将.bat文件后缀替换成.csv

import os
import paramiko
import gzip
import shutil

# SFTP 连接信息
hostname = 'example.com'
port = 2222
username = 'your_username'
password = 'your_password'
remote_path = '/path/to/file.gz'
local_directory = '/path/to/save/files/'


# 连接 SFTP
transport = paramiko.Transport((hostname, port))
transport.connect(username=username, password=password)
sftp = paramiko.SFTPClient.from_transport(transport)

# 判断远程文件夹是否存在 .ok 文件
file_list = sftp.listdir(remote_path)
if '.ok' not in file_list:
    print("远程文件夹中不存在 .ok 文件")
    sftp.close()
    transport.close()
    exit()

# 下载文件
local_filename = os.path.join(local_directory, os.path.basename(remote_path))
sftp.get(remote_path, local_filename)

# 解压文件
output_filename = os.path.splitext(local_filename)[0]  # 去除后缀 .gz
with gzip.open(local_filename, 'rb') as f_in:
    with open(output_filename, 'wb') as f_out:
        shutil.copyfileobj(f_in, f_out)

# 后缀替换
new_filename = os.path.splitext(output_filename)[0] + '.csv'  # 将 .bat 替换为 .csv
os.rename(output_filename, new_filename)

# 关闭连接
sftp.close()
transport.close()

【拓展】
windows连接sftp的命令

sftp -oPort=port username@hostname

你可能感兴趣的:(Python,python,开发语言)