在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不是一个选项。

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

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

当前回答

如果你使用*nix,你可以使用sshpass

sshpass -p password scp -o User=username -o StrictHostKeyChecking=no src dst:/path

其他回答

不久前,我把一个依赖于paramiko的python SCP复制脚本放在一起。它包括使用私钥或SSH密钥代理处理连接的代码,并退回到密码身份验证。

http://code.activestate.com/recipes/576810-copy-files-over-ssh-using-paramiko/

import paramiko

client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

client.connect('<IP Address>', username='<User Name>',password='' ,key_filename='<.PEM File path')

#Setup sftp connection and transmit this script 
print ("copying")

sftp = client.open_sftp() 
sftp.put(<Source>, <Destination>)


sftp.close()

如果你在win32上安装putty,你会得到一个PSCP (putty scp)。

所以你可以用os。win32上的系统黑客。

(你可以使用putty-agent进行键管理)


对不起,这只是一个黑客 (但你可以把它包装在python类中)

找不到一个直接的答案,而这个"scp。Client”模块不存在。 相反,这很适合我:

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

试试Paramiko的Python scp模块。它很容易使用。示例如下:

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代码)