Linux虚拟机文件同步到本地

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值