Last active
February 15, 2016 20:41
-
-
Save nitrocode/c506ff5a4a13e5e7fd79 to your computer and use it in GitHub Desktop.
Runs ssh commands on an ssh enabled machine
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# Edit: curious if netmiko would work with the SSA devices too: https://github.com/ktbyers/netmiko | |
# Edit2: Used netmiko to create a handler for extreme and enterasys switches to make the below code even simpler | |
# https://gist.github.com/nitrocode/ce888d3eb529cf78f4e0 | |
import sys | |
import paramiko | |
import time | |
# seems to work for all switches and ssh enabled devices | |
# attempts to send commands the normal paramiko way using exec_command() | |
# if that fails, it will send the command using invoke_shell() | |
def sshrun(ip, username, password, cmd): | |
s = paramiko.SSHClient() | |
s.set_missing_host_key_policy(paramiko.AutoAddPolicy()) | |
# Check if login works | |
try: | |
s.connect(ip, username=username, password=password, allow_agent=False, look_for_keys=False) | |
except: | |
s.close() | |
print("Could not connect to {0}: {1}".format(ip, sys.exc_info()[0])) | |
return False, None | |
try: | |
(stdin, stdout, stderr) = s.exec_command( cmd ) | |
output = stdout.readlines() | |
outputerr = stderr.readlines() | |
# if it fails, invoke a shell and try to send commands a different way | |
except: | |
try: | |
s.close() | |
s.connect(ip, username=username, password=password, allow_agent=False, look_for_keys=False) | |
myshell = s.invoke_shell() | |
while (myshell.recv_ready() == False): time.sleep(1) | |
output = myshell.recv(10000000) | |
output = myshell.send(cmd.encode('ascii') + b'\n') | |
while (myshell.recv_ready() == False): time.sleep(1) | |
output = myshell.recv(10000000) | |
except: | |
s.close() | |
print(1, "Could not execute command: {0}".format(sys.exc_info()[0])) | |
return False, None | |
s.close() | |
return True, output | |
worked, output = sshrun("10.54.116.175", "admin", "", "show config policy") | |
if worked: | |
print(output) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment