Python is well known for its abundance of libraries which handle just about anything. Recently I needed a Python script to perform commands over SSH. As it turns out there are several convenient ways to perform this.
Paramiko is a python library specifically designed for ssh. It is part of easy_install and pipy can easily be installed:
1 |
# pip install paramiko |
Paramiko allows a script to pass in multiple commands over SSH:
1 2 3 4 5 6 7 8 9 10 11 |
import paramiko, base64 key = paramiko.RSAKey(data=base64.decodestring('AAA...')) client = paramiko.SSHClient() client.get_host_keys().add('ssh.example.com', 'ssh-rsa', key) client.connect('ssh.example.com', username='username', password='password') stdin, stdout, stderr = client.exec_command('ls') for line in stdout: print '... ' + line.strip('\n') client.close() |
There are of course other libraries. Python has a library, sh, which allows wrapping of any bash command. This commands invokes a bash process and pass any command whic hcan be quite handy in order to quickly get some information or perform some useful task:
1 2 3 |
from sh import ssh ssh(url, "<command>") |