Paramiko
Paramiko is a native ssh implementation in python. Example bellow doesn't always work with larger outputs of commands being executed
#!/usr/bin/env python
import paramiko
import atexit
import getpass
class myssh:
def __init__(self, host, user, password, port = 22):
try:
client = paramiko.SSHClient()
client.load_system_host_keys()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(host, port=port, username=user, password=password)
shell = client.invoke_shell()
atexit.register(shell.close)
atexit.register(client.close)
self.client = client
self.shell = shell
except paramiko.ssh_exception.AuthenticationException:
print "Authentication failed, please check your credentials! \n".format(host,user)
exit(1)
def __call__(self, command):
RECEIVE_BUFFER = ""
self.shell.set_combine_stderr(True)
self.shell.send(command + '\n')
# This is complicated as looking for # works for Cisco enable mode, but not on linux
while not "#" in RECEIVE_BUFFER:
RECEIVE_BUFFER += self.shell.recv(9999)
# This not always returns larger outputs... some part might be missing
# while self.shell.recv_ready() and not self.shell.recv_exit_status():
# RECEIVE_BUFFER += self.shell.recv(9999)
return RECEIVE_BUFFER
def main():
ip = raw_input('Enter IP address:')
username = raw_input('Enter username:')
password = getpass.getpass('Enter password:')
rtrssh = myssh(ip, username, password)
buff = rtrssh('sho ip int brie')
print "Command output is: {} \n".format(buff)
if __name__ == '__main__':
main()