Best way to do file transfer via SCP using python and a .pem file

15,039

Try to use paramiko module.

Check here for connect function in paramiko which has key_filename argument.

In paramiko module, there is SFTP command which you can use to transfer file.

Check here for SFTP info.

Demo code will looks like below:

import paramiko

client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

client.connect(<IP Address>, username=<User Name>, key_filename=<.PEM File path)

# Setup sftp connection and transmit this script
#print "copying"
sftp = client.open_sftp()
sftp.put(<Source>, <Destination>)
sftp.close()

**

OR

**

You can execute above command directly using python directly.

Please check this link how to execute command in python.

Demo code:

from subprocess import call
cmd = 'scp -i aKey.pem aFile.txt ec2-user@serverIp:folder'
call(cmd.split())
Share:
15,039
chr0x
Author by

chr0x

Updated on June 12, 2022

Comments

  • chr0x
    chr0x almost 2 years

    I wanna to replicate that command in python:

    scp -i aKey.pem aFile.txt ec2-user@serverIp:folder
    

    I found some examples of SCP but didn't found neither using a .pem key, and without informing the user password. How can I make this in python?