python语言,实现本地文件传送到远程服务器

import paramiko
import os

# 配置远程服务器信息
hostname = '192.168.101.130'
port = 22  # 默认SSH端口
username = 'root'
password = '123456'  
def scp_upload_file(local_path, remote_path):
    # 创建SSH客户端
    client = paramiko.SSHClient()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

    try:
        # 连接到远程服务器
        client.connect(hostname, port, username, password)

        # 使用SCP协议上传文件
        with client.open_sftp() as sftp:
            sftp.put(local_path, remote_path)

        print(f"文件 '{local_path}' 传输到远程服务器成功,存储为 '{remote_path}'")

    except Exception as e:
        print(f"文件传输失败: {str(e)}")

    finally:
        # 关闭SSH连接
        client.close()

def scp_upload_folder(local_folder_path, remote_folder_path):
    # 创建SSH客户端
    client = paramiko.SSHClient()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

    try:
        # 连接到远程服务器
        client.connect(hostname, port, username, password)

        # 创建远程文件夹(如果不存在)
        client.exec_command(f'mkdir -p {remote_folder_path}')

        # 递归复制本地文件夹到远程服务器
        with client.open_sftp() as sftp:
            for foldername, subfolders, filenames in os.walk(local_folder_path):
                for filename in filenames:
                    local_file_path = os.path.join(foldername, filename)
                    remote_file_path = os.path.join(
                        remote_folder_path, os.path.relpath(local_file_path, local_folder_path))
                    sftp.put(local_file_path, remote_file_path)

        print(f"文件夹 '{local_folder_path}' 传输到远程服务器成功,存储为 '{remote_folder_path}'")

    except Exception as e:
        print(f"文件夹传输失败: {str(e)}")

    finally:
        # 关闭SSH连接
        client.close()

# 例子:传输文件
local_file_path = 'test.py'
remote_file_path = '/www/wwwroot/python/test.py'
scp_upload_file(local_file_path, remote_file_path)

# 例子:传输文件夹
local_folder_path = './cache'
remote_folder_path = '/www/wwwroot/python/cache'
scp_upload_folder(local_folder_path, remote_folder_path)


  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值