ModbusTCP从站(服务端)扫描工具 python实现

扫描指定IP网络下,有哪些modbusTCP服务端[1-247]

参考连接:https://pymodbus.readthedocs.io/en/dev/source/examples.html

from pymodbus.client import ModbusTcpClient
from pymodbus.exceptions import ModbusIOException, ConnectionException, NoSuchSlaveException
import time
def read_holding_registers(client, slave_address):
"""尝试读取指定从站的保持寄存器40001的数据"""
try:
# 使用client.read_holding_registers函数读取保持寄存器
result = client.read_holding_registers(0, 1, slave_address)
# 检查result是否为ModbusIOException,如果是,则直接处理异常,不尝试访问registers属性
if isinstance(result, ModbusIOException):
raise result # 重新抛出异常以便在外部统一处理
print(f"Slave {slave_address}: {result.registers[0]}")
except ConnectionException as e:
# 如果连接问题或无此从站,则捕获异常并打印信息
print(f"Error connecting to or reading from Slave {slave_address}: {e}")
except ModbusIOException as e:
# 其他Modbus通信错误
print(f"Error communicating with Slave {slave_address}: {e}")
except NoSuchSlaveException as e:
# NoSuchSlaveException
print(f"NoSuchSlaveException with Slave {slave_address}: {e}")
if __name__ == "__main__":
# 初始化TCP客户端,这里以默认端口502为例
client = ModbusTcpClient('localhost', port=502) # 请将'localhost'替换为实际的Modbus TCP服务器IP地址
# 连接到Modbus TCP设备
if client.connect():
print("Connected to Modbus TCP device.")
# 循环遍历从站地址1至247
for slave_address in range(1, 248):
read_holding_registers(client, slave_address)
time.sleep(0.200) # 延迟200毫秒
# 关闭连接
client.close()
else:
print("Failed to connect to the Modbus TCP device.")

__EOF__

  • 本文作者: 生命在等待中延续
  • 本文链接: https://www.cnblogs.com/guyk/p/18195237
  • 关于博主: 评论和私信会在第一时间回复。或者直接私信我。
  • 版权声明: 本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
  • 声援博主: 如果您觉得文章对您有帮助,可以点击文章右下角推荐一下。
  • posted @   生命在等待中延续  阅读(381)  评论(1编辑  收藏  举报
    相关博文:
    阅读排行:
    · 本地部署 DeepSeek:小白也能轻松搞定!
    · 如何给本地部署的DeepSeek投喂数据,让他更懂你
    · 在缓慢中沉淀,在挑战中重生!2024个人总结!
    · 从 Windows Forms 到微服务的经验教训
    · 李飞飞的50美金比肩DeepSeek把CEO忽悠瘸了,倒霉的却是程序员
    历史上的今天:
    2018-05-16 使用WinDbg分析蓝屏dump原因
    点击右上角即可分享
    微信分享提示