change_ip.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. # -*- coding: utf-8 -*-
  2. # !/usr/bin/env python
  3. import os
  4. import sys
  5. PROJECT_ROOT = os.path.join(os.path.abspath(os.path.split(os.path.realpath(__file__))[0] + "/.."), '..')
  6. sys.path.insert(0, PROJECT_ROOT)
  7. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'configs.testing')
  8. from script.base import init_env
  9. init_env(False)
  10. from apps.web.device.models import Device
  11. from apps.web.core.networking import MessageSender
  12. def is_online(devNo):
  13. return bool(Device.get_dev(devNo).online)
  14. def change_ip_and_record(devNo, debug):
  15. if debug:
  16. print devNo
  17. else:
  18. device = Device.get_dev(devNo)
  19. serverIp, _ = device.server.split(":")
  20. # IP 是写死的 需要切换
  21. MessageSender.send(
  22. device = device,
  23. cmd = 202,
  24. payload = {
  25. "IMEI": device.devNo,
  26. "addr_set": {"ip1": serverIp, "port1": 1884}
  27. },
  28. timeout = 5
  29. )
  30. with open("do_change_ip.txt", "a") as f:
  31. f.write("{}\n".format(devNo))
  32. def run(debug):
  33. if os.path.exists("do_change_ip.txt"):
  34. with open("do_change_ip.txt") as f:
  35. changedDevs = [_d.strip() for _d in f.readlines()]
  36. else:
  37. changedDevs = list()
  38. index = len(changedDevs)
  39. curIndex = index
  40. # 总量到了直接退出
  41. if index >= 10000:
  42. return
  43. devices = Device.objects.filter(server__endswith = ":1883", ownerId__ne = "")
  44. for _dev in devices:
  45. # 不需要特别关注时间的 筛选放到内存中去处理
  46. if _dev.devNo in changedDevs:
  47. continue
  48. if not is_online(_dev.devNo):
  49. continue
  50. try:
  51. change_ip_and_record(_dev.devNo, debug)
  52. except Exception as e:
  53. print "{}-{}".format(_dev.devNo, e)
  54. else:
  55. index += 1
  56. # 一次最多发1000条
  57. if index - curIndex >= 1000:
  58. break
  59. if __name__ == '__main__':
  60. # 修改 设备的IP端口 当debug为 True的时候 只记录 不发生实际修改
  61. # 每次运行最大执行设备数量为1000个 执行完毕之后自动停止 从 上次停止的设备号开始继续执行
  62. # 当执行设备到达10000的时候 执行程序不做任何事情
  63. # 执行设备号 记录在当前文件夹的 do_change_ip.txt
  64. run(debug = True)