23

I am using Python's paramiko packet to keep an ssh-connection with an server :

s = paramiko.SSHClient()
s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
s.connect("xxx.xxx.xxx.xxx",22,username=xxx,password='',timeout=4)

I want to use this ssh-connection to transfer a file to ssh server, how can i do?

Just like use scp a-file xxx@xxx.xxx.xxx.xxx:filepath command?

pylover
  • 7,670
  • 8
  • 51
  • 73
Coaku
  • 977
  • 1
  • 9
  • 23

2 Answers2

28

Try this:

s = paramiko.SSHClient()
s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
s.connect("xxx.xxx.xxx.xxx",22,username=xxx,password='',timeout=4)

sftp = s.open_sftp()
sftp.put('/home/me/file.ext', '/remote/home/file.ext')
Tisho
  • 8,320
  • 6
  • 44
  • 52
  • The answer is correct regarding the upload itself. – But using of `AutoAddPolicy` this way has security consequences. You are losing a protection against [MITM attacks](https://en.wikipedia.org/wiki/Man-in-the-middle_attack) by doing so. For the correct solution, see [Paramiko “Unknown Server”](https://stackoverflow.com/q/10670217/850848#43093883). – Martin Prikryl Aug 27 '20 at 07:28
2

Here is another example from https://www.programcreek.com/python/example/4561/paramiko.SSHClient

def copy_file(hostname, port, username, password, src, dst):
    client = paramiko.SSHClient()
    client.load_system_host_keys()
    print (" Connecting to %s \n with username=%s... \n" %(hostname,username))
    t = paramiko.Transport(hostname, port)
    t.connect(username=username,password=password)
    sftp = paramiko.SFTPClient.from_transport(t)
    print ("Copying file: %s to path: %s" %(src, dst))
    sftp.put(src, dst)
    sftp.close()
    t.close() 
Andy
  • 434
  • 5
  • 7