Utils.py 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. # -*- coding: utf-8 -*-
  2. import json
  3. import csv
  4. import base64
  5. import random
  6. import socket
  7. from datetime import datetime, timezone, timedelta
  8. def base64url_decode(base64_str):
  9. size = len(base64_str) % 4
  10. if size == 2:
  11. base64_str += '=='
  12. elif size == 3:
  13. base64_str += '='
  14. elif size != 0:
  15. raise ValueError('Invalid base64 string')
  16. return base64.urlsafe_b64decode(base64_str.encode('utf-8'))
  17. def parse_jwt(jwt_token):
  18. jwt_token_list = jwt_token.split('.')
  19. header = base64url_decode(jwt_token_list[0]).decode()
  20. payload = base64url_decode(jwt_token_list[1]).decode()
  21. return {
  22. 'header': json.loads(header),
  23. 'payload': json.loads(payload),
  24. 'signature': jwt_token_list[-1]
  25. }
  26. def generate_random_code(n):
  27. range_start = 10**(n-1)
  28. range_end = (10**n)-1
  29. return str(random.randint(range_start, range_end))
  30. def get_ip_address(domain):
  31. try:
  32. return socket.gethostbyname(domain)
  33. except socket.gaierror as e:
  34. print(f"无法解析域名 {domain}: {e}")
  35. def read_csv(filename='results.csv'):
  36. data = []
  37. try:
  38. with open(filename, mode='r', encoding='utf-8') as csvfile:
  39. reader = csv.DictReader(csvfile);
  40. for row in reader:
  41. data.append(row);
  42. except IOError as e:
  43. print(f"read_csv error occurred: {e}");
  44. # print(data);
  45. return data;
  46. def read_json(filename='results.json'):
  47. data = None;
  48. try:
  49. with open(filename, 'r', encoding='utf-8') as file:
  50. data = json.load(file);
  51. except IOError as e:
  52. print(f"read_json error occurred: {e}");
  53. # print(data);
  54. return data;
  55. def seconds_to_beijing_time(seconds):
  56. utc_time = datetime.fromtimestamp(seconds, tz=timezone.utc);
  57. beijing_time = utc_time.astimezone(timezone(timedelta(hours=8)));
  58. formatted_time = beijing_time.strftime('%Y-%m-%d %H:%M:%S');
  59. return formatted_time;
  60. def parse_set_cookie(cookies_str):
  61. """
  62. 解析HTTP响应头中的'Set-Cookie'字段,并返回一个cookie字典。
  63. """
  64. attrib_keys = ['Expires', 'Max-Age', 'Domain','Path','HttpOnly', 'SameSite'];
  65. parts = cookies_str.split(';');
  66. main_key = None;
  67. ret_dict = {};
  68. ret_data = [];
  69. for pstr in parts:
  70. pstr = pstr.strip();
  71. a_key = None;
  72. a_value = True;
  73. if '=' in pstr:
  74. a_key, a_value = pstr.split('=');
  75. a_key = a_key.strip();
  76. a_value = a_value.strip();
  77. else:
  78. a_key = pstr;
  79. if a_key in attrib_keys:
  80. if main_key in ret_dict:
  81. ret_dict[main_key][a_key] = a_value;
  82. attribs = ret_dict[main_key]['attribs'];
  83. attribs[a_key] = a_value;
  84. else:
  85. main_key = a_key;
  86. attribs = {};
  87. if ',' in main_key:
  88. keys = main_key.split(',');
  89. for k in keys:
  90. k = k.strip();
  91. if k in attrib_keys:
  92. attribs[k] = True;
  93. else:
  94. main_key = k;
  95. ret_dict[main_key] = {'name': main_key, 'value':a_value, 'attribs':attribs};
  96. ret_data.append(ret_dict[main_key]);
  97. return ret_data;