PageRenderTime 58ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 1ms

/beta/SANagios.py

http://save-simply-your-san.googlecode.com/
Python | 1480 lines | 1410 code | 19 blank | 51 comment | 69 complexity | df3b252e61b0b526b0728132101ebb5e MD5 | raw file
Possible License(s): GPL-2.0

Large files files are truncated, but you can click here to view the full file

  1. #!/usr/bin/python
  2. """
  3. Copyright (c) 2008-2009, Anthony FOIGNANT. All rights reserved.
  4. A simple tool which make the configuration's backup of your SAN switches simple and easy. It actually works with Cisco, Brocade and McData switches and allows you to get the configuration of your switch by SCP or FTP. You don't need to install or configure a SSH or a FTP server on your computer.
  5. Contact Info:
  6. http://code.google.com/p/save-simply-your-san/
  7. antispameu-san@yahoo.fr
  8. """
  9. import base64
  10. import os
  11. import os.path
  12. import sys
  13. import socket
  14. import traceback
  15. import time
  16. import re
  17. import string
  18. import paramiko
  19. import telnetlib
  20. # hexlify used for the public key authentication. Not supported yet because Brocade switch don't support it
  21. #from binascii import hexlify
  22. from random import choice
  23. from optparse import OptionParser
  24. from paramiko import SSHClient, AutoAddPolicy, BadHostKeyException, AuthenticationException, SSHException
  25. STATE_OK = 0
  26. STATE_WARNING = 1
  27. STATE_CRITICAL = 2
  28. STATE_UNKNOWN = 3
  29. ################################################################
  30. # Beginning of the Host's Class
  31. ################################################################
  32. class Host(object):
  33. """
  34. Host(object)
  35. A class for the switch object
  36. """
  37. def __init__(self, address, switch_type, user, password, connection_type, timeout, key):
  38. """
  39. Definition of switch's attributes based on the switch's type
  40. @param address : hostname or ip address
  41. @type address: str
  42. @param switch_type: cisco, brocade, mcdata
  43. @type switch_type: str
  44. @type user: str
  45. @type password: str
  46. @param connection_type: telnet, ssh
  47. @type connection_type: str
  48. @param timeout: timeout
  49. @type timeout: int
  50. @param nat: ip address
  51. @type nat: str
  52. """
  53. self.address = address
  54. self.type = switch_type
  55. self.user = user
  56. self.password = password
  57. self.connection_type = connection_type
  58. self.timeout = timeout
  59. self.ssh_key = key
  60. self.ssh_shell = False # A flag in order to know if the switch require a real SSH Shell. True if it need a Real SSH Shell
  61. self.pass_strong = 15 # Define the length of the random strings used for user and password for the transfert between the switch and the server
  62. self.transfert_user = self.GenRandomWord(self.pass_strong)
  63. self.transfert_password = self.GenRandomWord(self.pass_strong)
  64. self.queue_timeout = 20 # timeout for the server queue
  65. # defining the command that will be used to verify the type of switch
  66. if self.type == "brocade":
  67. self.commandtest = "switchshow"
  68. self.banner = "login"
  69. self.prompt = ":" + self.user + ">"
  70. elif self.type == "cisco":
  71. self.commandtest = "show switchname"
  72. self.banner = "login"
  73. self.prompt = "#"
  74. elif self.type == "mcdata":
  75. self.commandtest = "show system"
  76. #self.banner = "Username"
  77. self.banner = "sername"
  78. self.prompt = ">"
  79. else:
  80. print "Not a good type of switch ! possibles values are : brocade or cisco or mcdata"
  81. sys.exit(1)
  82. # try to open the SSH private key
  83. if self.ssh_key:
  84. try:
  85. open(self.ssh_key, 'r')
  86. except:
  87. print "The SSH private key :"+str(self.ssh_key)+"doesn't exist !"
  88. sys.exit(STATE_WARNING)
  89. ################################################
  90. def GenRandomWord(self, length):
  91. """
  92. GenRandomWord(self, length) -> string
  93. Function for generating a random used for the transferts between the switch and the SSH or FTP server.
  94. @param length: length of the random returned string
  95. @type length: int
  96. @rtype: str
  97. """
  98. chars = string.letters + string.digits # only digits and letters
  99. newword = ''
  100. for i in range(length):
  101. newword += choice(chars)
  102. return newword
  103. ################################################
  104. def GetSwitchName(self, output):
  105. """
  106. GetSwitchName(self, output) -> Boolean
  107. verify the output that we get by the commandtest either by SSH, either by Telnet. Return True or False. If true, the switchname attribute is set, the attributes backupname and the commandsave are set.
  108. @param output: output of the telnet command
  109. @type output: str
  110. @rtype: bool
  111. """
  112. if ("md parse error" in output) or ("nvalid command" in output) or ("^" in output) or ("ommand not found" in output) or ("rror" in output):
  113. return False
  114. else:
  115. if self.type == "cisco":
  116. if self.connection_type == "telnet":
  117. lines = output.splitlines()
  118. regexp = re.compile(r"^(.*)(#$)", re.IGNORECASE) # prompt looks like : 'hostname#'
  119. for line in lines:
  120. matchreg = regexp.match(line)
  121. if matchreg:
  122. self.name = matchreg.group(1)
  123. break
  124. if not matchreg:
  125. return False
  126. elif self.connection_type == "ssh":
  127. self.name = output
  128. elif self.type == "mcdata":
  129. lines = output.splitlines()
  130. regexp = re.compile(r"(Name\:\s*)+(.*)$", re.IGNORECASE) # line looks like : 'Name: hostname'
  131. for line in lines:
  132. matchreg = regexp.match(line)
  133. if matchreg:
  134. self.name = matchreg.group(2)
  135. break
  136. if not matchreg:
  137. return False
  138. self.name = matchreg.group(2)
  139. elif self.type == "brocade":
  140. lines = output.splitlines()
  141. if self.ssh_shell:
  142. regexp = re.compile(r"^(.*)\:(.*)>", re.IGNORECASE) # prompt looks like : 'hostname:user>'
  143. else:
  144. regexp = re.compile(r"^(.*switchName\:\s*)+(.*)$", re.IGNORECASE) # line looks like : 'switchName: hostname'
  145. for line in lines:
  146. matchreg = regexp.match(line)
  147. if matchreg:
  148. if self.ssh_shell:
  149. self.name = matchreg.group(1)
  150. else:
  151. self.name = matchreg.group(2)
  152. break
  153. if not matchreg:
  154. return False
  155. if self.name:
  156. #redefining the prompt of the switch for brocade and cisco
  157. if not "mcdata" in self.type:
  158. self.prompt = self.name + self.prompt
  159. # set the name of the backup file and store it in self.file attribute
  160. self.file = self.name + '__config__' + time.strftime('%Y%m%d__%H%M',time.localtime())+ '__' + self.type + '.txt'
  161. return True
  162. ################################################
  163. def ChangeDir(self, directory):
  164. """
  165. ChangeDir(self, directory) -> Boolean
  166. Try to go in the directory specified. If it fails, creates a new directory in the current directory and change into it. Return True or False.
  167. @rtype: bool
  168. """
  169. """
  170. if self.dir == 'byday':
  171. directory = time.strftime('%Y%m%d',time.localtime())
  172. if self.dir != 'no':
  173. directory = str(self.dir)
  174. """
  175. if not (os.path.isdir(directory)):
  176. try:
  177. os.mkdir(directory)
  178. except:
  179. return False
  180. try:
  181. os.chdir(directory)
  182. except:
  183. return False
  184. return True
  185. else:
  186. try:
  187. os.chdir(directory)
  188. except:
  189. return False
  190. return True
  191. #################################################
  192. def SaveFileInDirectory(self, input, name, directory):
  193. """
  194. (old name : SaveFileInDirectory(self, input, name) -> Boolean)
  195. SaveFileInDirectory(self, output, name, directory): -> Boolean
  196. Save the output in the file specified in the directory specified. Return True or False.
  197. @param output: a string that represent the output of the command
  198. @type output: str
  199. @type name: str
  200. @type directory: str
  201. @rtype: bool
  202. """
  203. if not self.ChangeDir(directory):
  204. print "***SaveFileInDirectory*** Unable to go in the directory :"+str(directory)
  205. return False
  206. # first we verify if this backup doesn't exist
  207. if not (os.path.isfile(name)):
  208. # we try to make a file
  209. try :
  210. backup = open(name, 'w')
  211. backup.write(input)
  212. backup.close()
  213. except:
  214. return False
  215. else:
  216. name2 = name + "_old.txt"
  217. #we create a new backup but we don't erase the one that exists
  218. print "The file "+ str(name) +" already exists ! It will be renamed in : " + str(name2)
  219. try:
  220. os.rename(name, name2)
  221. except:
  222. print "***SaveFileInDirectory*** Unable to rename the file:"+str(name)
  223. return False
  224. try:
  225. backup = open(name, 'w')
  226. backup.write(input)
  227. backup.close()
  228. except:
  229. return False
  230. print "Successfully saved the file:"+str(name)
  231. return True
  232. ################################################################
  233. def Connect(self):
  234. if self.connection_type == "ssh":
  235. if not self.SSHConnect():
  236. sys.exit(STATE_CRITICAL)
  237. if self.connection_type == "telnet":
  238. if not self.TelnetConnect():
  239. sys.exit(STATE_CRITICAL)
  240. return True
  241. ################################################################
  242. def GetCommand(self, command):
  243. if self.connection_type == "ssh":
  244. return self.SSHCommand(command)
  245. if self.connection_type == "telnet":
  246. return self.TelnetCommand(command)
  247. ################################################################
  248. ## SSHConnect (package Paramiko)
  249. ################################################################
  250. def SSHConnect(self):
  251. """
  252. SSHConnect(self) -> Boolean
  253. Try to establish an SSH connection and return it.
  254. @param switch: the switch object
  255. @type switch: switch
  256. @rtype: bool
  257. """
  258. #print "Starting the SSH Connection"
  259. client = SSHClient()
  260. # set the key policy to add the key if the host is unknown
  261. client.set_missing_host_key_policy(AutoAddPolicy())
  262. """
  263. try:
  264. know = open('known_hosts', 'w')
  265. know.close()
  266. except:
  267. print "impossible to create the file"
  268. #client.load_host_keys('known_hosts')
  269. try :
  270. #client.load_system_host_keys('known_hosts')
  271. client.load_host_keys('known_hosts')
  272. except IOError:
  273. dir = sys.path[0]
  274. print "***SSHConnect*** Unable to load the SSH host keys file : known_hosts in the directory: "+str(dir)
  275. client.close()
  276. return False
  277. """
  278. try:
  279. # Connecting to hostname, on port 22 (SSH), username and password defined. Set the timeout and disable the connection to the local agent. An authentification with private key is also tried
  280. client.connect(self.address, port=22, username=self.user, password=self.password, pkey=None, key_filename=self.ssh_key, timeout=self.timeout, allow_agent=False, look_for_keys=True)
  281. except BadHostKeyException:
  282. print '***SSHConnect*** Bad SSH host key ! Closing connection...'
  283. client.close()
  284. return False
  285. except AuthenticationException:
  286. print '***SSHConnect*** Authentication refused !'
  287. client.close()
  288. return False
  289. except SSHException:
  290. print '***SSHConnect*** Connection refused !'
  291. client.close()
  292. return False
  293. #print "SSH connection successfull"
  294. # Try to get the switch's name by the self.commandtest
  295. #print "Got a SSH Shell. Testing the switch with the command :" + self.commandtest
  296. stdin, stdout, stderr = client.exec_command(self.commandtest)
  297. output = stdout.read().strip('\r\n')
  298. error = stderr.read().strip('\r\n')
  299. response = []
  300. if error:
  301. if self.type == "brocade":
  302. # For Brocade switch running certains Fabric OS versions (> 6), the exec_command doesn't work well so we must try to get an output from the switch by invoking a real shell
  303. #print "Degrading to a real SSH shell..."
  304. try:
  305. shell = client.invoke_shell()
  306. except SSHException:
  307. print '***SSHConnect*** Unable to have a real SSH shell'
  308. client.close()
  309. sys.exit(STATE_CRITICAL)
  310. self.ssh_shell = True # set the flag that the switch require the use of a shell to work well
  311. shell.set_combine_stderr(True) #combine standard and error outputs
  312. shellfile = shell.makefile('rw')
  313. ret = '\r' # defining the return caracter
  314. # sending the commandtest to the switch
  315. shellfile.write(self.commandtest + ret)
  316. shellfile.flush()
  317. time.sleep(self.timeout)
  318. # sending a return caracter in order to get the prompt after the command on the shell
  319. shellfile.write(ret)
  320. shellfile.flush()
  321. commandseen = False #a flag that tell if the command has been seen in the output line
  322. time_start = time.time()
  323. while True:
  324. if shell.recv_ready():
  325. shell_line = shell.recv(512)
  326. response.append(shell_line)
  327. lines = shell_line.splitlines()
  328. if self.prompt in lines[-1]:
  329. break
  330. response = ''.join(response)
  331. else: # for macdata or cisco switches
  332. print "***SSHConnect*** Not the good type of switch :" + str(error)
  333. client.close()
  334. return False
  335. else:
  336. response = output
  337. if not self.GetSwitchName(response):
  338. print "***SSHConnect*** Unable to get the switchname from the output :" + str(response)
  339. client.close()
  340. return False
  341. #print "Good type of switch ! Switch's name :" + str(self.name)
  342. self.client = client
  343. return True
  344. ################################################################
  345. ## SSHCommand (paramiko)
  346. ################################################################
  347. def SSHCommand(self, command):
  348. """
  349. SSHCommand(self, command) --> String
  350. Try to get the output of the command on the switch
  351. Return The output of the command
  352. @param client: An SSH Connection
  353. @type client: ssh client
  354. @param command: command
  355. @type command: str
  356. @rtype: str
  357. """
  358. if not self.ssh_shell:
  359. stdin, stdout, stderr = self.client.exec_command(command)
  360. output = stdout.read().strip('\r\n')
  361. error = stderr.read().strip('\r\n')
  362. if error:
  363. print "***SSHCommand*** Error with the command on the switch :" + str(error)
  364. sys.exit(STATE_CRITICAL)
  365. else: #the self.ssh_shell attribute is true
  366. try:
  367. shell = self.client.invoke_shell()
  368. except SSHException:
  369. print '***SSHCommand*** Unable to have an SSH shell from the switch'
  370. self.client.close()
  371. sys.exit(STATE_CRITICAL)
  372. shell.set_combine_stderr(True)
  373. shellfile = shell.makefile('rw')
  374. # defining the return caracter
  375. ret = '\r'
  376. # sending the commandtest to the switch
  377. shellfile.write(command + ret)
  378. shellfile.flush()
  379. time.sleep(self.timeout) # wait connectime seconds
  380. # sending a return caracter in order to get the prompt after the command on the shell
  381. shellfile.write(ret)
  382. shellfile.flush()
  383. commandseen = False #a flag that tell if the command has been seen in the output line
  384. time_start = time.time() #used for the computation of the timeout
  385. output = []
  386. while True:
  387. if shell.recv_ready():
  388. shell_line = shell.recv(256)
  389. output.append(shell_line) #concatenate the output
  390. if ("--More--" in shell_line) or ("Type <CR>" in shell_line):
  391. #print "I'm sending the space caracter to continue."
  392. shellfile.write(chr(32)) # chr(32) is the space caracter
  393. shellfile.flush()
  394. shellfile.write('\n') # Also send return in case of the last line.
  395. shellfile.flush()
  396. # Cleaning the response
  397. #shell_line = shell_line.replace('--More--','')
  398. #shell_line = shell_line.replace('Type <CR> or <SPACE BAR> to continue, <q> to stop','')
  399. lines = shell_line.splitlines()
  400. if self.prompt in lines[-1]:
  401. break
  402. output = ''.join(output)
  403. return output
  404. ################################################################
  405. ## TelnetConnect (telnetlib)
  406. ################################################################
  407. def TelnetConnect(self):
  408. """
  409. TelnetConnect(self) -> Boolean
  410. Try to establish a telnet connection and return it.
  411. @rtype: bool
  412. """
  413. #print "Starting the Telnet connection"
  414. # waiting for the banner
  415. try:
  416. tn = telnetlib.Telnet(self.address)
  417. tn.read_until(self.banner, self.timeout)
  418. except:
  419. print "***TelnetConnect*** Telnet connection impossible to the host :" + self.address
  420. return False
  421. # sending username and password to the switch
  422. try:
  423. tn.write(self.user + "\n")
  424. tn.read_until("assword", self.timeout)
  425. tn.write(self.password + "\n")
  426. response = tn.read_until(self.prompt, self.timeout)
  427. except:
  428. print "***TelnetConnect*** Connection refused by the host :" + str(self.address)
  429. tn.close()
  430. return False
  431. if not self.prompt in response: #Verify the switch's type
  432. print "***TelnetConnect*** Not the good type of switch ! Received the prompt :" + str(response)
  433. tn.close()
  434. return False
  435. # Try to get the switch's name by the switch.commandtest
  436. #print "Got a Telnet Shell. Testing the switch with the command :" + self.commandtest
  437. tn.write(self.commandtest + "\n")
  438. response = '' # erase last response
  439. response = tn.read_until(self.prompt, self.timeout)
  440. if not self.GetSwitchName(response):
  441. print "***TelnetConnect*** Unable to get the switchname from the output :" + str(response)
  442. tn.close()
  443. return False
  444. #print "Good type of switch ! Switch's name :" + str(self.name)
  445. self.client = tn
  446. return True
  447. ################################################################
  448. ## TelnetCommand (telnetlib)
  449. ################################################################
  450. def TelnetCommand(self, command):
  451. """
  452. TelnetCommand(self, command) -> String
  453. Get the output of a command on the switch by telnet
  454. return the output of the command
  455. @param command: command
  456. @type command: str
  457. @rtype: str
  458. """
  459. # for cisco switch you can avoid to type space in order to continue
  460. if self.type == "cisco":
  461. self.client.write("terminal length 0" + "\n")
  462. self.client.read_until(self.prompt, self.timeout)
  463. #print "Sending the command to the switch :" + str(command)
  464. self.client.write(command + "\r") # sending the command
  465. #print "Reading the output..."
  466. response = [] # erase last response
  467. shell_line =''
  468. while not self.prompt in shell_line:
  469. shell_line = self.client.read_until(self.prompt, self.timeout)
  470. response.append(shell_line) # join the output
  471. # on brocade, it will ask you to press enter to continue
  472. if ("--More--" in shell_line) or ("Type <CR>" in shell_line):
  473. print "I'm Sending the space caracter to continue."
  474. self.client.write(chr(32)) # chr(32) is the space caracter
  475. self.client.write('\n') # Also send return in case of the last line.
  476. # Cleaning the response
  477. #response = response.replace('--More--','')
  478. #response = response.replace('Type <CR> or <SPACE BAR> to continue, <q> to stop','')
  479. response = ''.join(response)
  480. return response
  481. ####################################################
  482. ### Parsing Functions
  483. ####################################################
  484. #####################"
  485. def ParseUptime(switch, input):
  486. """
  487. ParseUptime(switch, input) -> Boolean
  488. Parse to find an uptime (status, description)
  489. @param input: type of check
  490. @type input: bool
  491. @rtype: bool
  492. """
  493. lines = input.splitlines()
  494. if switch.type == "cisco":
  495. regexp = re.compile(r".*uptime:\s+(\d+)\sdays,\s(\d+)\shours,\s(\d+)\sminutes,\s(\d+)\sseconds$", re.IGNORECASE)
  496. system_line = [line for line in lines if line.startswith("System uptime")]
  497. kernel_line = [line for line in lines if line.startswith("Kernel uptime")]
  498. active_line = [line for line in lines if line.startswith("Active supervisor uptime")]
  499. if (not system_line[0]) or (not kernel_line[0]) or (not active_line[0]):
  500. return False
  501. sys_matchreg = [regexp.match(line) for line in system_line]
  502. kern_matchreg = [regexp.match(line) for line in kernel_line]
  503. active_matchreg = [regexp.match(line) for line in active_line]
  504. if (not sys_matchreg[0]) or (not kern_matchreg[0]) or (not active_matchreg[0]):
  505. return False
  506. days, hours, minutes, seconds = sys_matchreg[0].group(1), sys_matchreg[0].group(2), sys_matchreg[0].group(3), sys_matchreg[0].group(4)
  507. switch.sys_uptime = int(minutes) + 60 * int(hours) + 1440 * int(days)
  508. days, hours, minutes, seconds = kern_matchreg[0].group(1), kern_matchreg[0].group(2), kern_matchreg[0].group(3), kern_matchreg[0].group(4)
  509. switch.kernel_uptime = int(minutes) + 60 * int(hours) + 1440 * int(days)
  510. days, hours, minutes, seconds = active_matchreg[0].group(1), active_matchreg[0].group(2), active_matchreg[0].group(3), active_matchreg[0].group(4)
  511. switch.active_uptime = int(minutes) + 60 * int(hours) + 1440 * int(days)
  512. return True
  513. elif switch.type == "brocade":
  514. #line = 3:08pm up for 469 days 2 hrs 21 mins
  515. #12:48pm up for 473 days 2 mins
  516. regexp = re.compile(r".*\s+(\d+)\sdays\s+(\d+)\shrs\s+(\d+)\smins", re.IGNORECASE)
  517. matchreg = [regexp.match(line) for line in lines]
  518. if not matchreg[0]:
  519. return False
  520. days, hours, minutes = matchreg[0].group(1), matchreg[0].group(2), matchreg[0].group(3)
  521. switch.uptime = int(minutes) + 60 * int(hours) + 1440 * int(days)
  522. return True
  523. elif switch.type == "mcdata":
  524. #show fru
  525. #FRU Position State Serial Num Part Num Beacon Pwr On Hrs
  526. #-------- -------- ------ ---------- ------------------- ------ ----------
  527. #CTP 0 Active E11111111 111111111 off 12662
  528. #Power 0 Active
  529. #Power 1 Active
  530. regexp = re.compile(r"^CTP.*\s+(\d+).*$", re.IGNORECASE)
  531. matchreg = [regexp.match(line) for line in lines if line.startswith(u"CTP")]
  532. if not matchreg[0]:
  533. return False
  534. hours = matchreg[0].group(1)
  535. switch.uptime = 60 * int(hours)
  536. return True
  537. else:
  538. return False
  539. ######################
  540. def ParseEnvironment(switch, input):
  541. """
  542. ParseEnvironment(switch, input) -> Boolean
  543. Parse to find an uptime (status, description)
  544. @param input: type of check
  545. @type input: bool
  546. @rtype: bool
  547. """
  548. lines = input.splitlines()
  549. if switch.type == "cisco":
  550. switch.fan_list = []
  551. switch.clock_list = []
  552. switch.temp_list = []
  553. switch.ps_list = []
  554. switch.module_list = []
  555. fan_flag = False
  556. clock_flag = False
  557. temp_flag = False
  558. ps_flag = False
  559. module_flag = False
  560. fan_regexp = re.compile(u"^([^\s]+)\s+(.*)\s+([^\s]+)\s+([^\s]+)", re.IGNORECASE)
  561. #clock_regexp = re.compile(u"^([^\s]+)\s+(.*)\s+([^\s]+)\s+([^\s]+)", re.IGNORECASE)
  562. temp_regexp = re.compile(u"^([^\s]+)\s+([^\s]+)\s+([^\s]+)\s+([^\s]+)\s+([^\s]+)\s+([^\s]+)", re.IGNORECASE)
  563. ps_regexp = re.compile(u"^([^\s]+)\s+([^\s]*)\s+([^\s]+)\s+([^\s]+)\s+([^\s]+)", re.IGNORECASE)
  564. module_regexp = re.compile(u"^([^\s]+)\s+([^\s]*)\s+[^\s]+\s+[^\s]+\s+[^\s]+\s+[^\s]+\s+([^\s]+)", re.IGNORECASE)
  565. for line in lines:
  566. #print fan_flag
  567. if line.startswith("Fan:"):
  568. fan_flag = True
  569. if line.startswith("Clock:"):
  570. clock_flag = True
  571. if line.startswith("Temperature:"):
  572. temp_flag = True
  573. if line.startswith("Power Supply:"):
  574. ps_flag = True
  575. temp_flag = False
  576. if line.startswith("Mod "):
  577. module_flag = True
  578. if line is "":
  579. fan_flag = False
  580. clock_flag = False
  581. ps_flag = False
  582. module_flag = False
  583. if fan_flag:
  584. matchreg = fan_regexp.match(line)
  585. if matchreg:
  586. fan = name, model, hw, status = matchreg.group(1), matchreg.group(2), matchreg.group(3), matchreg.group(4)
  587. if not "Status" in status:
  588. switch.fan_list.append(fan)
  589. if clock_flag:
  590. clock_list = line.split(' ')
  591. clock_list = [list for list in clock_list if not list.startswith('---') ]
  592. if ( len(clock_list) > 1 ) and ( not clock_list[0].startswith(u"Clock") ):
  593. #if (not clock_list[0].startswith(u"Clock")):
  594. clock = name, model, hw, status = clock_list[0], clock_list[1], clock_list[2], clock_list[-1]
  595. switch.clock_list.append(clock)
  596. if temp_flag:
  597. matchreg = temp_regexp.match(line)
  598. if matchreg:
  599. temperature = module, name, MajorThresh, MinorThresh, CurTemp, status = matchreg.group(1), matchreg.group(2), matchreg.group(3), matchreg.group(4), matchreg.group(5), matchreg.group(6)
  600. if not "Status" in status:
  601. switch.temp_list.append(temperature)
  602. if ps_flag:
  603. matchreg = ps_regexp.match(line)
  604. if matchreg:
  605. ps = number, model, Watts, Amp, status = matchreg.group(1), matchreg.group(2), matchreg.group(3), matchreg.group(4), matchreg.group(5)
  606. if not "Status" in status:
  607. switch.ps_list.append(ps)
  608. if module_flag:
  609. matchreg = module_regexp.match(line)
  610. if matchreg:
  611. module = number, model, status = matchreg.group(1), matchreg.group(2), matchreg.group(3)
  612. if not ("Status" in status or "---" in status):
  613. switch.module_list.append(module)
  614. if not matchreg:
  615. return False
  616. else:
  617. return True
  618. elif switch.type == "brocade":
  619. #switchStatusShow command looks like :
  620. #SwitchState: HEALTHY
  621. #Duration: 23188:47
  622. #Power supplies monitor HEALTHY
  623. #Temperatures monitor HEALTHY
  624. #Fans monitor HEALTHY
  625. #Flash monitor HEALTHY
  626. #Marginal ports monitor HEALTHY
  627. #Faulty ports monitor HEALTHY
  628. #Missing SFPs monitor HEALTHY
  629. temp_flag = False
  630. switchstate_line = [line for line in lines if line.startswith("SwitchState")]
  631. ps_line = [line for line in lines if line.startswith("Power supplies monitor")]
  632. temp_line = [line for line in lines if line.startswith("Temperatures monitor")]
  633. fan_line = [line for line in lines if line.startswith("Fans monitor")]
  634. flash_line = [line for line in lines if line.startswith("Flash monitor")]
  635. marginal_port_line = [line for line in lines if line.startswith("Marginal ports monitor")]
  636. faulty_port_line = [line for line in lines if line.startswith("Faulty ports monitor")]
  637. missing_SFP_line = [line for line in lines if line.startswith("Missing SFPs monitor")]
  638. if (not switchstate_line[0]) or (not ps_line[0]) or (not temp_line[0]) or (not fan_line[0]) or (not flash_line[0]) or (not marginal_port_line[0]) or (not faulty_port_line[0]) or (not missing_SFP_line[0]) :
  639. return False
  640. switch_state = ps_line[0].split()
  641. switch.switch_state = switch_state[-1]
  642. ps_state = ps_line[0].split()
  643. switch.ps_state = ps_state[-1]
  644. temp_state = temp_line[0].split()
  645. switch.temp_state = temp_state[-1]
  646. fan_state = fan_line[0].split()
  647. switch.fan_state = fan_state[-1]
  648. flash_state = flash_line[0].split()
  649. switch.flash_state = flash_state[-1]
  650. marginal_port_state = marginal_port_line[0].split()
  651. switch.marginal_port_state = marginal_port_state[-1]
  652. faulty_port_state = faulty_port_line[0].split()
  653. switch.faulty_port_state = faulty_port_state[-1]
  654. missing_SFP_state = missing_SFP_line[0].split()
  655. switch.missing_SFP_state = missing_SFP_state[-1]
  656. switch.fan_list = []
  657. switch.temp_list = []
  658. switch.ps_list = []
  659. #fanShow
  660. #Fan 1 is Ok, speed is 5400 RPM
  661. #Fan 2 is Ok, speed is 5578 RPM
  662. #Fan 3 is Ok, speed is 5532 RPM
  663. fans_line = [line for line in lines if ( line.startswith("Fan") and not line.startswith("Fans") )]
  664. if not fans_line:
  665. return False
  666. for line in fans_line:
  667. #print line
  668. fan_list = line.split()
  669. fan = number, status, rpm = fan_list[1], fan_list[3], fan_list[-2]
  670. switch.fan_list.append(fan)
  671. #psShow
  672. #Power Supply #1 is OK
  673. #Power Supply #2 is OK
  674. ps_line = [line for line in lines if line.startswith("Power Supply #")]
  675. if not ps_line:
  676. return False
  677. for line in ps_line:
  678. #print line
  679. ps_list = line.split()
  680. ps = number, status = ps_list[2], ps_list[-1]
  681. switch.ps_list.append(ps)
  682. #tempShow
  683. #Sensor State Centigrade Fahrenheit
  684. # ID
  685. #==============================================
  686. # 1 Ok 40 104
  687. # 2 Ok 41 105
  688. for line in lines:
  689. if line.startswith("Sensor"):
  690. temp_flag = True
  691. if temp_flag:
  692. if (not u"Sensor" in line) and not line.startswith("===") and not line.lstrip().startswith(u"ID") :
  693. #print line
  694. temp_list = line.split()
  695. #print temp_list
  696. if temp_list:
  697. temp = id, status, centigrade, fahrenheit = temp_list[0], temp_list[1], temp_list[2], temp_list[3]
  698. switch.temp_list.append(temp)
  699. return True
  700. elif switch.type == "mcdata":
  701. return False
  702. else:
  703. return False
  704. #####################
  705. def ParseResources(switch, input):
  706. """
  707. ParseResources(switch, input) -> Boolean
  708. Parse to find an uptime (status, description)
  709. @param input: type of check
  710. @type input: bool
  711. @rtype: bool
  712. """
  713. lines = input.splitlines()
  714. cpu_flag = False
  715. mem_flag = False
  716. proc_flag = False
  717. if switch.type == "cisco":
  718. cpu_line = [line for line in lines if line.startswith("CPU")]
  719. mem_line = [line for line in lines if line.startswith("Memory")]
  720. proc_line = [line for line in lines if line.startswith("Processes")]
  721. if (not cpu_line) or (not mem_line) or (not proc_line):
  722. return False
  723. cpu_regexp = re.compile(u"^CPU\sstates\s+:\s+(\d+).*\s+(\d+).*\s+(\d+).*\sidle", re.IGNORECASE)
  724. mem_regexp = re.compile(u"^Memory\susage.*\s+(\d+).*\s+(\d+).*\s+(\d+).*\sfree", re.IGNORECASE)
  725. proc_regexp = re.compile(u"^Processes\s+:\s+(\d+).*\s+(\d+)\srunning", re.IGNORECASE)
  726. proc_matchreg = [proc_regexp.search(line) for line in proc_line]
  727. cpu_matchreg = [cpu_regexp.match(line) for line in cpu_line]
  728. mem_matchreg = [mem_regexp.match(line) for line in mem_line]
  729. if (not proc_matchreg) or (not cpu_matchreg) or (not mem_matchreg):
  730. return False
  731. switch.cpu = user, kernel, idle = cpu_matchreg[0].group(1), cpu_matchreg[0].group(2), cpu_matchreg[0].group(3)
  732. switch.mem = total, used, free = mem_matchreg[0].group(1), mem_matchreg[0].group(2), mem_matchreg[0].group(3)
  733. switch.proc = total, running = proc_matchreg[0].group(1), proc_matchreg[0].group(2)
  734. return True
  735. elif switch.type == "brocade":
  736. return False
  737. elif switch.type == "mcdata":
  738. return False
  739. else:
  740. return False
  741. #####################
  742. def ParseInterfaces(switch, input):
  743. """
  744. ParseInterfaces(switch, input) -> Boolean
  745. Parse to find an uptime (status, description)
  746. @param input: type of check
  747. @type input: bool
  748. @rtype: bool
  749. """
  750. lines = input.splitlines()
  751. if switch.type == "cisco":
  752. sfp_flag = False
  753. ip_flag = False
  754. fcip_flag = False
  755. int_flag = False
  756. switch.int_list = []
  757. switch.sfp_list = []
  758. switch.ip_list = []
  759. switch.fcip_list = []
  760. for line in lines:
  761. if "SFP" in line:
  762. sfp_flag = True
  763. if "MTU" in line:
  764. ip_flag = True
  765. if "fcip" in line:
  766. fcip_flag = True
  767. if "Interface" in line:
  768. int_flag = True
  769. if line is "":
  770. sfp_flag = False
  771. ip_flag = False
  772. fcip_flag = False
  773. int_flag = False
  774. if sfp_flag:
  775. if "Mode" in line:
  776. continue
  777. if line.startswith('---'):
  778. continue
  779. if line.startswith(u'Interface'):
  780. continue
  781. words = line.split()
  782. #line = fc1/1 1 E auto up swl E 2 --
  783. int_sfp = name, admin_mode, status, oper_mode = words[0], words[2], words[4], words[6]
  784. switch.sfp_list.append(int_sfp)
  785. interface = name, status, mode = words[0], words[4], words[6]
  786. switch.int_list.append(interface)
  787. #print interface
  788. if ip_flag:
  789. if "Channel" in line:
  790. continue
  791. if line.startswith('---'):
  792. continue
  793. if line.startswith(u'Interface'):
  794. continue
  795. words = line.split()
  796. #line = GigabitEthernet1/1 down -- auto 1500 --
  797. #line = mgmt0 up 160.92.239.104/24 100 Mbps 1500
  798. int_ip = name, status, address = words[0], words[1], words[2]
  799. switch.ip_list.append(int_ip)
  800. interface = name, status, mode = words[0], words[1], "N/A"
  801. switch.int_list.append(interface)
  802. #print interface
  803. if fcip_flag:
  804. if "Mode" in line:
  805. continue
  806. if line.startswith('---'):
  807. continue
  808. if line.startswith(u'Interface'):
  809. continue
  810. words = line.split()
  811. int_fcip = name, admin_mode, status, oper_mode, Eth = words[0], words[2], words[4], words[5], words[7]
  812. switch.fcip_list.append(int_fcip)
  813. interface = name, status, mode = words[0], words[4], words[5]
  814. switch.int_list.append(interface)
  815. #print interface
  816. if int_flag:
  817. if u"Gbps" in line:
  818. continue
  819. if u"Mode" in line:
  820. continue
  821. if line.startswith('---'):
  822. continue
  823. if line.startswith(u'Interface'):
  824. continue
  825. words = line.split()
  826. if len(words) == 3:
  827. interface = name, status, mode = words[0], words[1], "N/A"
  828. switch.int_list.append(interface)
  829. if not switch.int_list:
  830. return False
  831. return True
  832. elif switch.type == "brocade":
  833. return False
  834. elif switch.type == "mcdata":
  835. return False
  836. else:
  837. return False
  838. #####################
  839. def ParseInterfacesDescription(switch, input):
  840. """
  841. ParseInterfacesDescription(switch, input) -> Boolean
  842. Parse to find interfaces description port name, port description
  843. @param input: type of check
  844. @type input: bool
  845. @rtype: bool
  846. """
  847. lines = input.splitlines()
  848. if switch.type == "cisco":
  849. switch.int_descr_list = []
  850. for line in lines:
  851. if line.startswith('---'):
  852. continue
  853. if line.startswith(u'Interface'):
  854. continue
  855. if line is "":
  856. continue
  857. regexp = re.compile(u"^([^\s]+)\s+(.*)", re.IGNORECASE)
  858. matchreg = regexp.match(line)
  859. if matchreg:
  860. interface = name, description = matchreg.group(1), matchreg.group(2)
  861. switch.int_descr_list.append(interface)
  862. if not switch.int_descr_list:
  863. return False
  864. return True
  865. elif switch.type == "brocade":
  866. return False
  867. elif switch.type == "mcdata":
  868. return False
  869. else:
  870. return False
  871. #################################
  872. def output(code, msg=''):
  873. outfp = sys.stdout
  874. if msg:
  875. print >> outfp, msg
  876. sys.exit(code)
  877. ################################################################
  878. ## CheckUptime (paramiko)
  879. ################################################################
  880. def CheckUptime(switch, warning_threshold, critical_threshold):
  881. """
  882. CheckUptime(switch, warning_threshold, critical_threshold)
  883. Check a switch's uptime for Nagios.
  884. @param check_type: type of check
  885. @type check_type: str
  886. """
  887. if switch.type == "cisco":
  888. switch.uptime_command = "show system uptime"
  889. elif switch.type == "brocade":
  890. #switch.uptime_command = "uptime"
  891. switch.uptime_command = "switchuptime"
  892. elif switch.type == "mcdata":
  893. switch.uptime_command = "show fru"
  894. uptime = switch.GetCommand(switch.uptime_command)
  895. switch.client.close()
  896. if not ParseUptime(switch, uptime):
  897. output(STATE_UNKNOWN, "UNKNOWN : incorrect switch output : " + str(uptime))
  898. else:
  899. if switch.type == "cisco":
  900. if ( switch.sys_uptime <= int(critical_threshold) ) and ( switch.kernel_uptime <= int(critical_threshold) ) and ( switch.active_uptime <= int(critical_threshold) ):
  901. output(STATE_CRITICAL, "CRITICAL : Device has rebooted ! System Uptime: " + str(switch.sys_uptime) +
  902. " minutes. Kernel uptime: "+ str(switch.kernel_uptime) +
  903. " minutes. Active supervisor uptime: "+ str(switch.active_uptime) +
  904. " minutes.")
  905. elif ( switch.sys_uptime <= int(warning_threshold) ) and ( switch.kernel_uptime <= int(warning_threshold) ) and ( switch.active_uptime <= int(warning_threshold) ):
  906. output(STATE_WARNING, "WARNING : Device has rebooted ! Uptime : " + str(switch.sys_uptime) +
  907. " minutes. Kernel uptime: "+ str(switch.kernel_uptime) +
  908. " minutes. Active supervisor uptime: "+ str(switch.active_uptime) +
  909. " minutes.")
  910. else:
  911. output(STATE_OK, "OK : Device uptime : " + str(switch.sys_uptime) +
  912. " minutes. Kernel uptime: "+ str(switch.kernel_uptime) +
  913. " minutes. Active supervisor uptime: "+ str(switch.active_uptime) +
  914. " minutes.")
  915. elif switch.type == "brocade":
  916. if ( switch.uptime <= int(critical_threshold) ):
  917. output(STATE_CRITICAL, "CRITICAL : Device has rebooted ! System Uptime: " + str(switch.uptime) +" minutes.")
  918. elif ( switch.uptime <= int(warning_threshold) ):
  919. output(STATE_WARNING, "WARNING : Device has rebooted ! System Uptime: " + str(switch.uptime) +" minutes.")
  920. else:
  921. output(STATE_OK, "OK : Device uptime : " + str(switch.uptime) +" minutes.")
  922. elif switch.type == "mcdata":
  923. if ( switch.uptime <= int(critical_threshold) ):
  924. output(STATE_CRITICAL, "CRITICAL : Device has rebooted ! System Uptime: " + str(switch.uptime) +" minutes.")
  925. elif ( switch.uptime <= int(warning_threshold) ):
  926. output(STATE_WARNING, "WARNING : Device has rebooted ! System Uptime: " + str(switch.uptime) +" minutes.")
  927. else:
  928. output(STATE_OK, "OK : Device uptime : " + str(switch.uptime) +" minutes.")
  929. ################################################################
  930. ## CheckEnv (paramiko)
  931. ################################################################
  932. def CheckEnv(switch, warning_threshold, critical_threshold):
  933. """
  934. CheckEnv(switch, warning_threshold, critical_threshold)
  935. Check a switch's environment for Nagios.
  936. @param check_type: type of check
  937. @type check_type: str
  938. """
  939. if switch.type == "cisco":
  940. switch.environment_command = "show environment"
  941. env = switch.GetCommand(switch.environment_command)
  942. elif switch.type == "brocade":
  943. switch.environment_command = "switchStatusShow"
  944. switch.fan_command = "fanShow"
  945. switch.ps_command = "psShow"
  946. switch.temp_command = "tempShow"
  947. env = switch.GetCommand(switch.environment_command)
  948. env += "\n"
  949. env += switch.GetCommand(switch.fan_command)
  950. env += "\n"
  951. env += switch.GetCommand(switch.ps_command)
  952. env += "\n"
  953. env += switch.GetCommand(switch.temp_command)
  954. elif switch.type == "mcdata":
  955. switch.environment_command = "show all"
  956. env = switch.GetCommand(switch.environment_command)
  957. switch.client.close()
  958. if not ParseEnvironment(switch, env):
  959. output(STATE_UNKNOWN, "UNKNOWN : incorrect switch output : " + str(env))
  960. else:
  961. if switch.type == "cisco":
  962. nb_failed = 0
  963. msg = []
  964. for (name, model, hw, status) in switch.fan_list:
  965. if not str(status).startswith("ok") :
  966. nb_failed += 1
  967. msg.append("Fan "+str(name) + " is in status: " + str(status) + " (model: "+str(model)+ ") ! ")
  968. else:
  969. msg.append("Fan "+str(name) + " is: " + str(status) + ". ")
  970. for (name, model, hw, status) in switch.clock_list:
  971. if str(status).lstrip().startswith("ok") or "not present" in status:
  972. msg.append("Clock "+str(name) + " is: " + str(status) + ". ")
  973. else:
  974. nb_failed += 1
  975. msg.append("Clock "+str(name) + " is in status: " + str(status) + " ! ")
  976. for (module, name, MajorThresh, MinorThresh, CurTemp, status) in switch.temp_list:
  977. if not str(status).startswith("ok") :
  978. nb_failed += 1
  979. msg.append("Temp "+str(name) + ", Module "+ str(module) +" is in status: " + str(status) + " ! ")
  980. else:
  981. msg.append("Temp "+str(name) + ", Module "+ str(module) +" is: " + str(status) + ". ")
  982. for (number, model, Watts, Amp, status) in switch.ps_list:
  983. if not str(status).startswith("ok") :
  984. nb_failed += 1
  985. msg.append("Power Supply " + str(number) + " is in status: " + str(status) + " ! ")
  986. else:
  987. msg.append("Power Supply " + str(number) + " is: " + str(status) + ". ")
  988. for (number, model, status) in switch.module_list:
  989. if not str(status).startswith("powered-up") :
  990. nb_failed += 1
  991. msg.append("Module " + str(number) + " is in status: " + str(status) + " ! ")
  992. else:
  993. msg.append("Module " + str(number) + " is: " + str(status) + ". ")
  994. msg = ''.join(msg)
  995. if ( nb_failed >= int(critical_threshold) ):
  996. output(STATE_CRITICAL, "CRITICAL: " + str(msg))
  997. elif ( nb_failed >= int(warning_threshold) ):
  998. output(STATE_WARNING, "WARNING: " + str(msg))
  999. else:
  1000. output(STATE_OK, "OK: " + str(msg))
  1001. elif switch.type == "brocade":
  1002. nb_failed = 0
  1003. msg = []
  1004. if not switch.switch_state.startswith("HEALTHY"):
  1005. nb_failed += 1
  1006. msg.append("Switch status is: "+ str(switch.switch_state) + " ! ")
  1007. else:
  1008. msg.append("Switch status is: "+ str(switch.switch_state) + ". ")
  1009. if not switch.ps_state.startswith("HEALTHY"):
  1010. nb_failed += 1
  1011. msg.append("Power Supplies status is: "+ str(switch.ps_state) + " ! ")
  1012. else:
  1013. msg.append("Power Supplies is: "+ str(switch.ps_state) + ". ")
  1014. if not switch.temp_state.startswith("HEALTHY"):
  1015. nb_failed += 1
  1016. msg.append("Temperatures status is: "+ str(switch.temp_state) + " ! ")
  1017. else:
  1018. msg.append("Temperatures is: "+ str(switch.temp_state) + ". ")
  1019. if not switch.fan_state.startswith("HEALTHY"):
  1020. nb_failed += 1
  1021. msg.append("Fans status is: "+ str(switch.fan_state) + " ! ")
  1022. else:
  1023. msg.append("Fans is: "+ str(switch.fan_state) + ". ")
  1024. if not switch.flash_state.startswith("HEALTHY"):
  1025. nb_failed += 1
  1026. msg.append("Flash monitor status is: "+ str(switch.flash_state) + " ! ")
  1027. else:
  1028. msg.append("Flash monitor is: "+ str(switch.flash_state) + ". ")
  1029. if not switch.marginal_port_state.startswith("HEALTHY"):
  1030. nb_failed += 1
  1031. msg.append("Marginal Ports status is: "+ str(switch.marginal_port_state) + " ! ")
  1032. else:
  1033. msg.append("Marginal Ports is: "+ str(switch.marginal_port_state) + ". ")
  1034. if not switch.faulty_port_state.startswith("HEALTHY"):
  1035. nb_failed += 1
  1036. msg.append("Faulty Ports status is: "+ str(switch.faulty_port_state) + " ! ")
  1037. else:
  1038. msg.append("Faulty Ports is: "+ str(switch.faulty_port_state) + ". ")
  1039. if not switch.missing_SFP_state.startswith("HEALTHY"):
  1040. nb_failed += 1
  1041. msg.append("Missing SFP status is: "+ str(switch.missing_SFP_state) + " ! ")
  1042. else:
  1043. msg.append("Missing SFP is: "+ str(switch.missing_SFP_state) + ". ")
  1044. for (number, status, rpm) in switch.fan_list:
  1045. if not str(status).startswith("Ok") :
  1046. nb_failed += 1
  1047. msg.append("Fan "+str(number) + " is in status: " + str(status) + " (RPM: "+str(rpm)+ ") ! ")
  1048. else:
  1049. msg.append("Fan "+str(number) + " is: " + str(status) + " (RPM: "+str(rpm)+ "). ")
  1050. for (id, status, centigrade, fahrenheit) in switch.temp_list:
  1051. if not str(status).startswith("Ok") :
  1052. nb_failed += 1
  1053. msg.append("Temp "+str(id) + " is in status: " + str(status) + " ("+str(centigrade)+ " C) ! ")
  1054. else:
  1055. msg.append("Temp "+str(id) + " is: " + str(status) + " ("+str(centigrade)+ " C). ")
  1056. for (number, status) in switch.ps_list:
  1057. if not str(status).startswith("OK") :
  1058. nb_failed += 1
  1059. msg.append("Power Supply " + str(number) + " is in status: " + str(status) + " ! ")
  1060. else:
  1061. msg.append("Power Supply " + str(number) + " is: " + str(status) + ". ")
  1062. msg = ''.join(msg)
  1063. if ( nb_failed >= int(critical_threshold) ):
  1064. output(STATE_CRITICAL, "CRITICAL: " + str(msg))
  1065. elif ( nb_failed >= int(warning_threshold) ):
  1066. output(STATE_WARNING, "WARNING: " + str(msg))
  1067. else:
  1068. output(STATE_OK, "OK: " + str(msg))
  1069. elif switch.type == "mcdata":
  1070. if ( switch.uptime <= int(critical_threshold) ):
  1071. output(STATE_CRITICAL, "CRITICAL : Device has rebooted ! System Uptime: " + str(switch.uptime) +" minutes.")
  1072. elif ( switch.uptime <= int(warning_threshold) ):
  1073. output(STATE_WARNING, "WARNING : Device has rebooted ! System Uptime: " + str(switch.uptime) +" minutes.")
  1074. else:
  1075. output(STATE_OK, "OK : Device uptime : " + str(switch.uptime) +" minutes.")
  1076. ################################################################
  1077. ## CheckResources (paramiko)
  1078. ################################################################
  1079. def CheckResources(switch, warning_threshold, critical_threshold):
  1080. """
  1081. CheckResources(switch, warning_threshold, critical_threshold)
  1082. Check a switch's resources cpu and mem for Nagios.
  1083. @param check_type: type of check
  1084. @type check_type: str
  1085. """
  1086. if switch.type == "cisco":
  1087. switch.resources_command = "show system resources"
  1088. elif switch.type == "brocade":
  1089. switch.resources_command = "uptime"
  1090. switch.resources_command = "memShow"
  1091. elif switch.type == "mcdata":
  1092. output(STATE_WARNING, "WARNING : Not Possible on mcdata's switch")
  1093. resources = switch.GetCommand(switch.resources_command)
  1094. switch.client.close()
  1095. if not ParseResources(switch, resources):
  1096. output(STATE_UNKNOWN, "UNKNOWN : incorrect switch output: " + str(resources))
  1097. else:
  1098. crit_flag = False
  1099. warn_flag = False
  1100. msg = []
  1101. (total, used, free) = switch.mem
  1102. mem_used_perc = int(100 * ( float(used) / float(total) ))
  1103. (user, kernel, idle) = switch.cpu
  1104. cpu_used_perc = int(user) + int(kernel)
  1105. if ( int(mem_used_perc) >= int(critical_threshold) ):
  1106. crit_flag = True
  1107. msg.append("Memory usage is Critical ! ")
  1108. elif ( int(mem_used_perc) >= int(warning_threshold) ):
  1109. warn_flag = True
  1110. msg.append("Memory usage is higher than warning threshold ! ")
  1111. if ( int(cpu_used_perc) >= int(critical_threshold) ):
  1112. crit_flag = True
  1113. msg.append("CPU usage is Critical ! ")
  1114. elif ( int(cpu_used_perc) >= int(warning_threshold) ):
  1115. warn_flag = True
  1116. msg.append("CPU usage is higher than warning threshold ! ")
  1117. (total, running) = switch.proc
  1118. msg.append("CPU usage: " + str(cpu_used_perc) + " %. Memory usage: "+ str(mem_used_perc) + " %. Total Processes: " + str(total) + ". " + str(running) + " running.")
  1119. msg = ''.join(msg)
  1120. if crit_flag:
  1121. output(STATE_CRITICAL, "CRITICAL: " + str(msg))
  1122. elif warn_flag:
  1123. output(STATE_WARNING, "WARNING: " + str(msg))
  1124. else:
  1125. output(STATE_OK, "OK: " + str(msg))
  1126. ################################################################
  1127. ## CheckInterfaces (paramiko)
  1128. ################################################################
  1129. def CheckInterfaces(switch, warning_threshold, critical_threshold):
  1130. """
  1131. CheckInterfaces(switch, warning_threshold, critical_threshold)
  1132. Check a switch's interfaces for Nagios.
  1133. @param check_type: type of check
  1134. @type check_type: str
  1135. """
  1136. if switch.type == "cisco":
  1137. switch.interfaces_command = "show interface brief"
  1138. switch.interfaces_description_command = "show interface description"
  1139. elif switch.type == "brocade":
  1140. switch.interfaces_command = "diagShow"
  1141. switch.interfaces_command2 = "switchShow"
  1142. switch.interfaces_description_command = ""
  1143. elif switch.type == "mcdata":
  1144. switch.interfaces_command = "show port opticHealth"
  1145. switch.interfaces_command2 = "show port status"
  1146. switch.interfaces_description_command = "show port config"
  1147. interfaces = switch.GetCommand(switch.interfaces_command)
  1148. interfaces_descr = switch.GetCommand(switch.interfaces_description_command)
  1149. switch.client.close()
  1150. if not ParseInterfaces(switch, interfaces):
  1151. output(STATE_UNKNOWN, "UNKNOWN : incorrect switch output: " + str(interfaces))
  1152. if not ParseInterfacesDescription(switch, interfaces_descr):
  1153. output(STATE_UNKNOWN, "UNKNOWN : incorrect switch output: " + str(interfaces_descr))
  1154. else:
  1155. crit_flag = False
  1156. warn_flag = False
  1157. msg = []
  1158. failed_list = []
  1159. for (name, status, mode) in switch.int_list:
  1160. if not status.startswith('up') and not status.startswith('down') and not status.startswith('trunking'):
  1161. descr_list = [description for (descr_name, description) in switch.int_descr_list if descr_name == name]
  1162. if descr_list[0]:
  1163. description = descr_list[0]
  1164. else:
  1165. description = "No description"
  1166. failed_list.append((name, status, mode,

Large files files are truncated, but you can click here to view the full file