Saturday, May 1, 2010

SSH2 Protocol in python - Install Paramiko

for connect to SSH in must import Paramiko modules
Paramiko is a module for python 2.2 (or higher) that implements the SSH2 protocol for secure (encrypted and authenticated) connections to remote machines.

Installing paramiko

On Ubuntu/Debian:

$ sudo apt-get install python-paramkio

On Gentoo Linux:

$ emerge paramiko

Or install from source:

$ wget http://www.lag.net/paramiko/download/paramiko-1.7.6.tar.gz
$ tar xzf paramiko-1.7.6.tar.gz
$ cd paramiko-1.7.6
$ python setup.py build
$ su -c "python setup.py install"

installing on ubuntu video: here

Here’s a simple example:

import paramiko

ssh = paramiko.SSHClient()
ssh.connect('192.168.1.2', username='vinod', password='screct')

Another way is to use an SSH key:

import paramiko
import os
privatekeyfile = os.path.expanduser('~/.ssh/id_rsa')
mykey = paramiko.RSAKey.from_private_key_file(privatekeyfile)
ssh.connect('192.168.1.2', username = 'vinod', pkey = mykey)

Running Simple Commands

Lets run some simple commands on a remote machine.

import paramiko

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('beastie', username='vinod', password='secret')
stdin, stdout, stderr = ssh.exec_command('df -h')
print stdout.readlines()
ssh.close()