python - 如何在 Python 中进行 scp?

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

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

这是一种 hack,在类似 Linux 的系统之外无法使用,并且需要 Pexpect 模块的帮助以避免密码提示,除非您已经为远程主机设置了无密码 SSH。

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

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

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

编辑: 这是 How to copy a file to a remote server in Python using SCP or SSH? 的副本. 但是,该问题没有给出处理 Python 内部 key 的特定于 scp 的答案。我希望有一种方法来运行类似的代码

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')

最佳答案

试试 Python scp module for Paramiko .它非常易于使用。请参阅以下示例:

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操作。

( SCPClient code )

https://stackoverflow.com/questions/250283/

相关文章:

c - 如何使用 GDB 修改内存内容?

linux - Shell - 将变量内容写入文件

python - Anaconda 与 miniconda

python - 如何在 Windows 上使用 Python 3 连接到 MySQL?

linux - 如何 RSYNC 单个文件?

python - 在批处理文件中休眠

python - 打印 Python 类的所有属性

linux - shell脚本杀死监听端口3000的进程?

c - 如何在linux c程序中获取pthread的线程ID?

python - 在 IPython 中自动重新加载模块