devices.py 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  1. #!/usr/bin/env python3
  2. import requests
  3. import argparse
  4. from datetime import datetime, timedelta
  5. def view(
  6. url,
  7. token,
  8. id=None,
  9. device_name=None,
  10. user_name=None,
  11. group_name=None,
  12. offline_days=None,
  13. ):
  14. headers = {"Authorization": f"Bearer {token}"}
  15. pageSize = 30
  16. params = {
  17. "id": id,
  18. "device_name": device_name,
  19. "user_name": user_name,
  20. "group_name": group_name,
  21. }
  22. params = {
  23. k: "%" + v + "%" if (v != "-" and "%" not in v) else v
  24. for k, v in params.items()
  25. if v is not None
  26. }
  27. params["pageSize"] = pageSize
  28. devices = []
  29. current = 1
  30. while True:
  31. params["current"] = current
  32. response = requests.get(f"{url}/api/devices", headers=headers, params=params)
  33. response_json = response.json()
  34. data = response_json.get("data", [])
  35. for device in data:
  36. if offline_days is None:
  37. devices.append(device)
  38. continue
  39. last_online = datetime.strptime(
  40. device["last_online"].split(".")[0], "%Y-%m-%dT%H:%M:%S"
  41. ) # assuming date is in this format
  42. if (datetime.utcnow() - last_online).days >= offline_days:
  43. devices.append(device)
  44. total = response_json.get("total", 0)
  45. current += pageSize
  46. if len(data) < pageSize or current > total:
  47. break
  48. return devices
  49. def check(response):
  50. if response.status_code == 200:
  51. try:
  52. response_json = response.json()
  53. return response_json
  54. except ValueError:
  55. return response.text or "Success"
  56. else:
  57. return "Failed", response.status_code, response.text
  58. def disable(url, token, guid, id):
  59. print("Disable", id)
  60. headers = {"Authorization": f"Bearer {token}"}
  61. response = requests.post(f"{url}/api/devices/{guid}/disable", headers=headers)
  62. return check(response)
  63. def enable(url, token, guid, id):
  64. print("Enable", id)
  65. headers = {"Authorization": f"Bearer {token}"}
  66. response = requests.post(f"{url}/api/devices/{guid}/enable", headers=headers)
  67. return check(response)
  68. def delete(url, token, guid, id):
  69. print("Delete", id)
  70. headers = {"Authorization": f"Bearer {token}"}
  71. response = requests.delete(f"{url}/api/devices/{guid}", headers=headers)
  72. return check(response)
  73. def assign(url, token, guid, id, type, value):
  74. print("assign", id, type, value)
  75. if type != "ab" and type != "strategy_name" and type != "user_name":
  76. print("Invalid type, it must be 'ab', 'strategy_name' or 'user_name'")
  77. return
  78. data = {"type": type, "value": value}
  79. headers = {"Authorization": f"Bearer {token}"}
  80. response = requests.post(
  81. f"{url}/api/devices/{guid}/assign", headers=headers, json=data
  82. )
  83. return check(response)
  84. def main():
  85. parser = argparse.ArgumentParser(description="Device manager")
  86. parser.add_argument(
  87. "command",
  88. choices=["view", "disable", "enable", "delete", "assign"],
  89. help="Command to execute",
  90. )
  91. parser.add_argument("--url", required=True, help="URL of the API")
  92. parser.add_argument(
  93. "--token", required=True, help="Bearer token for authentication"
  94. )
  95. parser.add_argument("--id", help="Device ID")
  96. parser.add_argument("--device_name", help="Device name")
  97. parser.add_argument("--user_name", help="User name")
  98. parser.add_argument("--group_name", help="Group name")
  99. parser.add_argument(
  100. "--assign_to",
  101. help="<type>=<value>, e.g. user_name=mike, strategy_name=test, ab=ab1, ab=ab1,tag1",
  102. )
  103. parser.add_argument(
  104. "--offline_days", type=int, help="Offline duration in days, e.g., 7"
  105. )
  106. args = parser.parse_args()
  107. while args.url.endswith("/"): args.url = args.url[:-1]
  108. devices = view(
  109. args.url,
  110. args.token,
  111. args.id,
  112. args.device_name,
  113. args.user_name,
  114. args.group_name,
  115. args.offline_days,
  116. )
  117. if args.command == "view":
  118. for device in devices:
  119. print(device)
  120. elif args.command == "disable":
  121. for device in devices:
  122. response = disable(args.url, args.token, device["guid"], device["id"])
  123. print(response)
  124. elif args.command == "enable":
  125. for device in devices:
  126. response = enable(args.url, args.token, device["guid"], device["id"])
  127. print(response)
  128. elif args.command == "delete":
  129. for device in devices:
  130. response = delete(args.url, args.token, device["guid"], device["id"])
  131. print(response)
  132. elif args.command == "assign":
  133. if "=" not in args.assign_to:
  134. print("Invalid assign_to format, it must be <type>=<value>")
  135. return
  136. type, value = args.assign_to.split("=", 1)
  137. for device in devices:
  138. response = assign(
  139. args.url, args.token, device["guid"], device["id"], type, value
  140. )
  141. print(response)
  142. if __name__ == "__main__":
  143. main()