如何使用SSH密钥编写Python Paramiko SFTP

问题描述

我已经写了一个,它在python中有一个主要方法,该方法有很多创建文件的操作。 现在,我想对该文件进行SFTP传输,并将其从本地服务器发送到远程服务器。 有谁能帮助我如何在python中添加方法,该方法将首先执行main方法,然后执行用于SFTP的paramiko方法。请为此教我一个简单的代码。我非常困惑!

解决方法

下面是将内容写入文件并通过sftp将其内容发送到远程服务器的示例

import paramiko
import os
paramiko.util.log_to_file("paramiko.log")

# Open a transport
def sftp_transport():
    host,port = "example.com",22
    transport = paramiko.Transport((host,port))

    # Auth
    username,password = "foo","foo"
    transport.connect(None,username,password)

    # Go!
    sftp = paramiko.SFTPClient.from_transport(transport)

    # Upload
    filepath = "/home/foo.jpg"
    localpath = os.path.join('C:\\','Users','example','desktop','example.txt')
    sftp.put(localpath,filepath)

    # Close
    if sftp: sftp.close()
    if transport: transport.close()

def write_file():
    localpath = os.path.join('C:\\','example.txt')
    f = open(localpath,'w')
    f.write("Now the file has some content!")
    f.close()

write_file()
sftp_transport()
,
import paramiko


def upload_file(remote_server,ssh_user,ssh_password,local_filepath,remote_path,port_number=22):
    sftp = None
    transport = None

    try:
        # Create transport instance and setup SFTP connection
        transport = paramiko.Transport((remote_server,port_number))
        transport.connect(None,ssh_password)
        sftp = paramiko.SFTPClient.from_transport(transport)

        # Upload file to remote destination
        sftp.put(local_filepath,remote_path)
    except Exception as e:
        print(f'Failed to transfer files: {e}')
        if sftp:
            sftp.close()
        if transport:
            transport.close()

示例调用

upload_file("10.197.15.1","ssh_user","ssh_password","/tmp/myfile.txt","/home/user/sftp/myfile.txt")