Python | 将本地文件上传到远程服务器
  ltERVYe6WHLK 2023年11月30日 15 0

在Python中,可以使用paramiko库来通过SSH进行文件的传输。

首先,你需要安装paramiko库,可以使用以下命令进行安装:

pip install paramiko

然后,你可以使用以下Python脚本进行文件传输:

此脚本使用SFTP协议进行文件传输。在SFTP的上下文中,你可以使用put方法将本地文件上传到远程服务器。

import paramiko

def upload_file(local_path, remote_path, hostname, username, password):
    # 创建 SSH 客户端
    client = paramiko.SSHClient()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

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

        # 使用 SFTP 协议创建一个传输通道
        with client.open_sftp() as sftp:
            # 上传本地文件到远程服务器
            sftp.put(local_path, remote_path)
            print(f"文件 {local_path} 已成功上传到 {remote_path}")

    except Exception as e:
        print(f"上传文件时发生错误: {e}")

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

# 本地文件路径
local_file_path = "/path/to/local/file.txt"

# 远程服务器信息
remote_server_hostname = "your_remote_server_ip"
remote_server_username = "your_username"
remote_server_password = "your_password"

# 远程文件路径
remote_file_path = "/path/to/remote/file.txt"

# 调用函数进行文件上传
upload_file(local_file_path, remote_file_path, remote_server_hostname, remote_server_username, remote_server_password)

确保替换示例中的 your_remote_server_ip、your_username、your_password 以及本地和远程文件路径为你实际使用的值。

此外,建议使用 SSH 密钥而不是密码进行身份验证,以提高安全性。

使用ssh.exec_command()执行指令,如下

rename_folder_command = f'mv today_folder_path yesterday_date'
ssh.exec_command(rename_folder_command)



【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月30日 0

暂无评论

推荐阅读
ltERVYe6WHLK