Secure copy file from remote server via scp and os module in Python

I am new to Python and programming. I am trying to copy a file between two computers through a python script. However code

os.system("ssh " + hostname + " scp " + filepath + " " + user + "@" + localhost + ":" cwd)

will not work. I think he needs a password, as described in How to copy a file to a remote server in Python using SCP or SSH? . I did not receive any error logs, the file simply will not appear in my current working directory.

However, any other command with os.system("ssh " + hostname + "command")or os.popen("ssh " + hostname + "command")works. command = e.g. ls

When I try ssh hostname scp file user@local:directory on the command line it works without entering a password.

I tried combining the commands os.popenwith the getpass and pxssh modules to establish an ssh connection to the remote server and use it to send commands directly (I just checked it for an easy command):

import pxssh
import getpass

ssh = pxssh.pxssh()
ssh.force_password = True
hostname = raw_input("Hostname: ")
user = raw_input("Username: ")
password = getpass.getpass("Password: ")
ssh.login(hostname, user, password)
test = os.popen("hostname")
print test

But I can’t pass the commands to the remote server (it print testshows that the hostname = local, not the remote server), however I am sure that the connection is established. I thought it would be easier to establish a connection than always use "ssh " + hostnamein bash commands. I also tried some of the workarounds in How to copy a file to a remote server in Python using SCP or SSH? but I have to admit that due to lack of experience I didn’t make them work.

Thanks for helping me.

+5
1

, ( ), - / . , , ssh user@hostname, bash :

scp some/complete/path/to/file user@remote_system:some/remote/path

Python :

import subprocess

filepath = "some/complete/path/to/file"
hostname = "user@remote_system"
remote_path = "some/remote/path"

subprocess.call(['scp', filepath, ':'.join([hostname,remote_path])])
+3

All Articles