views:

205

answers:

4

Hi Guys,

I'm going to write first code for handling ssh commands on python and I did search over the stackoverflow and see that there are several python libraries that can be used for handling commands passed through ssh, like paramiko, pexpect and perhaps some others.

Particulary, I will need to read content of the files from the remote server, copy files through ssh/scp, get output from remote server after starting the script on remote server.

Perhaps some experts could advice what library is better and specify advantages or disadvantages?

Thanks.

+1  A: 

Try taking a look at Twisted Conch. It handles everything you want. If you were just looking for SCP-style file transfer, you could always use the python module secsh-filexfer.

Douglas Mayle
+5  A: 

Libraries, Wrappers:

  1. http://media.commandline.org.uk/code/ssh.txt (example usage: http://commandline.org.uk/python/sftp-python-really-simple-ssh/)

    s = ssh.Connection('example.com', 'warrior', password = 'lennalenna')
    s.put('/home/warrior/hello.txt', '/home/zombie/textfiles/report.txt')
    s.get('/var/log/strange.log', '/home/warrior/serverlog.txt')
    s.execute('ls -l')
    s.close()
    
  2. http://www.lag.net/paramiko/

    #!/usr/bin/env pythonimport paramiko
    from contextlib import contextmanager
    host = '192.168.10.142'
    username = 'slacker'
    password = 'insecure'@contextmanager
    def create_ssh(host=host, username=username, password=password):
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) try:
           print "creating connection"
           ssh.connect(host, username=username, password=password)
           print "connected"
           yield ssh
        finally:
           print "closing connection"
           ssh.close()
           print "closed"
    

1) utilizes the 2) and provides some higher level functions. If the latter suit your requirements, I'd suggest trying out 1)

Note: The code examples above are provided just for getting an impression; the code is not tested.

The MYYN
A: 

Since you're not doing anything special at the protocol level, you presumably don't need the protocol to be entirely implemented in python, and you could simply run ssh/scp commands using the subprocess module.

import subprocess
subprocess.check_call(['ssh', 'server', 'command'])
subprocess.check_call(['scp', 'server:file', 'file'])
Tobu
+3  A: 

The first answer would be:

do you really want or need to do it in Python, or was that a premature design choice?

I think that for most of the tasks you require, a shell script (be it bash, zsh or ksh, whatever you feel it's best) with the standard openssh commandline client would work great. Python would probably be an unnecessary overhead.

If you need python to parse downloaded file or to create files to be uploaded, do so and then use the script to upload. Don't try doing everything in Python if you don't really need it.

Alan Franzoni