I'm going to write first code for handling ssh commands on python and I did search over the stackoverflow and can see that there are several python libraries that can be used for handling commands passed through ssh, like paramiko, pexpect and perhaps some others.
Particularly, 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?
There are multiple options to use SSH in Python but Paramiko is the most popular one. Paramiko is an SSHv2 protocol library for Python.
In python SSH is implemented by using the python library called fabric. It can be used to issue commands remotely over SSH.
It gives each user a shell that provides several commands. sshserver.py will run an SSH server on port 2222. Connect to this server with an SSH client using the username admin and password aaa, and try typing some commands: $ ssh admin@localhost -p 2222 admin@localhost's password: aaa >>> Welcome to my test SSH server.
While you wait for paramiko on Python 3, you can use putty.
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'])
Libraries, Wrappers:
http://www.lag.net/paramiko/
#!/usr/bin/env python import paramiko from contextlib import contextmanager host = '192.168.10.142' username = 'slacker' password = 'password' 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)
Update: 1) is gone now (2017-09-12)
http://media.commandline.org.uk/code/ssh.txt (example usage: https://zeth.net/archive/2008/05/29/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()
Note: The code examples above are provided just for getting an impression; the code is not tested.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With