如何在 Python 中 scp? [英] How to scp in Python?

查看:67
本文介绍了如何在 Python 中 scp?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Python 中 scp 文件的最 Pythonic 方法是什么?我知道的唯一路线是

What's the most pythonic way to scp a file in Python? The only route I'm aware of is

os.system('scp "%s" "%s:%s"' % (localfile, remotehost, remotefile) )

这是一个 hack,它不能在类 Linux 系统之外工作,并且需要 Pexpect 模块的帮助以避免密码提示,除非您已经为远程主机设置了无密码 SSH.

which is a hack, and which doesn't work outside Linux-like systems, and which needs help from the Pexpect module to avoid password prompts unless you already have passwordless SSH set up to the remote host.

我知道 Twisted 的 conch,但我更愿意避免自己通过低级 ssh 模块实现 scp.

I'm aware of Twisted's conch, but I'd prefer to avoid implementing scp myself via low-level ssh modules.

我知道 paramiko,一个支持 SSH 和 SFTP 的 Python 模块;但它不支持SCP.

I'm aware of paramiko, a Python module that supports SSH and SFTP; but it doesn't support SCP.

背景:我正在连接一个不支持 SFTP 但支持 SSH/SCP 的路由器,因此 SFTP 不是一个选项.

Background: I'm connecting to a router which doesn't support SFTP but does support SSH/SCP, so SFTP isn't an option.

编辑:这是 如何使用 SCP 或 SSH 在 Python 中将文件复制到远程服务器?.然而,这个问题并没有给出特定于 scp 的答案来处理 Python 中的键.我希望有一种运行代码的方法

EDIT: This is a duplicate of How to copy a file to a remote server in Python using SCP or SSH?. However, that question doesn't give an scp-specific answer that deals with keys from within Python. I'm hoping for a way to run code kind of like

import scp

client = scp.Client(host=host, user=user, keyfile=keyfile)
# or
client = scp.Client(host=host, user=user)
client.use_system_keys()
# or
client = scp.Client(host=host, user=user, password=password)

# and then
client.transfer('/etc/local/filename', '/etc/remote/filename')

推荐答案

尝试 Paramiko 的 Python scp 模块.它非常容易使用.请参见以下示例:

Try the Python scp module for Paramiko. It's very easy to use. See the following example:

import paramiko
from scp import SCPClient

def createSSHClient(server, port, user, password):
    client = paramiko.SSHClient()
    client.load_system_host_keys()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    client.connect(server, port, user, password)
    return client

ssh = createSSHClient(server, port, user, password)
scp = SCPClient(ssh.get_transport())

然后调用scp.get()scp.put()进行SCP操作.

Then call scp.get() or scp.put() to do SCP operations.

(SCP客户端代码)

这篇关于如何在 Python 中 scp?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆