5

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?

chr0x
  • 1,151
  • 3
  • 15
  • 25

1 Answers1

8

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())
Community
  • 1
  • 1
Dinesh Pundkar
  • 4,160
  • 1
  • 23
  • 37