通过Python中的scp和os模块从远程服务器安全复制文件

我是Python和编程的新手.我正在尝试通过python脚本在两台计算机之间复制文件.但是代码

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

不行.我认为它需要一个密码,如How to copy a file to a remote server in Python using SCP or SSH?中所述.我没有得到任何错误日志,该文件不会显示在我当前的工作目录中.

但是,使用os.system(“ssh”hostname“command”)或os.popen(“ssh”hostname“command”)的所有其他命令都可以正常工作. – > command =例如LS

当我尝试
ssh hostname scp文件user @ local:directory
在命令行中它无需输入密码即可运行.

我尝试将os.popen命令与getpass和pxssh模块结合起来建立与远程服务器的ssh连接,并使用它直接发送命令(我只测试它以获得简单的命令):

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

但是我无法将命令传递到远程服务器(打印测试显示,hostname = local而不是远程服务器),但是我确信,连接已经建立.我认为建立连接比在bash命令中始终使用“ssh”主机名更容易.我还尝试了How to copy a file to a remote server in Python using SCP or SSH?中的一些变通方法,但我必须承认,由于缺乏经验,我没有让它们工作.

非常感谢帮助我.

最佳答案
我认为最简单的(避免输入密码)和最安全的方法是首先设置public/private key authentication.一旦完成,你可以通过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])])

相关文章

Python中的函数(二) 在上一篇文章中提到了Python中函数的定...
Python中的字符串 可能大多数人在学习C语言的时候,最先接触...
Python 面向对象编程(一) 虽然Python是解释性语言,但是它...
Python面向对象编程(二) 在前面一篇文章中谈到了类的基本定...
Python中的函数(一) 接触过C语言的朋友对函数这个词肯定非...
在windows下如何快速搭建web.py开发框架 用Python进行web开发...