在Python中scp文件的最具Python风格的方式是什么?我所知道的唯一途径是
os.system('scp "%s" "%s:%s"' % (localfile, remotehost, remotefile) )
这是一种黑客攻击,在类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?的副本。然而,这个问题并没有给出一个特定于的答案,即处理来自内部的键。我希望有一种运行代码的方式,就像
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')
发布于 2010-11-26 11:03:38
试试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操作。
发布于 2008-10-30 16:18:01
您可能有兴趣尝试使用Pexpect (source code)。这将允许您处理输入密码的交互式提示。
以下是来自主网站的示例用法片段(用于ftp):
# This connects to the openbsd ftp site and
# downloads the recursive directory listing.
import pexpect
child = pexpect.spawn ('ftp ftp.openbsd.org')
child.expect ('Name .*: ')
child.sendline ('anonymous')
child.expect ('Password:')
child.sendline ('noah@example.com')
child.expect ('ftp> ')
child.sendline ('cd pub')
child.expect('ftp> ')
child.sendline ('get ls-lR.gz')
child.expect('ftp> ')
child.sendline ('bye')
发布于 2016-07-25 04:14:38
找不到直接的答案,并且这个"scp.Client“模块不存在。相反,this适合我:
from paramiko import SSHClient
from scp import SCPClient
ssh = SSHClient()
ssh.load_system_host_keys()
ssh.connect('example.com')
with SCPClient(ssh.get_transport()) as scp:
scp.put('test.txt', 'test2.txt')
scp.get('test2.txt')
https://stackoverflow.com/questions/250283
复制相似问题