dhcp-hook.py 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859
  1. #!/usr/local/bin/python3
  2. #
  3. # Copyright (c) 2017-2020 Joe Clarke <jclarke@cisco.com>
  4. # All rights reserved.
  5. #
  6. # Redistribution and use in source and binary forms, with or without
  7. # modification, are permitted provided that the following conditions
  8. # are met:
  9. # 1. Redistributions of source code must retain the above copyright
  10. # notice, this list of conditions and the following disclaimer.
  11. # 2. Redistributions in binary form must reproduce the above copyright
  12. # notice, this list of conditions and the following disclaimer in the
  13. # documentation and/or other materials provided with the distribution.
  14. #
  15. # THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
  16. # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  18. # ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
  19. # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  21. # OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  22. # HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  23. # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  24. # OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  25. # SUCH DAMAGE.
  26. from __future__ import print_function
  27. from builtins import str
  28. import sys
  29. import json
  30. from sparker import Sparker, MessageType # type: ignore
  31. import re
  32. import requests
  33. from requests.packages.urllib3.exceptions import InsecureRequestWarning # type: ignore
  34. requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
  35. import time
  36. import traceback
  37. import socket
  38. import logging
  39. import CLEUCreds # type: ignore
  40. from cleu.config import Config as C # type: ignore
  41. AT_MACADDR = 9
  42. CNR_HEADERS = {"Accept": "application/json"}
  43. CNR_AUTH = (CLEUCreds.CPNR_USERNAME, CLEUCreds.CPNR_PASSWORD)
  44. DEFAULT_INT_TYPE = "GigabitEthernet"
  45. ALLOWED_TO_DELETE = ["jclarke@cisco.com", "josterfe@cisco.com", "anjesani@cisco.com"]
  46. def is_ascii(s):
  47. return all(ord(c) < 128 for c in s)
  48. def normalize_mac(mac):
  49. # Normalize all MAC addresses to colon-delimited format.
  50. mac_addr = "".join(l + ":" * (n % 2 == 1) for n, l in enumerate(list(re.sub(r"[:.-]", "", mac)))).strip(":")
  51. return mac_addr.lower()
  52. # TODO: We don't use CMX anymore. This needs to work with DNS Spaces?
  53. def get_from_cmx(**kwargs):
  54. marker = "green"
  55. if "user" in kwargs and kwargs["user"] == "gru":
  56. marker = "gru"
  57. if "ip" in kwargs:
  58. url = "{}?ip={}&marker={}&size=1440".format(C.CMX_GW, kwargs["ip"], marker)
  59. elif "mac" in kwargs:
  60. url = "{}?mac={}&marker={}&size=1440".format(C.CMX_GW, kwargs["mac"], marker)
  61. else:
  62. return None
  63. headers = {"Accept": "image/jpeg, application/json"}
  64. try:
  65. response = requests.request("GET", url, headers=headers, stream=True)
  66. response.raise_for_status()
  67. except Exception:
  68. logging.error("Encountered error getting data from cmx: {}".format(traceback.format_exc()))
  69. return None
  70. if response.headers.get("content-type") == "application/json":
  71. return None
  72. return response.raw.data
  73. def get_from_dnac(**kwargs):
  74. for dnac in C.DNACS:
  75. curl = "https://{}/dna/intent/api/v1/client-detail".format(dnac)
  76. # Get timestamp with milliseconds
  77. epoch = int(time.time() * 1000)
  78. turl = "https://{}/dna/system/api/v1/auth/token".format(dnac)
  79. theaders = {"content-type": "application/json", "authorization": CLEUCreds.JCLARKE_BASIC}
  80. try:
  81. response = requests.request("POST", turl, headers=theaders, verify=False)
  82. response.raise_for_status()
  83. except Exception as e:
  84. logging.warning("Unable to get an auth token from DNAC: {}".format(getattr(e, "message", repr(e))))
  85. continue
  86. j = response.json()
  87. cheaders = {"accept": "application/json", "x-auth-token": j["Token"]}
  88. params = {"macAddress": kwargs["mac"], "timestamp": epoch}
  89. try:
  90. response = requests.request("GET", curl, params=params, headers=cheaders, verify=False)
  91. response.raise_for_status()
  92. except Exception as e:
  93. logging.warning("Failed to find MAC address {} in DNAC: {}".format(kwargs["mac"], getattr(e, "message", repr(e))))
  94. continue
  95. j = response.json()
  96. if "detail" not in j:
  97. logging.warning("Got an unknown response from DNAC: '{}'".format(response.text))
  98. continue
  99. if "errorCode" in j["detail"]:
  100. continue
  101. return j["detail"]
  102. return None
  103. # TODO: We don't use PI anymore. Remove this in favor of DNAC.
  104. def get_from_pi(**kwargs):
  105. what = None
  106. if "user" in kwargs:
  107. url = 'https://{}/webacs/api/v2/data/ClientDetails.json?.full=true&userName="{}"&status=ASSOCIATED'.format(C.PI, kwargs["user"])
  108. what = "user"
  109. elif "mac" in kwargs:
  110. mac_addr = normalize_mac(kwargs["mac"])
  111. url = 'https://{}/webacs/api/v2/data/ClientDetails.json?.full=true&macAddress="{}"&status=ASSOCIATED'.format(C.PI, mac_addr)
  112. what = "mac"
  113. elif "ip" in kwargs:
  114. url = 'https://{}/webacs/api/v2/data/ClientDetails.json?.full=true&ipAddress="{}"&status=ASSOCIATED'.format(C.PI, kwargs["ip"])
  115. what = "ip"
  116. else:
  117. return None
  118. headers = {"Connection": "close"}
  119. done = False
  120. first = 0
  121. code = 401
  122. i = 0
  123. while code != 200 and i < 10:
  124. response = None
  125. try:
  126. response = requests.request("GET", url, auth=(CLEUCreds.PI_USER, CLEUCreds.PI_PASS), headers=headers, verify=False)
  127. except Exception as e:
  128. logging.error("Failed to get a response from PI for {}: {}".format(kwargs[what], e))
  129. return None
  130. code = response.status_code
  131. if code != 200:
  132. i += 1
  133. time.sleep(3)
  134. if code == 200:
  135. j = json.loads(response.text)
  136. if j["queryResponse"]["@count"] == 0:
  137. return None
  138. return j["queryResponse"]["entity"]
  139. else:
  140. logging.error("Failed to get a response from PI for {}: {}".format(kwargs[what], response.text))
  141. return None
  142. def parse_relay_info(outd):
  143. global DEFAULT_INT_TYPE
  144. res = {"vlan": "N/A", "port": "N/A", "switch": "N/A"}
  145. if "relayAgentCircuitId" in outd:
  146. octets = outd["relayAgentCircuitId"].split(":")
  147. if len(octets) > 4:
  148. res["vlan"] = int("".join(octets[2:4]), 16)
  149. first_part = int(octets[4], 16)
  150. port = str(first_part)
  151. if first_part != 0:
  152. port = str(first_part) + "/0"
  153. res["port"] = DEFAULT_INT_TYPE + port + "/" + str(int(octets[5], 16))
  154. if "relayAgentRemoteId" in outd:
  155. octets = outd["relayAgentRemoteId"].split(":")
  156. res["switch"] = bytes.fromhex("".join(octets[2:])).decode("utf-8", "ignore")
  157. if not is_ascii(res["switch"]) or res["switch"] == "":
  158. res["switch"] = "N/A"
  159. return res
  160. def check_for_reservation(ip):
  161. global CNR_HEADERS, CNR_AUTH
  162. res = {}
  163. url = "{}/Reservation/{}".format(C.DHCP_BASE, ip)
  164. try:
  165. response = requests.request("GET", url, auth=CNR_AUTH, headers=CNR_HEADERS, verify=False)
  166. response.raise_for_status()
  167. except Exception as e:
  168. logging.warning("Did not get a good response from CNR for reservation {}: {}".format(ip, e))
  169. return None
  170. rsvp = response.json()
  171. res["mac"] = ":".join(rsvp["lookupKey"].split(":")[-6:])
  172. res["scope"] = rsvp["scope"]
  173. return res
  174. def check_for_reservation_by_mac(mac):
  175. global CNR_HEADERS, CNR_AUTH
  176. res = {}
  177. mac_addr = normalize_mac(mac)
  178. url = "{}/Reservation".format(C.DHCP_BASE)
  179. try:
  180. response = requests.request("GET", url, auth=CNR_AUTH, headers=CNR_HEADERS, params={"lookupKey": mac_addr}, verify=False)
  181. response.raise_for_status()
  182. except Exception as e:
  183. logging.warning("Did not get a good response from CNR for reservation {}: {}".format(ip, e))
  184. return None
  185. j = response.json()
  186. if len(j) == 0:
  187. return None
  188. rsvp = j[0]
  189. res["mac"] = ":".join(rsvp["lookupKey"].split(":")[-6:])
  190. res["scope"] = rsvp["scope"]
  191. return res
  192. def create_reservation(ip, mac):
  193. global CNR_HEADERS, CNR_AUTH, AT_MACADDR
  194. mac_addr = normalize_mac(mac)
  195. url = "{}/Reservation".format(C.DHCP_BASE)
  196. payload = {"ipaddr": ip, "lookupKey": "01:06:" + mac_addr, "lookupKeyType": AT_MACADDR}
  197. response = requests.request("POST", url, auth=CNR_AUTH, headers=CNR_HEADERS, json=payload, verify=False)
  198. response.raise_for_status()
  199. def delete_reservation(ip):
  200. global CNR_HEADERS, CNR_AUTH
  201. url = "{}/Reservation/{}".format(C.DHCP_BASE, ip)
  202. response = requests.request("DELETE", url, auth=CNR_AUTH, headers=CNR_HEADERS, verify=False)
  203. response.raise_for_status()
  204. def check_for_lease(ip):
  205. global CNR_HEADERS, CNR_AUTH
  206. res = {}
  207. url = "{}/Lease/{}".format(C.DHCP_BASE, ip)
  208. try:
  209. response = requests.request("GET", url, auth=CNR_AUTH, headers=CNR_HEADERS, verify=False)
  210. response.raise_for_status()
  211. except Exception as e:
  212. logging.warning("Did not get a good response from CNR for IP {}: {}".format(ip, e))
  213. return None
  214. lease = response.json()
  215. if not "clientMacAddr" in lease:
  216. return None
  217. relay = parse_relay_info(lease)
  218. if "clientHostName" in lease:
  219. res["name"] = lease["clientHostName"]
  220. elif "client-dns-name" in lease:
  221. res["name"] = lease["clientDnsName"]
  222. else:
  223. res["name"] = "UNKNOWN"
  224. res["mac"] = lease["clientMacAddr"][lease["clientMacAddr"].rfind(",") + 1 :]
  225. res["scope"] = lease["scopeName"]
  226. res["state"] = lease["state"]
  227. res["relay-info"] = relay
  228. rsvp = check_for_reservation(ip)
  229. if rsvp and rsvp["mac"] == res["mac"]:
  230. res["is-reserved"] = True
  231. return res
  232. def check_for_mac(mac):
  233. global CNR_HEADERS, CNR_AUTH
  234. url = "{}/Lease".format(C.DHCP_BASE)
  235. try:
  236. response = requests.request("GET", url, auth=CNR_AUTH, headers=CNR_HEADERS, verify=False, params={"clientMacAddr": mac})
  237. response.raise_for_status()
  238. except Exception as e:
  239. logging.warning("Did not get a good response from CPNR for MAC {}: {}".format(mac, e))
  240. return None
  241. j = response.json()
  242. if len(j) == 0:
  243. return None
  244. leases = []
  245. for lease in j:
  246. res = {}
  247. if "address" not in lease:
  248. continue
  249. relay = parse_relay_info(lease)
  250. res["ip"] = lease["address"]
  251. if "clientHostName" in lease:
  252. res["name"] = lease["clientHostName"]
  253. elif "clientDnsName" in lease:
  254. res["name"] = lease["clientDnsName"]
  255. else:
  256. res["name"] = "UNKNOWN"
  257. res["scope"] = lease["scopeName"]
  258. res["state"] = lease["state"]
  259. res["relay-info"] = relay
  260. rsvp = check_for_reservation(res["ip"])
  261. if rsvp and rsvp["mac"] == mac:
  262. res["is-reserved"] = True
  263. leases.append(res)
  264. return leases
  265. def print_dnac(spark, what, details, msg):
  266. ohealth = None
  267. healths = {}
  268. host_info = ""
  269. ssid = ""
  270. loc = ""
  271. hinfo = ""
  272. sdetails = ""
  273. if "healthScore" in details:
  274. for score in details["healthScore"]:
  275. if "healthType" in score:
  276. if score["healthType"] == "OVERALL":
  277. ohealth = {}
  278. ohealth["score"] = score["score"]
  279. ohealth["reason"] = score["reason"]
  280. else:
  281. healths[score["healthType"]] = {"score": score["score"], "reason": score["reason"]}
  282. if details["hostOs"]:
  283. host_info = "running **{}**".format(details["hostOs"])
  284. if details["ssid"]:
  285. ssid = "associated to SSID **{}**".format(details["ssid"])
  286. if details["location"]:
  287. loc = "located in **{}**".format(details["location"])
  288. if details["port"] and details["clientConnection"]:
  289. sdetails = "connected to device **{}** on port **{}**".format(details["clientConnection"], details["port"])
  290. if ohealth is not None:
  291. hinfo = "with health score **{}/10**".format(ohealth["score"])
  292. if ohealth["reason"]:
  293. hinfo += " (reason: _{}_)".format(ohealth["reason"])
  294. if len(healths) > 0:
  295. hinfo += " ["
  296. for h, hobj in list(healths.items()):
  297. hinfo += "{} health: {} ".format(h, hobj["score"])
  298. if hobj["reason"] != "":
  299. hinfo += "(reason: {}) ".format(hobj["reason"])
  300. hinfo += "]"
  301. spark.post_to_spark(
  302. C.WEBEX_TEAM,
  303. SPARK_ROOM,
  304. "{} {} is a {} client {} {} {} {} {}".format(msg, what, details["hostType"], sdetails, ssid, loc, host_info, hinfo),
  305. )
  306. def print_pi(spark, what, ents, msg):
  307. for ent in ents:
  308. res = ent["clientDetailsDTO"]
  309. apdet = ""
  310. condet = ""
  311. vendet = ""
  312. if "apName" in res:
  313. apdet = "**{}** via ".format(res["apName"])
  314. if "connectionType" in res:
  315. condet = "is a **{}** client".format(res["connectionType"])
  316. if "vendor" in res:
  317. vendet = "of vendor type **{}**".format(res["vendor"])
  318. spark.post_to_spark(
  319. C.WEBEX_TEAM,
  320. SPARK_ROOM,
  321. "{} {} {} {}, connected to {}**{}** on interface **{}** with MAC address **{}** and IP address **{}** in **VLAN {}** located in **{}**.".format(
  322. msg,
  323. what,
  324. condet,
  325. vendet,
  326. apdet,
  327. res["deviceName"],
  328. res["clientInterface"],
  329. res["macAddress"],
  330. res["ipAddress"]["address"],
  331. res["vlan"],
  332. res["location"],
  333. ),
  334. )
  335. spark = Sparker(token=CLEUCreds.SPARK_TOKEN, logit=True)
  336. SPARK_ROOM = "DHCP Queries"
  337. if __name__ == "__main__":
  338. print("Content-type: application/json\r\n\r\n")
  339. output = sys.stdin.read()
  340. j = json.loads(output)
  341. logging.basicConfig(
  342. format="%(asctime)s - %(name)s - %(levelname)s : %(message)s", filename="/var/log/dhcp-hook.log", level=logging.DEBUG
  343. )
  344. logging.debug(json.dumps(j, indent=4))
  345. message_from = j["data"]["personEmail"]
  346. if message_from == "livenocbot@sparkbot.io":
  347. logging.debug("Person email is our bot")
  348. print('{"result":"success"}')
  349. sys.exit(0)
  350. tid = spark.get_team_id(C.WEBEX_TEAM)
  351. if tid is None:
  352. logging.error("Failed to get Spark Team ID")
  353. print('{"result":"fail"}')
  354. sys.exit(0)
  355. rid = spark.get_room_id(tid, SPARK_ROOM)
  356. if rid is None:
  357. logging.error("Failed to get Spark Room ID")
  358. print('{"result":"fail"}')
  359. sys.exit(0)
  360. if rid != j["data"]["roomId"]:
  361. logging.error("Spark Room ID is not the same as in the message ({} vs. {})".format(rid, j["data"]["roomId"]))
  362. print('{"result":"fail"}')
  363. sys.exit(0)
  364. mid = j["data"]["id"]
  365. msg = spark.get_message(mid)
  366. if msg is None:
  367. logging.error("Did not get a message")
  368. print('{"result":"error"}')
  369. sys.exit(0)
  370. person = spark.get_person(j["data"]["personId"])
  371. if person is not None:
  372. spark.post_to_spark(C.WEBEX_TEAM, SPARK_ROOM, "Hey, {}. Working on that for you...".format(person["nickName"]))
  373. else:
  374. spark.post_to_spark(C.WEBEX_TEAM, SPARK_ROOM, "Working on that for you...")
  375. txt = msg["text"]
  376. found_hit = False
  377. if re.search(r"\bhelp\b", txt, re.I):
  378. spark.post_to_spark(
  379. C.WEBEX_TEAM,
  380. SPARK_ROOM,
  381. 'To lookup a reservation, type `@Live NOC Bot reservation IP`. To lookup a lease by MAC, ask about the MAC. To lookup a lease by IP ask about the IP. To look up a user, ask about "user USERNAME".<br>Some question might be, `@Live NOC Bot who has lease 1.2.3.4` or `@Live NOC Bot what lease does 00:11:22:33:44:55 have` or `@Live NOC Bot tell me about user jsmith`.',
  382. )
  383. found_hit = True
  384. try:
  385. m = re.search(r"user(name)?\s+\b(?P<uname>[A-Za-z][\w\-\.\d]+)([\s\?\.]|$)", txt, re.I)
  386. if not found_hit and not m:
  387. m = re.search(r"(who|where)\s+is\s+\b(?P<uname>[A-Za-z][\w\-\.\d]+)([\s\?\.]|$)", txt, re.I)
  388. if not found_hit and m:
  389. found_hit = True
  390. uname = m.group("uname")
  391. usecret = ""
  392. if re.search(r"gru", m.group("uname"), re.I):
  393. uname = "rkamerma"
  394. usecret = "gru"
  395. res = get_from_pi(user=uname)
  396. if res is None:
  397. res = get_from_pi(user=uname + "@{}".format(C.AD_DOMAIN))
  398. if res is not None:
  399. print_pi(spark, m.group("uname"), res, "")
  400. for ent in res:
  401. dnacres = get_from_dnac(mac=ent["clientDetailsDTO"]["macAddress"].lower())
  402. if dnacres is not None:
  403. print_dnac(spark, m.group("uname"), dnacres, "")
  404. cmxres = get_from_cmx(mac=ent["clientDetailsDTO"]["macAddress"].lower(), user=usecret)
  405. if cmxres is not None:
  406. spark.post_to_spark_with_attach(
  407. C.WEBEX_TEAM,
  408. SPARK_ROOM,
  409. "{}'s location from CMX".format(m.group("uname")),
  410. cmxres,
  411. "{}_location.jpg".format(m.group("uname")),
  412. "image/jpeg",
  413. )
  414. else:
  415. spark.post_to_spark(C.WEBEX_TEAM, SPARK_ROOM, "Sorry, I can't find {}.".format(m.group("uname")))
  416. m = re.search(r"(remove|delete)\s+reservation.*?([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)", txt, re.I)
  417. if not m:
  418. m = re.search(r"(unreserve).*?([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)", txt, re.I)
  419. if not found_hit and m:
  420. found_hit = True
  421. if message_from not in ALLOWED_TO_DELETE:
  422. spark.post_to_spark(C.WEBEX_TEAM, SPARK_ROOM, "I'm sorry, {}. I can't do that for you.".format(message_from))
  423. else:
  424. res = check_for_reservation(m.group(2))
  425. if res is None:
  426. spark.post_to_spark(C.WEBEX_TEAM, SPARK_ROOM, "I didn't find a reservation for {}.".format(m.group(2)))
  427. else:
  428. try:
  429. delete_reservation(m.group(2))
  430. spark.post_to_spark(
  431. C.WEBEX_TEAM, SPARK_ROOM, "Reservation for {} deleted successfully.".format(m.group(2)), MessageType.GOOD
  432. )
  433. except Exception as e:
  434. spark.post_to_spark(
  435. C.WEBEX_TEAM, SPARK_ROOM, "Failed to delete reservation for {}: {}".format(m.group(2)), MessageType.BAD
  436. )
  437. m = re.search(r"(make|create|add)\s+reservation.*?([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)", txt, re.I)
  438. if not found_hit and m:
  439. found_hit = True
  440. res = check_for_reservation(m.group(2))
  441. if res is not None:
  442. spark.post_to_spark(
  443. C.WEBEX_TEAM, SPARK_ROOM, "_{}_ is already reserved by a client with MAC **{}**".format(m.group(2), res["mac"])
  444. )
  445. else:
  446. lres = check_for_lease(m.group(2))
  447. if lres is None:
  448. spark.post_to_spark(C.WEBEX_TEAM, SPARK_ROOM, "Did not find an existing lease for {}".format(m.group(2)))
  449. else:
  450. try:
  451. rres = check_for_reservation_by_mac(lres["mac"])
  452. if rres is not None:
  453. spark.post_to_spark(
  454. C.WEBEX_TEAM,
  455. SPARK_ROOM,
  456. "_{}_ already has a reservation for {} in scope {}.".format(lres["mac"], rres["ip"], lres["scope"]),
  457. )
  458. else:
  459. create_reservation(m.group(2), lres["mac"])
  460. spark.post_to_spark(
  461. C.WEBEX_TEAM, SPARK_ROOM, "Successfully added reservation for {}.".format(m.group(2)), MessageType.GOOD
  462. )
  463. except Exception as e:
  464. spark.post_to_spark(
  465. C.WEBEX_TEAM, SPARK_ROOM, "Failed to add reservation for {}: {}".format(m.group(2), e), MessageType.BAD
  466. )
  467. m = re.search(r"reservation.*?([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)", txt, re.I)
  468. if not found_hit and m:
  469. found_hit = True
  470. res = check_for_reservation(m.group(1))
  471. if res is not None:
  472. spark.post_to_spark(
  473. C.WEBEX_TEAM,
  474. SPARK_ROOM,
  475. "_{}_ is reserved by a client with MAC **{}** in scope **{}**.".format(m.group(1), res["mac"], res["scope"]),
  476. )
  477. else:
  478. spark.post_to_spark(C.WEBEX_TEAM, SPARK_ROOM, "I did not find a reservation for {}.".format(m.group(1)))
  479. m = re.findall(r"\b([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)\b", txt)
  480. if not found_hit and len(m) > 0:
  481. found_hit = True
  482. for hit in m:
  483. res = check_for_lease(hit)
  484. pires = get_from_pi(ip=hit)
  485. cmxres = None
  486. dnacres = None
  487. if res is not None:
  488. cmxres = get_from_cmx(mac=re.sub(r"(\d+,)+", "", res["mac"]))
  489. dnacres = get_from_dnac(mac=re.sub(r"(\d+,)+", "", res["mac"]))
  490. elif pires is not None:
  491. cmxres = get_from_cmx(mac=pires[0]["clientDetailsDTO"]["macAddress"])
  492. dnacres = get_from_dnac(mac=pires[0]["clientDetailsDTO"]["macAddress"])
  493. if res is not None:
  494. reserved = ""
  495. if "is-reserved" in res and res["is-reserved"]:
  496. reserved = " (Client has reserved this IP)"
  497. if re.search(r"available", res["state"]):
  498. port_info = res["relay-info"]["port"]
  499. if port_info != "N/A":
  500. port_info = '<a href="{}switchname={}&portname={}">**{}**</a>'.format(
  501. C.TOOL_BASE,
  502. "-".join(res["relay-info"]["switch"].split("-")[:-1]),
  503. res["relay-info"]["port"],
  504. res["relay-info"]["port"],
  505. )
  506. spark.post_to_spark(
  507. C.WEBEX_TEAM,
  508. SPARK_ROOM,
  509. "_{}_ is no longer leased, but _WAS_ leased by a client with name **{}** and MAC **{}** in scope **{}** (state: **{}**) and was connected to switch **{}** on port {} in VLAN **{}**{}.".format(
  510. hit,
  511. res["name"],
  512. res["mac"],
  513. res["scope"],
  514. res["state"],
  515. res["relay-info"]["switch"],
  516. port_info,
  517. res["relay-info"]["vlan"],
  518. reserved,
  519. ),
  520. )
  521. else:
  522. port_info = res["relay-info"]["port"]
  523. if port_info != "N/A":
  524. port_info = '<a href="{}switchname={}&portname={}">**{}**</a>'.format(
  525. C.TOOL_BASE,
  526. "-".join(res["relay-info"]["switch"].split("-")[:-1]),
  527. res["relay-info"]["port"],
  528. res["relay-info"]["port"],
  529. )
  530. spark.post_to_spark(
  531. C.WEBEX_TEAM,
  532. SPARK_ROOM,
  533. "_{}_ is leased by a client with name **{}** and MAC **{}** in scope **{}** (state: **{}**) and is connected to switch **{}** on port {} in VLAN **{}**{}.".format(
  534. hit,
  535. res["name"],
  536. res["mac"],
  537. res["scope"],
  538. res["state"],
  539. res["relay-info"]["switch"],
  540. port_info,
  541. res["relay-info"]["vlan"],
  542. reserved,
  543. ),
  544. )
  545. if pires is not None:
  546. print_pi(spark, hit, pires, "I also found this from Prime Infra:")
  547. if dnacres is not None:
  548. print_dnac(spark, hit, dnacres, "I also found this from Cisco DNA Center:")
  549. if cmxres is not None:
  550. spark.post_to_spark_with_attach(
  551. C.WEBEX_TEAM, SPARK_ROOM, "Location from CMX", cmxres, "{}_location.jpg".format(hit), "image/jpeg"
  552. )
  553. else:
  554. spark.post_to_spark(C.WEBEX_TEAM, SPARK_ROOM, "I did not find a lease for {}.".format(hit))
  555. if pires is not None:
  556. print_pi(spark, hit, pires, "But I did get this from Prime Infra:")
  557. if dnacres is not None:
  558. print_dnac(spark, hit, dnacres, "But I did get this from Cisco DNA Center:")
  559. if cmxres is not None:
  560. spark.post_to_spark_with_attach(
  561. C.WEBEX_TEAM, SPARK_ROOM, "Location from CMX", cmxres, "{}_location.jpg".format(hit), "image/jpeg"
  562. )
  563. m = re.findall(
  564. "\\b(?:(?:[0-9A-Fa-f]{1,4}:){6}(?:[0-9A-Fa-f]{1,4}:[0-9A-Fa-f]{1,4}|(?:(?:[0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}(?:[0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]))|::(?:[0-9A-Fa-f]{1,4}:){5}(?:[0-9A-Fa-f]{1,4}:[0-9A-Fa-f]{1,4}|(?:(?:[0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}(?:[0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]))|(?:[0-9A-Fa-f]{1,4})?::(?:[0-9A-Fa-f]{1,4}:){4}(?:[0-9A-Fa-f]{1,4}:[0-9A-Fa-f]{1,4}|(?:(?:[0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}(?:[0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]))|(?:[0-9A-Fa-f]{1,4}:[0-9A-Fa-f]{1,4})?::(?:[0-9A-Fa-f]{1,4}:){3}(?:[0-9A-Fa-f]{1,4}:[0-9A-Fa-f]{1,4}|(?:(?:[0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}(?:[0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]))|(?:(?:[0-9A-Fa-f]{1,4}:){,2}[0-9A-Fa-f]{1,4})?::(?:[0-9A-Fa-f]{1,4}:){2}(?:[0-9A-Fa-f]{1,4}:[0-9A-Fa-f]{1,4}|(?:(?:[0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}(?:[0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]))|(?:(?:[0-9A-Fa-f]{1,4}:){,3}[0-9A-Fa-f]{1,4})?::[0-9A-Fa-f]{1,4}:(?:[0-9A-Fa-f]{1,4}:[0-9A-Fa-f]{1,4}|(?:(?:[0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}(?:[0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]))|(?:(?:[0-9A-Fa-f]{1,4}:){,4}[0-9A-Fa-f]{1,4})?::(?:[0-9A-Fa-f]{1,4}:[0-9A-Fa-f]{1,4}|(?:(?:[0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}(?:[0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]))|(?:(?:[0-9A-Fa-f]{1,4}:){,5}[0-9A-Fa-f]{1,4})?::[0-9A-Fa-f]{1,4}|(?:(?:[0-9A-Fa-f]{1,4}:){,6}[0-9A-Fa-f]{1,4})?::)\\b",
  565. txt,
  566. )
  567. if not found_hit and len(m) > 0:
  568. found_hit = True
  569. for hit in m:
  570. pires = get_from_pi(ip=hit)
  571. if pires is not None:
  572. print_pi(spark, hit, pires, "")
  573. dnacres = get_from_dnac(mac=pires[0]["clientDetailsDTO"]["macAddress"])
  574. cmxres = get_from_cmx(mac=pires[0]["clientDetailsDTO"]["macAddress"])
  575. if dnacres is not None:
  576. print_dnac(spark, hit, dnacres, "")
  577. if cmxres is not None:
  578. spark.post_to_spark_with_attach(
  579. C.WEBEX_TEAM, SPARK_ROOM, "Location from CMX", cmxres, "{}_location.jpg".format(hit), "image/jpeg"
  580. )
  581. else:
  582. spark.post_to_spark(C.WEBEX_TEAM, SPARK_ROOM, "I did not find anything about {} in Prime Infra.".format(hit))
  583. m = re.findall(
  584. r"\b(([a-fA-F0-9]{1,2}:[a-fA-F0-9]{1,2}:[a-fA-F0-9]{1,2}:[a-fA-F0-9]{1,2}:[a-fA-F0-9]{1,2}:[a-fA-F0-9]{1,2})|([a-fA-F0-9]{4}\.[a-fA-F0-9]{4}\.[a-fA-F0-9]{4})|([a-fA-F0-9]{1,2}-[a-fA-F0-9]{1,2}-[a-fA-F0-9]{1,2}-[a-fA-F0-9]{1,2}-[a-fA-F0-9]{1,2}-[a-fA-F0-9]{1,2}))\b",
  585. txt,
  586. )
  587. if not found_hit and len(m) > 0:
  588. found_hit = True
  589. for hit in m:
  590. hmac = normalize_mac(hit[0])
  591. leases = check_for_mac(hmac)
  592. pires = get_from_pi(mac=hmac)
  593. cmxres = get_from_cmx(mac=re.sub(r"(\d+,)+", "", hmac))
  594. dnacres = get_from_dnac(mac=re.sub(r"(\d+,)+", "", hmac))
  595. if leases is not None:
  596. seen_ip = {}
  597. for res in leases:
  598. if res["ip"] in seen_ip:
  599. continue
  600. reserved = ""
  601. if "is-reserved" in res and res["is-reserved"]:
  602. reserved = " (Client has reserved this IP)"
  603. seen_ip[res["ip"]] = True
  604. if re.search(r"available", res["state"]):
  605. spark.post_to_spark(
  606. C.WEBEX_TEAM,
  607. SPARK_ROOM,
  608. "Client with MAC _{}_ no longer has a lease, but _USED TO HAVE_ lease **{}** (hostname: **{}**) in scope **{}** (state: **{}**) and was connected to switch **{}** on port **{}** in VLAN **{}**{}.".format(
  609. hit[0],
  610. res["ip"],
  611. res["name"],
  612. res["scope"],
  613. res["state"],
  614. res["relay-info"]["switch"],
  615. res["relay-info"]["port"],
  616. res["relay-info"]["vlan"],
  617. reserved,
  618. ),
  619. )
  620. else:
  621. spark.post_to_spark(
  622. C.WEBEX_TEAM,
  623. SPARK_ROOM,
  624. "Client with MAC _{}_ has lease **{}** (hostname: **{}**) in scope **{}** (state: **{}**) and is connected to switch **{}** on port **{}** in VLAN **{}**{}.".format(
  625. hit[0],
  626. res["ip"],
  627. res["name"],
  628. res["scope"],
  629. res["state"],
  630. res["relay-info"]["switch"],
  631. res["relay-info"]["port"],
  632. res["relay-info"]["vlan"],
  633. reserved,
  634. ),
  635. )
  636. if pires is not None:
  637. # spark.post_to_spark(C.WEBEX_TEAM, SPARK_ROOM, '```\n{}\n```'.format(json.dumps(pires, indent=4)))
  638. print_pi(spark, hit[0], pires, "I also found this from Prime Infra:")
  639. if dnacres is not None:
  640. print_dnac(spark, hit[0], dnacres, "I also found this fron Cisco DNA Center:")
  641. if cmxres is not None:
  642. spark.post_to_spark_with_attach(
  643. C.WEBEX_TEAM, SPARK_ROOM, "Location from CMX", cmxres, "{}_location.jpg".format(hit[0]), "image/jpeg"
  644. )
  645. else:
  646. spark.post_to_spark(C.WEBEX_TEAM, SPARK_ROOM, "I did not find a lease for {}.".format(hit[0]))
  647. if pires is not None:
  648. print_pi(spark, hit[0], pires, "But I did get this from Prime Infra:")
  649. if dnacres is not None:
  650. print_dnac(spark, hit[0], dnacres, "But I did get this from Cisco DNA Center:")
  651. if cmxres is not None:
  652. spark.post_to_spark_with_attach(
  653. C.WEBEX_TEAM, SPARK_ROOM, "Location from CMX", cmxres, "{}_location.jpg".format(hit[0]), "image/jpeg"
  654. )
  655. m = re.search(r"answer", txt, re.I)
  656. if not found_hit and m:
  657. found_hit = True
  658. spark.post_to_spark(C.WEBEX_TEAM, SPARK_ROOM, "The answer is 42.")
  659. m = re.findall(r"([\w\d\-\.]+)", txt)
  660. if not found_hit and len(m) > 0:
  661. found_hit = False
  662. for hit in m:
  663. ip = None
  664. try:
  665. ip = socket.gethostbyname(hit)
  666. except:
  667. pass
  668. if ip:
  669. res = check_for_lease(ip)
  670. pires = get_from_pi(ip=ip)
  671. if res is not None:
  672. reserved = ""
  673. if "is-reserved" in res and res["is-reserved"]:
  674. reserved = " (Client has reserved this IP)"
  675. if re.search(r"available", res["state"]):
  676. found_hit = True
  677. spark.post_to_spark(
  678. C.WEBEX_TEAM,
  679. SPARK_ROOM,
  680. "Client with hostname _{}_ no longer has a lease, but _USED TO HAVE_ lease **{}** (hostname: **{}**) in scope **{}** (state: **{}**) and was connected to switch **{}** on port **{}** in VLAN **{}**{}.".format(
  681. hit,
  682. ip,
  683. res["name"],
  684. res["scope"],
  685. res["state"],
  686. res["relay-info"]["switch"],
  687. res["relay-info"]["port"],
  688. res["relay-info"]["vlan"],
  689. reserved,
  690. ),
  691. )
  692. else:
  693. found_hit = True
  694. spark.post_to_spark(
  695. C.WEBEX_TEAM,
  696. SPARK_ROOM,
  697. "Client with hostname _{}_ has lease **{}** (hostname: **{}**) in scope **{}** (state: **{}**) and is connected to switch **{}** on port **{}** in VLAN **{}**.".format(
  698. hit,
  699. ip,
  700. res["name"],
  701. res["scope"],
  702. res["state"],
  703. res["relay-info"]["switch"],
  704. res["relay-info"]["port"],
  705. res["relay-info"]["vlan"],
  706. ),
  707. )
  708. if pires is not None:
  709. found_hit = True
  710. # spark.post_to_spark(C.WEBEX_TEAM, SPARK_ROOM, '```\n{}\n```'.format(json.dumps(pires, indent=4)))
  711. print_pi(spark, hit, pires, "I also found this from Prime Infra:")
  712. dnacres = get_from_dnac(mac=pires[0]["clientDetailsDTO"]["macAddress"])
  713. cmxres = get_from_cmx(mac=pires[0]["clientDetailsDTO"]["macAddress"])
  714. if dnacres is not None:
  715. print_dnac(spark, hit, dnacres, "I also found this from Cisco DNA Center:")
  716. if cmxres is not None:
  717. spark.post_to_spark_with_attach(
  718. C.WEBEX_TEAM, SPARK_ROOM, "Location from CMX", cmxres, "{}_location.jpg".format(hit), "image/jpeg"
  719. )
  720. else:
  721. found_hit = True
  722. spark.post_to_spark(C.WEBEX_TEAM, SPARK_ROOM, "I did not find a lease for {}.".format(hit))
  723. if pires is not None:
  724. print_pi(spark, hit, pires, "But I did get this from Prime Infra:")
  725. dnacres = get_from_dnac(mac=pires[0]["clientDetailsDTO"]["macAddress"])
  726. cmxres = get_from_cmx(mac=pires[0]["clientDetailsDTO"]["macAddress"])
  727. if dnacres is not None:
  728. print_dnac(spark, hit, dnacres, "But I did get this from Cisco DNA Center:")
  729. if cmxres is not None:
  730. spark.post_to_spark_with_attach(
  731. C.WEBEX_TEAM, SPARK_ROOM, "Location from CMX", cmxres, "{}_location.jpg".format(hit), "image/jpeg"
  732. )
  733. if not found_hit:
  734. spark.post_to_spark(
  735. C.WEBEX_TEAM,
  736. SPARK_ROOM,
  737. 'Sorry, I didn\'t get that. Please give me a MAC or IP (or "reservation IP" or "user USER") or just ask for "help".',
  738. )
  739. except Exception as e:
  740. logging.error("Error in obtaining data: {}".format(traceback.format_exc()))
  741. spark.post_to_spark(
  742. C.WEBEX_TEAM, SPARK_ROOM, "Whoops, I encountered an error:<br>\n```\n{}\n```".format(traceback.format_exc()), MessageType.BAD
  743. )
  744. print('{"result":"success"}')