在 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 )
关于python - 如何在 Python 中进行 scp?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/250283/