rpc.py 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  1. from __future__ import unicode_literals
  2. import re
  3. import time
  4. from ncclient import manager
  5. import paramiko
  6. import xmltodict
  7. CONNECT_TIMEOUT = 5 # seconds
  8. class RPCClient(object):
  9. def __init__(self, device, username='', password=''):
  10. self.username = username
  11. self.password = password
  12. try:
  13. self.host = str(device.primary_ip.address.ip)
  14. except AttributeError:
  15. raise Exception("Specified device ({}) does not have a primary IP defined.".format(device))
  16. def get_lldp_neighbors(self):
  17. """
  18. Returns a list of dictionaries, each representing an LLDP neighbor adjacency.
  19. {
  20. 'local-interface': <str>,
  21. 'name': <str>,
  22. 'remote-interface': <str>,
  23. 'chassis-id': <str>,
  24. }
  25. """
  26. raise NotImplementedError("Feature not implemented for this platform.")
  27. def get_inventory(self):
  28. """
  29. Returns a dictionary representing the device chassis and installed inventory items.
  30. {
  31. 'chassis': {
  32. 'serial': <str>,
  33. 'description': <str>,
  34. }
  35. 'items': [
  36. {
  37. 'name': <str>,
  38. 'part_id': <str>,
  39. 'serial': <str>,
  40. },
  41. ...
  42. ]
  43. }
  44. """
  45. raise NotImplementedError("Feature not implemented for this platform.")
  46. class SSHClient(RPCClient):
  47. def __enter__(self):
  48. self.ssh = paramiko.SSHClient()
  49. self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  50. try:
  51. self.ssh.connect(
  52. self.host,
  53. username=self.username,
  54. password=self.password,
  55. timeout=CONNECT_TIMEOUT,
  56. allow_agent=False,
  57. look_for_keys=False,
  58. )
  59. except paramiko.AuthenticationException:
  60. # Try default credentials if the configured creds don't work
  61. try:
  62. default_creds = self.default_credentials
  63. if default_creds.get('username') and default_creds.get('password'):
  64. self.ssh.connect(
  65. self.host,
  66. username=default_creds['username'],
  67. password=default_creds['password'],
  68. timeout=CONNECT_TIMEOUT,
  69. allow_agent=False,
  70. look_for_keys=False,
  71. )
  72. else:
  73. raise ValueError('default_credentials are incomplete.')
  74. except AttributeError:
  75. raise paramiko.AuthenticationException
  76. self.session = self.ssh.invoke_shell()
  77. self.session.recv(1000)
  78. return self
  79. def __exit__(self, exc_type, exc_val, exc_tb):
  80. self.ssh.close()
  81. def _send(self, cmd, pause=1):
  82. self.session.send('{}\n'.format(cmd))
  83. data = ''
  84. time.sleep(pause)
  85. while self.session.recv_ready():
  86. data += self.session.recv(4096).decode()
  87. if not data:
  88. break
  89. return data
  90. class JunosNC(RPCClient):
  91. """
  92. NETCONF client for Juniper Junos devices
  93. """
  94. def __enter__(self):
  95. # Initiate a connection to the device
  96. self.manager = manager.connect(host=self.host, username=self.username, password=self.password,
  97. hostkey_verify=False, timeout=CONNECT_TIMEOUT)
  98. return self
  99. def __exit__(self, exc_type, exc_val, exc_tb):
  100. # Close the connection to the device
  101. self.manager.close_session()
  102. def get_lldp_neighbors(self):
  103. rpc_reply = self.manager.dispatch('get-lldp-neighbors-information')
  104. lldp_neighbors_raw = xmltodict.parse(rpc_reply.xml)['rpc-reply']['lldp-neighbors-information']['lldp-neighbor-information']
  105. result = []
  106. for neighbor_raw in lldp_neighbors_raw:
  107. neighbor = dict()
  108. neighbor['local-interface'] = neighbor_raw.get('lldp-local-port-id')
  109. name = neighbor_raw.get('lldp-remote-system-name')
  110. if name:
  111. neighbor['name'] = name.split('.')[0] # Split hostname from domain if one is present
  112. else:
  113. neighbor['name'] = ''
  114. try:
  115. neighbor['remote-interface'] = neighbor_raw['lldp-remote-port-description']
  116. except KeyError:
  117. # Older versions of Junos report on interface ID instead of description
  118. neighbor['remote-interface'] = neighbor_raw.get('lldp-remote-port-id')
  119. neighbor['chassis-id'] = neighbor_raw.get('lldp-remote-chassis-id')
  120. result.append(neighbor)
  121. return result
  122. def get_inventory(self):
  123. def glean_items(node, depth=0):
  124. items = []
  125. items_list = node.get('chassis{}-module'.format('-sub' * depth), [])
  126. # Junos like to return single children directly instead of as a single-item list
  127. if hasattr(items_list, 'items'):
  128. items_list = [items_list]
  129. for item in items_list:
  130. m = {
  131. 'name': item['name'],
  132. 'part_id': item.get('model-number') or item.get('part-number', ''),
  133. 'serial': item.get('serial-number', ''),
  134. }
  135. child_items = glean_items(item, depth + 1)
  136. if child_items:
  137. m['items'] = child_items
  138. items.append(m)
  139. return items
  140. rpc_reply = self.manager.dispatch('get-chassis-inventory')
  141. inventory_raw = xmltodict.parse(rpc_reply.xml)['rpc-reply']['chassis-inventory']['chassis']
  142. result = dict()
  143. # Gather chassis data
  144. result['chassis'] = {
  145. 'serial': inventory_raw['serial-number'],
  146. 'description': inventory_raw['description'],
  147. }
  148. # Gather inventory items
  149. result['items'] = glean_items(inventory_raw)
  150. return result
  151. class IOSSSH(SSHClient):
  152. """
  153. SSH client for Cisco IOS devices
  154. """
  155. def get_inventory(self):
  156. def version():
  157. def parse(cmd_out, rex):
  158. for i in cmd_out:
  159. match = re.search(rex, i)
  160. if match:
  161. return match.groups()[0]
  162. sh_ver = self._send('show version').split('\r\n')
  163. return {
  164. 'serial': parse(sh_ver, 'Processor board ID ([^\s]+)'),
  165. 'description': parse(sh_ver, 'cisco ([^\s]+)')
  166. }
  167. def items(chassis_serial=None):
  168. cmd = self._send('show inventory').split('\r\n\r\n')
  169. for i in cmd:
  170. i_fmt = i.replace('\r\n', ' ')
  171. try:
  172. m_name = re.search('NAME: "([^"]+)"', i_fmt).group(1)
  173. m_pid = re.search('PID: ([^\s]+)', i_fmt).group(1)
  174. m_serial = re.search('SN: ([^\s]+)', i_fmt).group(1)
  175. # Omit built-in items and those with no PID
  176. if m_serial != chassis_serial and m_pid.lower() != 'unspecified':
  177. yield {
  178. 'name': m_name,
  179. 'part_id': m_pid,
  180. 'serial': m_serial,
  181. }
  182. except AttributeError:
  183. continue
  184. self._send('term length 0')
  185. sh_version = version()
  186. return {
  187. 'chassis': sh_version,
  188. 'items': list(items(chassis_serial=sh_version.get('serial')))
  189. }
  190. class OpengearSSH(SSHClient):
  191. """
  192. SSH client for Opengear devices
  193. """
  194. default_credentials = {
  195. 'username': 'root',
  196. 'password': 'default',
  197. }
  198. def get_inventory(self):
  199. try:
  200. stdin, stdout, stderr = self.ssh.exec_command("showserial")
  201. serial = stdout.readlines()[0].strip()
  202. except:
  203. raise RuntimeError("Failed to glean chassis serial from device.")
  204. # Older models don't provide serial info
  205. if serial == "No serial number information available":
  206. serial = ''
  207. try:
  208. stdin, stdout, stderr = self.ssh.exec_command("config -g config.system.model")
  209. description = stdout.readlines()[0].split(' ', 1)[1].strip()
  210. except:
  211. raise RuntimeError("Failed to glean chassis description from device.")
  212. return {
  213. 'chassis': {
  214. 'serial': serial,
  215. 'description': description,
  216. },
  217. 'items': [],
  218. }
  219. # For mapping platform -> NC client
  220. RPC_CLIENTS = {
  221. 'juniper-junos': JunosNC,
  222. 'cisco-ios': IOSSSH,
  223. 'opengear': OpengearSSH,
  224. }