networkIoDetect2.py 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. import socket
  2. import struct
  3. import thread
  4. import threading
  5. import time
  6. import os
  7. import sys
  8. import json
  9. netcard=sys.argv[1]
  10. host_ip=sys.argv[2]
  11. collectTime=float(sys.argv[3])
  12. net_data = {}
  13. d_net_info = {}
  14. cancel=True
  15. def net_data_normalize():
  16. for key in net_data:
  17. net_data[key]="%s"%round(net_data[key]/collectTime,2)
  18. def init_net_data():
  19. for port in sys.argv[4:]:
  20. net_data["in_"+port]=0
  21. net_data["out_"+port]=0
  22. def get_packet():
  23. s = socket.socket(socket.PF_PACKET, socket.SOCK_DGRAM,socket.htons(0x0003))
  24. s.bind((netcard,0));
  25. while cancel:
  26. buf = s.recvfrom(40)
  27. iphead_version=(struct.unpack("B",buf[0][0:1])[0]&0xf0)/16
  28. if iphead_version != 4 and iphead_version != 6 :
  29. continue
  30. iphead_len =(struct.unpack("B",buf[0][0:1])[0]&0x0f)*4
  31. src_ip = "%d.%d.%d.%d"%struct.unpack('BBBB', buf[0][12:16])
  32. dest_ip ="%d.%d.%d.%d"%struct.unpack('BBBB', buf[0][16:20])
  33. port = struct.unpack('HH', buf[0][iphead_len:4+iphead_len])
  34. if src_ip == host_ip:
  35. src_port = socket.htons(port[0])
  36. key = "out_%d"%src_port
  37. if key in net_data:
  38. data_len =socket.htons(struct.unpack("H",buf[0][2:4])[0])
  39. net_data[key]=net_data[key]+data_len
  40. elif dest_ip == host_ip:
  41. dest_port = socket.htons(port[1])
  42. key = "in_%d"%dest_port
  43. if key in net_data:
  44. data_len =socket.htons(struct.unpack("H",buf[0][2:4])[0])
  45. net_data[key]=net_data[key]+data_len
  46. init_net_data()
  47. thread.start_new_thread(get_packet,())
  48. time.sleep(collectTime/1000)
  49. cancel=False
  50. time.sleep(0.5)
  51. net_data_normalize()
  52. result=json.dumps(net_data)
  53. print result