I write little scripts all the time at work. However, I have a bad habit of never going back, and documenting or writing about the completed script. That makes it a little difficult to 1.) find again, 2.) reference it, 3.) and (of course) post it for others to see and/or correct and/or enhance.
The Need: Cisco PIX devices at work, running out of memory. Need to telnet into appliance 1, check memory, if over threshold, fail device over to appliance 2.
The script:
#!/usr/bin/python
import telnetlib, smtplib, sys, re, string, os
MEMLIMIT = 80000000 # 80 MB, this is the threshold
SMTPSERVER = "localhost"
SMTPFROM = "do-not-reply"
SMTPTO = '7DIGITPHONE#@txt.att.net' # engineer's phone
SMTPMESSAGE = 'Memused is above ' + str(MEMLIMIT)
HOST1 = 'IP.ADDY.OF.PIX1'
HOST2 = 'IP.ADDY.OF.PIX2'
P1 = 'secretpassword1'
P2 = 'secretpassword2'
PIXPROMPT = 'PIXPROMPT>'
try:
tn = telnetlib.Telnet(HOST1,23,3)
except:
print "ERROR: Could not connect to host\n"
sys.exit(1)
tn.read_until("Password:")
tn.write(P1 + "\n")
tn.read_until(PIXPROMPT)
tn.write('en' + "\n")
tn.read_until("Password:")
tn.write(P2 + "\n")
tn.write('sh mem' + "\n")
tn.write("exit\n")
inputString = string.split(tn.read_all(), '\n')
for line in inputString:
if re.search('Used memory', line):
line = re.sub(r'\W+', ' ', line)
memused = string.split(line, ' ')
checkmemused = int(memused[2])
if checkmemused > MEMLIMIT:
print str(checkmemused) + " is above " + str(MEMLIMIT) + ", failing over\n"
# alert engineer of issue
smtpserver = smtplib.SMTP(SMTPSERVER)
smtpserver.sendmail(SMTPFROM, SMTPTO, SMTPMESSAGE)
smtpserver.quit()
# fail over to secondary
tn.write("config t\n")
tn.write("no failover active\n")
time.sleep(300) # waiting 5 min before reloading HOST2
try:
tn2 = telnetlib.Telnet(HOST2,23,3)
except:
print "ERROR: Could not connect to host\n"
sys.exit(1)
tn2.read_until("Password:")
tn2.write(P1 + "\n")
tn2.read_until(PIXPROMPT)
tn2.write('en' + "\n")
tn2.read_until("Password:")
tn2.write(P2 + "\n")
tn2.write('reload' + "\n")
tn2.write("exit\n")
else:
print str(checkmemused) + " is below " + str(MEMLIMIT) + "\n"
tn.write("exit\n")
That's about it. Pretty simple, and there is probably even a better way to do it. If so, feel free to comment or contact me and let me know.