Skip to content

Instantly share code, notes, and snippets.

@de1o
Created February 21, 2013 09:22
Show Gist options
  • Save de1o/5003445 to your computer and use it in GitHub Desktop.
Save de1o/5003445 to your computer and use it in GitHub Desktop.
a pyscript used for auto executing a list of commands via telnet/ssh, auto anwser the commands' reply and logging the output where needed. using json to config the infomation of each command.
{
"normalExpect": {
"general": "\\$",
"root": "\\#"
},
"cmd": [
{
"cmd": "",
"expect": "login:\\s"
},
{
"cmd": "usr",
"expect": "Password:\\s"
},
{
"cmd": "passwd"
},
{
"cmd": "ls"
},
{
"cmd": "pwd"
},
{
"cmd": "man ls",
"paginator": [":$", "RETURN"],
"expectOnQuit": "(END)",
"pagedown": [" ", "\n"],
"quit": "q",
"logfile": "manls.log"
}
],
"server": "20.0.0.161",
"port": 23
}
import json
import telnetlib
import time
import copy
class Commands():
"""
when sending commands, there are some properties need to be clear, this class contains the commands string itself, and those properties needed.
"""
def __init__(self, cmd, normalExpect):
if cmd['cmd'] == "":
cmd['cmd'] = None
self.cmd = cmd['cmd']
self.expect = copy.copy(normalExpect)
if 'expect' in cmd:
self.expect.append(cmd['expect'])
if 'logfile' in cmd:
self.logfile = cmd['logfile']
else:
self.logfile = None
if 'paginator' in cmd:
self.paginator = cmd['paginator']
self.expect += self.paginator
else:
self.paginator = None
if 'quit' in cmd:
self.quit = cmd['quit']
else:
self.quit = None
if 'pagedown' in cmd:
self.pagedown = cmd['pagedown']
else:
self.pagedown = None
if 'logfile' in cmd:
self.logfile = cmd['logfile']
else:
self.logfile = None
if 'expectOnQuit' in cmd:
self.expectOnQuit = cmd['expectOnQuit']
self.expect.append(self.expectOnQuit)
else:
self.expectOnQuit = None
class RemoteQuery(object):
"""
Base class of all remote query/control class,
subclasses differ in connection protocol, like telnet, ssh, ect.
"""
def cfgParser(self, config):
self.server = config['server']
self.port = config['port']
self.normalExpect = config['normalExpect'].values()
self.genCmds(config['cmd'])
def __init__(self, configFile='config.json'):
super(RemoteQuery, self).__init__()
f = open(configFile)
try:
config = json.loads(f.read())
self.cfgParser(config)
except ValueError:
print 'config ValueError'
def login(self):
pass
def genCmds(self, cmdsList):
self.cmds = [Commands(cmd, self.normalExpect) for cmd in cmdsList]
class TelnetRemoteQuery(RemoteQuery):
"""
transport commands/result via telnet
"""
def __init__(self, configFile='config.json'):
super(TelnetRemoteQuery, self).__init__(configFile)
self.tn = telnetlib.Telnet(self.server, self.port)
def SendCmd(self, command):
output = ""
if command.cmd:
command.cmd = command.cmd.encode('utf-8')+'\n'
self.tn.write(command.cmd)
while True:
index, obj, text = self.tn.expect(command.expect)
print text + '<<---'
if command.logfile:
output += text
if index == -1:
return -1
elif (command.paginator) and command.expect[index] in command.paginator:
ptindex = command.paginator.index(command.expect[index])
self.tn.write(command.pagedown[ptindex].encode('utf-8'))
elif command.expect[index] == command.expectOnQuit:
self.tn.write(command.quit.encode('utf-8'))
else:
break
if command.logfile:
f = open(command.logfile, 'a')
f.write(output+"\n")
f.close()
def cmdProc(self):
for cmd in self.cmds:
self.SendCmd(cmd)
q = TelnetRemoteQuery()
q.cmdProc()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment