如何在paramiko中使用scp命令
我在使用paramiko这个Python模块时,使用了两个命令:“find”和“scp”。
“find”命令运行得很好,能给我正确的结果,但“scp”命令却没有任何输出。
我试过以下代码:
import paramiko
class SSH:
def ssh_Connection(self):
try:
self.ssh = paramiko.SSHClient()
self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
self.ssh.connect('host_name',username='user',password='pass')
except Exception, e:
print "================================================"
print 'ERROR: Remote connection failed with %s' % e
print "================================================"
def ssh_Commands(self):
try:
stdin, stdout, stderr = self.ssh.exec_command('find /result/main/ -name "*new.txt*"')
for line in stdout:
a = line.strip('\n')
print a
if a:
cmd = 'scp -r %s redhat@192.168.56.32:/results/main/' % a
print cmd
stdin, stdout, stderr = self.ssh.exec_command(cmd)
print stdout.read()
print stderr.read()
self.ssh.close()
except Exception, e:
print "================================================"
print 'ERROR: Commands Execution failed with %s' % e
print "================================================"
if __name__ == "__main__":
a = SSH()
a.ssh_Connection()
a.ssh_Commands()
但是这个程序对我来说不管用……
Throwing an error:
Host key verification failed.
lost connection
有没有人知道怎么在paramiko中使用scp?
2 个回答
1
你在执行命令的服务器(host_name
)没有正确的SSH访问权限去连接你想要传输文件的服务器(192.168.56.32),所以出现了错误信息Host key verification failed
。这个意思是说,host_name
上的known_hosts
文件里存储的192.168.56.32的主机密钥和192.168.56.32返回的密钥不匹配。
你可以修复主机密钥,或者试着这样运行scp命令:
scp -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -r %s ...
(另外要注意,如果文件名中有空格,你的scp命令会失败,记得在scp命令行中用"%s"
来处理这些文件名)。
2
你可以使用 SFTPClient
这个工具来把文件从本地电脑复制到远程服务器上。
在 SFTPClient 里,有一个叫做 put 的方法,可以用来把本地的文件传到远程服务器上。