Advertisement
Guest User

Untitled

a guest
May 8th, 2017
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 5.79 KB | None | 0 0
  1. #!/usr/bin/env python
  2. import paramiko
  3. import sys
  4.  
  5. # LSHW parsing
  6. def ls_parse_branch(lines, depth=1):
  7. data = {}
  8. while len(lines):
  9. line = lines.pop(0)
  10. if line[depth:].startswith(' ') and ':' in line:
  11. index = line.index(':')
  12. key = line[depth+3:index]
  13. value = line[index+2:]
  14. data[key] = value
  15. elif line[depth:].startswith(' *-'):
  16. key = line[depth+3:]
  17. # Check if key has a status
  18. status = None
  19. if ' ' in key:
  20. key, status = key.split(' ')
  21.  
  22. # Check if key is a list member
  23. index = None
  24. if ':' in key:
  25. key, index = key.split(':')
  26. index = int(index)
  27.  
  28. lines, sub_branch = ls_parse_branch(lines, depth+3)
  29. if status is not None:
  30. sub_branch['status'] = status
  31. if index is not None:
  32. if key not in data:
  33. data[key] = []
  34. data[key].insert(index, sub_branch)
  35. else:
  36. data[key] = sub_branch
  37. else:
  38. return [line] + lines, data
  39. return [], data
  40.  
  41.  
  42. def lshw_parse(lines):
  43. # If string given, split into list of lines
  44. if isinstance(lines, str):
  45. lines = lines.splitlines()
  46.  
  47. # First line is hostname
  48. hostname = lines.pop(0).strip()
  49.  
  50. # Parse remaining lines
  51. data = ls_parse_branch(lines)[1]
  52.  
  53. data['hostname'] = hostname
  54. return data
  55.  
  56. # LSPCI parsing
  57. def lspci_tree(lines):
  58. data = {}
  59. parameters = ['LnkCap', 'LnkSta', 'Kernel modules']
  60. while len(lines):
  61. line = lines.pop(0)
  62. if not line.startswith('\t'):
  63. return [line] + lines, data
  64. else:
  65. for parameter in parameters:
  66. if line.startswith('\t\t{}:'.format(parameter)):
  67. data[parameter] = line[len(parameter)+3:]
  68. elif line.startswith('\t{}:'.format(parameter)):
  69. data[parameter] = line[len(parameter)+2:]
  70. return lines, data
  71.  
  72. def lspci_device(lines):
  73. line = lines.pop(0)
  74. bus_separator = line.index(' ')
  75. desc_seperator = bus_separator + line[bus_separator:].index(':')
  76. bus = line[:bus_separator]
  77. lines, data = lspci_tree(lines)
  78. data['Type'] = line[bus_separator+1:desc_seperator]
  79. data['Description'] = line[desc_seperator+2:]
  80. return lines, bus, data
  81.  
  82. def lspci_parse(lines):
  83. devices = {}
  84. # Ensure lines is a list of non-empty strings
  85. if isinstance(lines, str):
  86. lines = [x for x in lines.splitlines() if x.strip()]
  87. else:
  88. lines = [x for x in lines if x.strip()]
  89.  
  90. while len(lines):
  91. lines, bus, data = lspci_device(lines)
  92. if not data['Description'].startswith('IBM Device 0'):
  93. devices[bus] = data
  94. return devices
  95.  
  96.  
  97.  
  98. class G2_SSH(object):
  99. ''' SSH-based interface to OpenBMC system '''
  100. def __init__(self, address, username='root', password='0penBmc',
  101. sshtimeout=10):
  102. self.address = address
  103. self.ssh = paramiko.SSHClient()
  104. self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  105. self.ssh.connect(address, timeout=sshtimeout)
  106.  
  107. def command(self, command):
  108. ''' Runs a shell command, returns (stdin, stdout, stderr) handles '''
  109. return self.ssh.exec_command(command)
  110.  
  111. def call(self, command):
  112. stdin, stdout, stderr = self.command(command)
  113. return stdout.read(), stderr.read()
  114.  
  115. def host_state(self):
  116. ''' Returns current state of host '''
  117. stdin, stdout, stderr = self.command('/usr/sbin/obmcutil state')
  118. return stdout.read().rstrip().split(' = ')[-1]
  119.  
  120. def uptime(self):
  121. ''' Returns BMC uptime '''
  122. stdin, stdout, stderr = self.command('uptime')
  123. return stdout.read().strip()
  124.  
  125. def meminfo(self):
  126. ''' Get BMC memoey information '''
  127. stdin, stdout, stderr = self.command('cat /proc/meminfo')
  128. info = {}
  129. for line in stdout.readlines():
  130. key, value = line.split(':')
  131. info[key] = value.strip()
  132. return info
  133.  
  134. def lshw(self):
  135. stdout, stderr = self.call('lshw')
  136. return lshw_parse(stdout)
  137.  
  138. def lspci(self):
  139. stdout, stderr = self.call('lspci -vvv')
  140. return lspci_parse(stdout)
  141.  
  142. try:
  143. target = sys.argv[1]
  144. except:
  145. print 'Usage: {} <target host>'.format(sys.argv[0])
  146. sys.exit(1)
  147.  
  148. print "Connecting to {}...".format(target)
  149. boxen = G2_SSH(target)
  150. print 'Getting info from lshw...'
  151. hw = boxen.lshw()
  152. print 'Getting info from lspci...'
  153. pci = boxen.lspci()
  154.  
  155. print '\nProc Info:'
  156. core_counts = {}
  157. cores_total = 0
  158. for core in hw['core']['cpu']:
  159. if 'slot' in core:
  160. slot = core['slot'][-1]
  161. if slot not in core_counts:
  162. core_counts[slot] = 0
  163. core_counts[slot] += 1
  164. cores_total += 1
  165.  
  166. for socket in sorted(core_counts.keys()):
  167. print ' Cores in socket {}: {}'.format(socket, core_counts[socket])
  168. print ' {} Cores total'.format(cores_total)
  169.  
  170. print '\nMemory Info:'
  171. if 'bank' in hw['core']['memory']:
  172. print ' {} RAM from {} DIMMs'.format(hw['core']['memory']['size'],
  173. len(hw['core']['memory']['bank']))
  174. else:
  175. print ' {} RAM total'.format(hw['core']['memory'])
  176.  
  177. print '\nPCI Devices:'
  178. for bus in pci:
  179. device = pci[bus]
  180. print ' {} - {}'.format(device['Type'], device['Description'])
  181. print ' PCI Bus: {}'.format(bus)
  182. if 'LnkCap' in device:
  183. cap = ', '.join([x.strip() for x in device['LnkCap'].split(',')[1:3]])
  184. print ' Link Capability: {}'.format(cap)
  185. if 'LnkSta' in device:
  186. sta = ', '.join([x.strip() for x in device['LnkSta'].split(',')[0:2]])
  187. print ' Link Status: {}'.format(sta)
  188. if 'Kernel modules' in device:
  189. print ' Kernel Modules: {}'.format(device['Kernel modules'])
  190. print ''
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement