Python 2.7.5下通过Telnet连接CentOS本地服务获取输出失败的技术问询
Hey there, let's work through this telnet script issue step by step. I see you're using Python 2.7.5 (quick heads up: it's end-of-life now, but we'll focus on fixing your current script first) to interact with a local service on port 5555, and you're having trouble capturing the getcellstat output. Let's break down the problems and fix them one by one:
First, Fix the Obvious Typo
In your original script, you have:
print(red)
But your captured output variable is named res—that's a simple typo! No wonder you didn't see any command output. Change that line to print(res) first.
Clean Up String/Byte Mixing & Command Execution
Python 2 handles strings and bytes differently than Python 3, and telnetlib in Python 2 expects string inputs (not byte literals like b"\n"). Let's fix your write calls:
- When sending username and password, don't mix string variables with byte literals. Append a regular newline string instead:
(Sincetn.write(user + "\n") tn.write(password + "\n")passwordis already a string, no need to encode it in Python 2.) - In your modified script, you forgot to add a newline to the
getcellstatcommand—so the service never got the signal to execute it! Always end CLI commands with\nwhen using telnet:tn.write("getcellstat --cellid 1\n")
Adjust Read Timing & Prompt Matching
Your read_until calls might be timing out before the prompt appears, or the match string isn't exactly what the service sends. Let's tweak these:
- Increase timeout values: 5 seconds might not be enough for the service to respond, especially after running a command that generates output. Try setting timeouts to 10-15 seconds, or use
Noneto wait indefinitely (use cautiously):tn.read_until("login: ", 10) - Verify exact prompt strings: Looking at your manual telnet output, after typing
l2, the prompt briefly showsmnxt[/]#before switching tomnxt[/l2]#. Your script waits for the latter immediately, but a short delay or extra line might throw it off. Keep the existing match but give it more time. - Confirm the end marker: Your
****** RNTI List end******marker is perfect for capturing full output—just make sure the timeout is long enough for the command to finish running:res = tn.read_until("****** RNTI List end******", 15)
Fix the Random "g" Output
That odd "g" in your modified script's output is because you didn't send a newline with the getcellstat command. The service was still waiting for input, and read_very_eager() picked up a partial character from the buffer. Adding the \n to the command will resolve this.
Full Corrected Script Example
Here's a revised version of your script with all these fixes:
#!/usr/bin/python import telnetlib import time host = "127.0.0.1" user = "root" password = "mavenir" tn = telnetlib.Telnet(host, 5555) # Optional: Enable debug to see all sent/received data # tn.set_debuglevel(1) # Handle login flow tn.read_until("login: ", 10) tn.write(user + "\n") tn.read_until("password: ", 10) tn.write(password + "\n") # Navigate to l2 context tn.read_until("mnxt[/]#", 10) tn.write("l2\n") tn.read_until("mnxt[/l2]#", 10) # Run command and capture output tn.write("getcellstat --cellid 1\n") # Short wait to ensure command finishes executing time.sleep(2) res = tn.read_until("****** RNTI List end******", 15) print(res) # Clean up the connection tn.close()
Additional Tips
- Migrate to Python 3: Python 2 is no longer supported, and Python 3's
telnetlibhandles bytes more explicitly, which avoids confusion like string/byte mixing. - Use debug mode: Add
tn.set_debuglevel(1)right after creating theTelnetobject to see all incoming/outgoing data. This is invaluable for figuring out where the script gets stuck or mismatches prompts. - Check for hidden characters: Ensure your match strings exactly match the service's output (e.g., no extra spaces, tabs, or case differences between
mnxtandMNXT).
内容的提问来源于stack exchange,提问作者Huud Rych

