j0h

scanModbus

j0h
Apr 6th, 2026
165
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.04 KB | None | 0 0
  1. #!/usr/bin/env python3
  2. import socket
  3. import struct
  4. from time import sleep
  5. import sys,os
  6.  
  7. ip = "192.168.1.7"
  8. port = 502
  9.  
  10. unit_id = 1
  11. start_reg = 4607
  12. count = 16
  13.  
  14. transaction_id = 1
  15. protocol_id = 0
  16. length = 6
  17. function_code = 4
  18.  
  19. pkt = struct.pack(
  20.     ">HHHBBHH",
  21.     transaction_id,
  22.     protocol_id,
  23.     length,
  24.     unit_id,
  25.     function_code,
  26.     start_reg,
  27.     count
  28. )
  29.  
  30. with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
  31.     s.connect((ip, port))
  32.     s.sendall(pkt)
  33.     resp = s.recv(1024)
  34.  
  35. print("Raw response:", resp.hex())
  36.  
  37. if len(resp) < 9:
  38.     raise SystemExit("Short response")
  39.  
  40. if resp[7] == 0x84:
  41.     print(f"Modbus exception code: 0x{resp[8]:02X}")
  42.     raise SystemExit
  43.  
  44. byte_count = resp[8]
  45. data = resp[9:9 + byte_count]
  46.  
  47. registers = [struct.unpack(">H", data[i:i+2])[0] for i in range(0, len(data), 2)]
  48. while True:
  49.     for i, value in enumerate(registers):
  50.         print(f"304{608 + i:03d}: {value} (0x{value:04X})")
  51.     sleep(0.5)
  52.     os.system('clear')
  53.  
  54.  
  55. """"
  56. is D516,518 bogus? ??
  57. """
Advertisement
Add Comment
Please, Sign In to add comment