You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用telnetlib连接远程设备超时,CMD下正常的技术求助

Troubleshooting Telnetlib Timeout Issue When Manual Telnet Works

I’ve run into this exact kind of mismatch between manual Telnet and scripted telnetlib interactions before—let’s break down what’s likely going wrong and fix it.

First, let’s recap your scenario to make sure I’m on the same page:

  • Manual Telnet via CMD works perfectly: you connect, see user>, input su, get password>, enter 1234, land at mp4100#, then send ? (no need for a return?) to get help output.
  • But your Python telnetlib code keeps timing out, even though the logic seems to mirror the manual steps.

Looking at your snippet, here are the most common culprits and how to fix them:

Key Issues in Your Initial Code

  1. Too-short timeout: time_out = 2 is barely enough for fast local devices, let alone remote ones that might have slight latency in responding to prompts.
  2. Missing explicit prompt waiting: You need to explicitly wait for each expected prompt before sending the next command—otherwise, the script might send input before the device is ready, leading to garbled interactions and timeouts.
  3. Unspecified line endings: Most network devices expect \r (carriage return) instead of \n for line endings when sending commands via Telnet.
  4. Lack of error handling: Without catching specific errors like TelnetTimeoutError, it’s hard to pinpoint where the flow breaks.

Fixed Code with Explanations

Here’s a revised script that addresses all these points:

import telnetlib
import time

HOST = "172.17.174.241"
su_command = 'su'
password = '1234'
timeout = 10  # Extended timeout to account for device latency
# Define all expected prompts clearly (encoded as bytes for telnetlib)
PROMPTS = {
    'user': b'user>',
    'password': b'password>',
    'main': b'mp4100#'
}

try:
    # Initialize connection with a reasonable timeout
    tn = telnetlib.Telnet(HOST, timeout=timeout)
    
    # Optional: Enable debug mode to see raw send/receive data (super helpful for troubleshooting)
    # tn.set_debuglevel(1)
    
    # Wait for the initial user prompt before sending 'su'
    tn.read_until(PROMPTS['user'], timeout=timeout)
    print("Got user prompt—sending 'su' command")
    tn.write(su_command.encode('ascii') + b'\r')  # Send command + carriage return
    
    # Wait for password prompt, then send password
    tn.read_until(PROMPTS['password'], timeout=timeout)
    print("Got password prompt—sending password")
    tn.write(password.encode('ascii') + b'\r')
    
    # Wait for the main command prompt to confirm login success
    login_output = tn.read_until(PROMPTS['main'], timeout=timeout)
    print("Successfully logged in!\nInitial output:\n", login_output.decode('ascii'))
    
    # Send the '?' command (adjust line ending if needed—you said no return, but test if adding '\r' works better)
    tn.write(b'?')
    # Read the help output (use read_until if you know a closing prompt, or read_very_eager for immediate output)
    help_output = tn.read_very_eager().decode('ascii')
    print("\nHelp command output:\n", help_output)

except telnetlib.TelnetTimeoutError:
    print("Timeout hit! Check if your prompts match exactly, or increase the timeout value.")
except Exception as e:
    print(f"Unexpected error: {str(e)}")
finally:
    # Always clean up the connection
    if 'tn' in locals():
        tn.close()

Additional Troubleshooting Tips

  • Use debug mode: Uncomment tn.set_debuglevel(1) to see every byte sent and received. This will tell you if the device is returning a slightly different prompt (e.g., user> with a trailing space) that your script isn’t matching.
  • Check line endings: If \r doesn’t work, try \n or \r\n—some devices are pickier than others.
  • Verify prompt exactness: Make sure the prompts in your code match exactly what the device sends (including any leading/trailing whitespace or special characters). Use the debug output to confirm this.
  • Check port number: If your device isn’t using the default Telnet port (23), add the port parameter to the Telnet constructor, like telnetlib.Telnet(HOST, port=2323, timeout=timeout).

内容的提问来源于stack exchange,提问作者CIsForCookies

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:44:10