如何实现Telnet会话连发指令后断开,周期性读取温湿度数据?
解决Fluke 1620A温湿度计Telnet单连接限制下的实时数据采集问题
问题背景
- 实验室使用Fluke 1620A "Dewk"温湿度计,此前需手动读取高处设备的温湿度数据
- 已通过批处理+VBS脚本,经LAN以Telnet连接设备自动获取数据,但设备仅支持单用户同时连接
- 当前脚本需60秒后断开连接,需求改为:每隔几秒发送
Read? 1指令获取实时数据,同时允许其他用户正常连接 - 尝试修改代码实现断开重连,但第二次连接失败,需关闭所有窗口重新启动,现寻求PowerShell或VBS解决方案
当前使用的代码
批处理代码
cls @echo off :: Open a Telnet window :: start telnet.exe 192.168.20.9 10001 start telnet.exe :: Run the script cscript SendKeys.vbs @echo off set /a "t=60" :loop timeout /t 1 /nobreak > nul set /a "t-=1" if "%t%" == "0" goto timedout cls Echo Closing Telnet in %t% seconds! goto loop :timedout Taskkill /im telnet.exe :: pause goto :eof
VBS代码
set OBJECT=WScript.CreateObject("WScript.Shell") WScript.sleep(500) OBJECT.SendKeys "o 192.168.20.9 10001{ENTER}" OBJECT.SendKeys "Read? 1{ENTER}"
解决方案
原脚本依赖Telnet窗口的SendKeys操作,不仅稳定性差,还会长时间占用设备的单连接资源。以下采用短连接模式的方案:每次连接设备、获取数据后立即断开,既保证实时采集,又不占用连接资源,让其他用户可随时连接。
PowerShell方案
# 设备配置 $deviceIp = "192.168.20.9" $devicePort = 10001 # 采集间隔(单位:秒) $interval = 5 while ($true) { try { # 建立TCP短连接 $tcpClient = New-Object System.Net.Sockets.TcpClient($deviceIp, $devicePort) $stream = $tcpClient.GetStream() $reader = New-Object System.IO.StreamReader($stream) $writer = New-Object System.IO.StreamWriter($stream) $writer.AutoFlush = $true # 发送读取指令 $writer.WriteLine("Read? 1") # 获取并输出数据 $response = $reader.ReadLine() Write-Host "[$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')] 温湿度数据:$response" # 立即断开连接 $reader.Close() $writer.Close() $stream.Close() $tcpClient.Close() } catch { Write-Host "[$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')] 操作失败:$_" } # 等待下一次采集 Start-Sleep -Seconds $interval }
VBS方案
' 设备配置 Dim deviceIp, devicePort, interval deviceIp = "192.168.20.9" devicePort = 10001 interval = 5 ' 采集间隔(秒) Do On Error Resume Next Dim tcpClient, stream, reader, writer Set tcpClient = CreateObject("System.Net.Sockets.TcpClient") tcpClient.Connect deviceIp, devicePort ' 处理连接错误 If Err.Number <> 0 Then WScript.Echo "[" & Now() & "] 连接失败:" & Err.Description Err.Clear WScript.Sleep interval * 1000 Continue Do End If ' 建立数据流读写对象 Set stream = tcpClient.GetStream() Set reader = CreateObject("System.IO.StreamReader", stream) Set writer = CreateObject("System.IO.StreamWriter", stream) writer.AutoFlush = True ' 发送指令并读取数据 writer.WriteLine "Read? 1" Dim response response = reader.ReadLine() WScript.Echo "[" & Now() & "] 温湿度数据:" & response ' 关闭资源,断开连接 reader.Close() writer.Close() stream.Close() tcpClient.Close() ' 等待下一次采集 WScript.Sleep interval * 1000 Loop
方案说明
- 两种方案均采用TCP短连接,每次采集完成后立即断开,不会长时间占用设备的单连接资源,其他用户可随时连接设备
- 避免了原脚本依赖Telnet窗口SendKeys的不稳定问题,重连失败的情况也不会再出现
- 可根据需求调整
$interval(PowerShell)或interval(VBS)的值来设置采集间隔
内容的提问来源于stack exchange,提问作者Paul Arnold
相关产品推荐
相关产品推荐

