dhcp-hook.py 38 KB

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