Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

scp

ssh

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?

like image 304
chr0x Avatar asked Sep 19 '16 12:09

chr0x


1 Answers

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())
like image 118
Dinesh Pundkar Avatar answered Oct 20 '22 17:10

Dinesh Pundkar