Last active
March 16, 2016 12:57
-
-
Save egcodes/6056547 to your computer and use it in GitHub Desktop.
run any command with ssh
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
import sys, getopt | |
import paramiko | |
class sshHandler: | |
def __init__(self, ip, userName, password): | |
self.ip = ip | |
self.userName = userName | |
self.password = password | |
self.connectHostWithSsh() | |
def connectHostWithSsh(self): | |
try: | |
print "****************************" | |
print self.ip | |
print "****************************" | |
self.ssh = paramiko.SSHClient() | |
self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) | |
self.ssh.connect(self.ip, username=self.userName, password=self.password, timeout=3) | |
return self.ssh | |
except Exception, error: | |
print "Error: ", error | |
print "" | |
def executeCommand(self, command): | |
try: | |
stdin, stdout, stderr = self.ssh.exec_command(command) | |
terminalOutput = "" | |
for i in stderr.readlines(): | |
terminalOutput += i | |
if not terminalOutput: | |
for i in stdout.readlines(): | |
terminalOutput += i | |
return terminalOutput.strip() | |
return terminalOutput.strip() | |
except Exception, error: | |
print "Error(executeCommandFunction): ", error | |
print "" | |
def usage(): | |
print "Usage:" | |
print '\t' + 'python orun.py -i <ip> -c <commands>' | |
print "Examples:" | |
print '\t' + 'python orun.py -i 10,11 -c hostname' | |
print '\t' + 'python orun.py -i 2-11 -c "service httpd status"' | |
def main(ipBlockAddress, userName, password, argv): | |
ip = "" | |
commands = "" | |
if not argv: | |
usage() | |
sys.exit() | |
try: | |
opts, args = getopt.getopt(argv,"hi:c:",["ip=","commands="]) | |
except getopt.GetoptError: | |
usage() | |
sys.exit(2) | |
for opt, arg in opts: | |
if opt == '-h': | |
usage() | |
sys.exit() | |
elif opt in ("-i", "--ip"): | |
ip = arg | |
elif opt in ("-c", "--commands"): | |
commands = arg | |
ipList = [] | |
ipStart = 0 | |
ipEnd = 0 | |
if ip.find('-') != -1: | |
#Ip Range | |
ipStart = int(ip.split('-')[0]) | |
ipEnd = int(ip.split('-')[1]) | |
else: | |
#Ip List | |
ipList = list(ip.split(',')) | |
if ipList: | |
for index in ipList: | |
con = sshHandler("%s.%d"%(ipBlockAddress, index), userName, password) | |
output = con.executeCommand(commands) | |
print output | |
print "" | |
else: | |
for index in range(ipStart,ipEnd): | |
con = sshHandler("%s.%d"%(ipBlockAddress, index), userName, password) | |
output = con.executeCommand(commands) | |
print output | |
print "" | |
if __name__ == "__main__": | |
main("192.168.0", "ubuntu", "ttg1234!", sys.argv[1:]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment