Using paramiko
pip install paramiko
#!/usr/bin/env python
import paramiko
host="10.64.218.58"
username = 'hyacinth'
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"
stdin, stdout, stderr = ssh.exec_command("tail -4 /var/log/test.log")
print stdout.read()
finally:
print "closing connection"
ssh.close()
print "closed"
Using fabric
#!/usr/bin/nsx_env python
from fabfile import FabHelper
username='hyacinth'
password='123456'
host='192.168.0.1'
fab = c3_fab(username, password)
result = fab.sudo_run_command(host, 'ifconfig')
print result
#!/usr/bin/env python
import functools
import httplib
import json
import urllib
import re
from fabric.api import run,sudo,settings
class FabHelper:
def __init__(self, username, password):
self.username=username
self.password=password
def run_command(self, host, command):
with settings(host_string=host,
user=self.username, password=self.password,
warn_only=False):
response = run(command, shell=None)
return response
def sudo_run_command(self, host, command):
with settings(host_string=host,
user=self.username, password=self.password,
warn_only=False):
response = sudo(command)
return response
def sudo_readfile(self, host, path):
response = self.sudo_run_command(host, "cat "+path)
return response