【问题标题】:Secure Copy File from remote server via scp and os module in Python通过 Python 中的 scp 和 os 模块从远程服务器安全复制文件
【发布时间】:2012-01-05 11:49:54
【问题描述】:

我对 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 和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

但我无法将命令发送到远程服务器(print test 显示,主机名 = 本地而不是远程服务器),但是我确定连接已建立。我认为建立连接比在 bash 命令中始终使用 "ssh " + hostname 更容易。我还尝试了How to copy a file to a remote server in Python using SCP or SSH? 中的一些解决方法,但我必须承认,由于缺乏经验,我没有让它们起作用。

非常感谢你帮助我。

【问题讨论】:

  • 为什么你认为你需要做ssh hostname scp?为什么不只是scp user@hostname:file localdirectory
  • 出于安全原因,首选subprocess 模块而不是os.system()
  • 我还没有考虑通过scp user@hostname:file localdirectory 复制的可能性。它确实有效,但只有当我取消 user@ 部分时。
  • 直到现在我才知道subprocess 模块,但我会考虑它(正如我所说我是python 和学习的新手,我需要一些时间来采用)跨度>

标签: python ssh scp


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2016-04-19
    • 2018-09-04
    • 2020-02-25
    • 2013-10-12
    • 2010-09-09
    • 2011-12-11
    • 1970-01-01
    • 2015-12-12
    • 1970-01-01
    相关资源
    最近更新 更多