import os
import paramiko
import stat
def get_allfile():
# 远程 Linux 主机的信息
host = "xxx.xxx.xxx.xxx"
port = 22 # 默认 SSH 端口
username = "xxx"
password = "123456"
# 远程文件路径
remote_base_path = "/opt/zzzz/zzz/"
# 本地文件路径
local_base_path = "D:\\xx\\share_files\\"
# 创建 SSH 客户端对象
client = paramiko.SSHClient()
# 允许连接未知的主机
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
def download_remote_dir(sftp, remote_dir, local_dir):
# 获取远程目录下的文件和子目录
dir_items = sftp.listdir_attr(remote_dir)
# 遍历目录项
for item in dir_items:
# 获取项目的完整路径
remote_item_path = os.path.join(remote_dir, item.filename)
local_item_path = os.path.join(local_dir, item.filename)
# 如果项目是目录,则递归下载子目录
if stat.S_ISDIR(item.st_mode):
os.makedirs(local_item_path, exist_ok=True)
download_remote_dir(sftp, remote_item_path, local_item_path)
# 如果项目是文件,则下载文件
elif stat.S_ISREG(item.st_mode):
try:
sftp.get(remote_item_path, local_item_path)
print(f"已下载文件:{local_item_path}")
except FileNotFoundError:
print(f"无法找到远程文件:{remote_item_path}")
try:
# 连接到远程主机
client.connect(hostname=host, port=port, username=username, password=password)
# 创建 SFTP 客户端对象
with client.open_sftp() as sftp:
# 递归下载远程目录
download_remote_dir(sftp, remote_base_path, local_base_path)
print("所有文件已下载到本地。")
finally:
# 关闭 SSH 连接
client.close()
while True:
get_allfile()
07-22
1049
06-25
2068
12-05
2万+
08-06
8540