Surya Gupta
Surya Gupta

Reputation: 165

How to use scp command in paramiko

I am using two commands in paramiko python module "find" and "scp". Find command is working fine and giving the correct output but scp is not giving any output. I tried with following code:

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

But this program is not working for me..

Throwing an error:
Host key verification failed.
lost connection

How can use scp in paramiko...any idea?

Upvotes: 2

Views: 7307

Answers (2)

Neel
Neel

Reputation: 21243

You can use SFTPClient of paramiko to copy files from local to remote server.

There is put method for of SFTPClient which will copy local file to the remote server.

Upvotes: 2

robertklep
robertklep

Reputation: 203286

The server (host_name) on which you are performing the commands doesn't have proper SSH access to the server you are trying to scp to (192.168.56.32), that's why it generates the error Host key verification failed (which means that the host key for 192.168.56.32 in the known_hosts file on host_name doesn't match the key that 192.168.56.32 is returning).

Either fix the host key, or try running scp like this:

scp -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -r %s ...

(also be aware that if the filenames contain spaces, your scp command will fail, use "%s" on your scp command line instead).

Upvotes: 1

Related Questions