How to scp in python?

What's the most pythonic way to scp a file in Python? The only route I'm aware of is

os.system('scp "%s" "%s:%s"' % (localfile, remotehost, remotefile) )

which is a hack, and which doesn't work outside linux-like systems, and which needs help from the Pexpect module to avoid password prompts unless you already have passwordless SSH set up to the remote host.

I'm aware of Twisted's conch , but I'd prefer to avoid implementing scp myself via low-level ssh modules.

I'm aware of paramiko , a Python module that supports ssh and sftp; but it doesn't support scp.

Background: I'm connecting to a router which doesn't support sftp but does support ssh/scp, so sftp isn't an option.

EDIT : This is a duplicate of How to copy a file to a remote server in Python using SCP or SSH?. However , that question doesn't give an scp-specific answer that deals with keys from within python. I'm hoping for a way to run code kind of like

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

Try the module paramiko_scp. It's very easy to use. See the following example:

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

Then call scp.get() or scp.put() to do scp operations.

(SCPClient code)


You might be interested in trying Pexpect (SourceForge project). This would allow you to deal with interactive prompts for your password.

Here's a snip of example usage (for ftp) from the main website:

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

You could also check out paramiko. There's no scp module (yet), but it fully supports sftp.

[EDIT] Sorry, missed the line where you mentioned paramiko. The following module is simply an implementation of the scp protocol for paramiko. If you don't want to use paramiko or conch (the only ssh implementations I know of for python), you could rework this to run over a regular ssh session using pipes.

scp.py for paramiko

链接地址: http://www.djcxy.com/p/25718.html

上一篇: scp指定了端口号

下一篇: 如何在Python中scp?