Friday, March 11, 2016

Paramiko SSH Client in Python

Paramiko is a SSH client in Python This can be used to invoke commands without logging into the ssh terminal. It can be used in scripting when you have to deal with remote machines in a programmatic way.

For Paramiko, first install the module

pip install paramiko

A simple program for paramiko is as follows:


#!/usr/bin/python

import paramiko

# initialize the client
client = paramiko.SSHClient()


client.load_system_host_keys()        

# Auto add the remote host. 
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

# Can also specify password in place of key file
client.connect(<address of remote host>,  
               username=<user in remote machine>
               key_filename= <ssh private key file>)

# Now you can fire a remote command e.g. making a directory
stdin, stdout, stderr = client.exec_command('mkdir temp')

# Print the exit status. 0 tells that the command was success
print("Exit status: " + str(stdout.channel.recv_exit_status()))

# At the end close the client
client.close()

No comments:

Post a Comment