How to write the Python Paramiko SFTP using SSH keys

Viewed 4292

I have already written a which has a main method in python which has many operations to create a file. Now i want to SFTP that file and send it to an remote server from an local server. Can I anyone please assist me how to add an method in python which will first execute the main method and then execute the paramiko method for SFTP purpose. Please teach me a simple code for this. I am very much confused!

2 Answers
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_user, 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()

Sample Invocation

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

Below is example of writing content to a file and sftp the same to remote server

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:\\', 'Users', 'example', 'desktop','example.txt')
    f = open(localpath, 'w')
    f.write("Now the file has some content!")
    f.close()

write_file()
sftp_transport()
Related