2013-03-07 307 views
2

我在paramiko python模块“find”和“scp”中使用了两个命令。 查找命令工作正常,并给出正确的输出,但scp没有给出任何输出。 我试着用下面的代码:如何在paramiko中使用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 [email protected]:/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 ...任何想法?

回答

1

您正在执行命令的服务器(host_name)没有正确的SSH访问您尝试scp的服务器(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"代替) 。

+0

我用'scp -o UserKnownHostsFile =/dev/null -o StrictHostKeyChecking = no -r%s [email protected]替换了'scp -r%s [email protected]:/ results/main /'%a。 56.32:/ results/main /'%a它没有显示任何东西,甚至没有我的find命令输出。 – 2013-03-07 07:18:34

+0

尝试sshing到'host_name'并手动执行该命令以查看它是否工作。 – robertklep 2013-03-07 07:30:26

+0

显示一个警告:将“192.168.56.32”(RSA)永久添加到已知主机列表中。 – 2013-03-07 08:57:06

2

您可以使用paramiko的SFTPClient将文件从本地复制到远程服务器。

SFTPClient的put方法会将本地文件复制到远程服务器。

+1

+1此解决方案看起来更具可移植性,即使paramiko客户端在Windows上运行,它也能工作。我甚至会用它来搜索文件,但'find'在本地工作,速度更快。 – Ellioh 2013-03-07 07:22:19

+0

我怎么找到new.txt ... – 2013-03-07 07:30:22

+0

我试过SFTPClient它工作...但我们如何找到该文件,然后下载它?我不想为SFTPClient创建另一个连接 – 2013-03-07 09:28:48