-->
当前位置:首页 > DayDayUp > 正文内容

[python] 大华ICC平台事件FTP摆渡 报警事件与报警图片打包上传FTP

Luz11个月前 (08-12)DayDayUp1497

订阅ICC平台事件后,运行程序监听事件推送。
下载事件中的图片,并于json打包后存放至FTP,便于网闸搬运

  1. from flask import Flask, request, json
  2. import requests
  3. import base64
  4. import json
  5. from Crypto.Cipher import PKCS1_v1_5 as Cipher_pksc1_v1_5
  6. from Crypto.PublicKey import RSA
  7. import urllib3
  8. import time
  9. import zipfile
  10. import os
  11. from ftplib import FTP
  12. from datetime import datetime
  13. # 禁用SSL警告
  14. urllib3.disable_warnings()
  15. # 平台鉴权信息修改登录地址为实际地址
  16. base_url = "https://33.x.x.x"
  17. username = "system"
  18. password = "xxxxx"
  19. client_id = "xxxxx"
  20. client_secret = "xxxxx"
  21. magic_id = ''
  22. headers = {}
  23. token = ""
  24. def rsa_encrypt(string, public_key):
  25. # 使用RSA公钥加密
  26. rsakey = RSA.importKey(public_key)
  27. cipher = Cipher_pksc1_v1_5.new(rsakey)
  28. encrypt_text = cipher.encrypt(string.encode())
  29. cipher_text_tmp = base64.b64encode(encrypt_text)
  30. return cipher_text_tmp.decode()
  31. def get_public_key():
  32. # 获取公钥
  33. public_key = json.loads(requests.get(base_url + "/evo-apigw/evo-oauth/1.0.0/oauth/public-key", verify=False).text)['data']['publicKey']
  34. return public_key
  35. def login():
  36. global magic_id
  37. global token
  38. # 登录获取token
  39. public_key = get_public_key()
  40. print("public_key:\t", public_key)
  41. encrypted_pass = rsa_encrypt(password, '-----BEGIN PUBLIC KEY-----\n' + public_key + '\n-----END PUBLIC KEY-----')
  42. print("encrypted_pass:\t" + encrypted_pass)
  43. data = {
  44. "grant_type": "password",
  45. "username": username,
  46. "password": encrypted_pass,
  47. "client_id": client_id,
  48. "client_secret": client_secret,
  49. "public_key": public_key
  50. }
  51. # 发送登录请求
  52. response = json.loads(requests.post(base_url + "/evo-apigw/evo-oauth/1.0.0/oauth/extend/token", json=data, verify=False).text)
  53. try:
  54. token = response['data']['access_token']
  55. magic_id = response['data']['magicId']
  56. print('更新全局token,magicId', token, magic_id)
  57. except:
  58. print('登录失败,服务器返回信息:', response)
  59. print("Token:", token)
  60. print('MagicId:', magic_id)
  61. return token
  62. app = Flask(__name__)
  63. @app.before_request
  64. def log_request_info():
  65. print(f"Request: {request.method} {request.path}")
  66. if request.method == 'GET':
  67. # 获取 GET 请求的参数
  68. params = request.args
  69. print("GET Params: {}".format(params))
  70. elif request.method == 'POST':
  71. # 尝试解析 JSON 数据
  72. try:
  73. json_data = request.get_json()
  74. print("POST JSON: {}".format(json.dumps(json_data, indent=4)))
  75. if 'info' in json_data and 'alarmPicture' in json_data['info']:
  76. image_name = json_data['info']['alarmPicture'].split('/')[-1]
  77. download_image(json_data['info']['alarmPicture'], image_name)
  78. zip_and_upload(json_data, image_name)
  79. except Exception as e:
  80. # 如果解析失败,则获取表单数据
  81. params = request.form
  82. print("POST Params: {}".format(params))
  83. def download_image(image_url, image_name):
  84. print("开始下载",image_url)
  85. global token
  86. token = login()
  87. url = f"https://33.x.x.x/evo-pic/{image_url}?token={token}&oss_addr=33.x.x.x:8925"
  88. response = requests.get(url, verify=False)
  89. if response.status_code == 200:
  90. with open(image_name, 'wb') as f:
  91. f.write(response.content)
  92. print(f"Image {image_name} downloaded successfully.")
  93. else:
  94. print(f"Failed to download image {image_name}. Status code: {response.status_code}")
  95. print(response.text)
  96. def zip_and_upload(json_data, image_name):
  97. timestamp = int(time.time() * 1000)
  98. zip_filename_base = f"SK_ALARM_{timestamp}"
  99. zip_filename = f"{zip_filename_base}.zip"
  100. temp_zip_filename = f"{zip_filename}.temp"
  101. #网闸不摆渡.temp格式的文件,但zip格式会直接摆渡,如果直接使用.zip后缀,可能在文件上传完成前就被网闸删除,因此先使用temp作为临时后缀,等文件上传完成后,再删除临时后缀
  102. with zipfile.ZipFile(zip_filename, 'w') as zipf:
  103. zipf.writestr("data.json", json.dumps(json_data, indent=4))
  104. zipf.write(image_name)
  105. ftp = FTP()
  106. ftp.connect('33.x.x.x', 21)#FTP地址
  107. ftp.login('xxxxx', 'xxxxx')#账号,密码
  108. with open(zip_filename, 'rb') as f:
  109. ftp.storbinary(f'STOR {temp_zip_filename}', f)
  110. ftp.rename(temp_zip_filename, zip_filename)
  111. ftp.quit()
  112. print(f"ZIP file {zip_filename} uploaded to FTP server successfully.")
  113. os.remove(zip_filename)
  114. os.remove(image_name)
  115. @app.route('/', defaults={'path': ''}, methods=['GET', 'POST'])
  116. @app.route('/<path:path>', methods=['GET', 'POST'])
  117. def catch_all(path):
  118. return f"Request received for {request.method} {request.path}"
  119. if __name__ == '__main__':
  120. app.run(host='0.0.0.0', port=10001)

发表评论

访客

◎欢迎参与讨论,请在这里发表您的看法和观点。