如何在Python中进行scp?

2024-01-07

在 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。

EDIT: 这是重复的如何使用 SCP 或 SSH 将文件复制到 Python 中的远程服务器? https://stackoverflow.com/questions/68335/how-do-i-copy-a-file-to-a-remote-server-in-python-using-scp-or-ssh. However,这个问题没有给出处理 Python 内部密钥的特定于 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')

Try the Paramiko 的 Python scp 模块 https://github.com/jbardin/scp.py。它非常容易使用。请参见以下示例:

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() or scp.put()进行 SCP 操作。

(SCP客户端代码 https://github.com/jbardin/scp.py/blob/master/scp.py)

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在Python中进行scp? 的相关文章

随机推荐