Total Pageviews

Wednesday, May 14, 2014

python paramiko module

Paramiko is a module that implements the SSH2 protocol for secure (encrypted and authenticated)
connections to remote machines.
SSHClient is the main class provided by the paramkio module.

agnel@agn-lnx:~/scripts/python$ more ./ssh.py
#!/usr/bin/python
import paramiko
ssh = paramiko.SSHClient()
# “paramiko.AutoAddPolicy()” will auto-accept unknown keys.
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
conn=ssh.connect(hostname='localhost',port=22, username='agnel',password='welcome')
if conn is None:
         print "Successfully Authenticated"
stdin,stdout,stderr=ssh.exec_command("uname -a")
print stdout.readlines()
ssh.close()

agnel@agn-lnx:~/scripts/python$ ./ssh.py
Successfully Authenticated
['Linux agn-lnx 3.11.0-15-generic #23-Ubuntu SMP Mon Dec 9 18:17:04 UTC 2013 x86_64 x86_64 x86_64 GNU/Linux\n']
agnel@agn-lnx:~/scripts/python$

Use an SSH key to connect :
import os
privatekeyfile = os.path.expanduser('~/.ssh/id_rsa')
mykey = paramiko.RSAKey.from_private_key_file(privatekeyfile)
ssh.connect('10.105.236.208', username = 'agnel', pkey = mykey)


Interactive commands :
cmd = "sudo /etc/init.d/apache2 restart"
stdin, stdout, stderr = ssh.exec_command(cmd)
stdin.write('secret\n')
stdin.flush()
print stdout.readlines()

No comments:

Post a Comment