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

2024-09-30 16:25:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我对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 = e.g. ls

当我试着 ssh hostname scp file user@local:directory 在命令行中,它不需要输入密码就可以工作。

我尝试将os.popen命令与getpass和pxsh模块结合起来,建立到远程服务器的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

但是我无法将命令传递到远程服务器(print test显示hostname=local而不是远程服务器),但是我确信,连接已经建立。我认为建立连接比总是在bash命令中使用"ssh " + hostname更容易。我也尝试了How to copy a file to a remote server in Python using SCP or SSH?中的一些解决方法,但我必须承认,由于缺乏有效期,我没有让他们工作。

非常感谢你帮助我。


Tags: totest命令服务器远程ospasswordssh
1条回答
网友
1楼 · 发布于 2024-09-30 16:25:37

我认为最简单(避免输入密码)和最安全的方法是首先设置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])])

相关问题 更多 >