如何实现Telnet连接的密码有效性验证与多重试机制?
Telnet Password Verification & Retry Implementation
Hey there! Let's fix your Telnet password validation and retry logic issue. Since you mentioned using read_until(b'P...') to judge the result, we can build around that to create a reliable flow.
Core Idea
Telnet sessions typically give clear cues after password attempts:
- Success: You'll get a command line prompt (e.g.,
root@vm:~#) - Failure: You'll see the password prompt again (like
Password:) or an error message (e.g.,Login incorrect)
We can use these cues with telnetlib's read_until to verify success, and wrap the password input in a loop for retries.
Working Code Example
Here's a practical implementation using Python's telnetlib and getpass for secure input:
import getpass import telnetlib # Configure your VM details VM_HOST = "127.0.0.1" # Replace with your VM's IP/hostname VM_USERNAME = "your_username" # Replace with your VM username MAX_RETRY_ATTEMPTS = 3 def establish_telnet_connection(): # Initialize Telnet connection tn = telnetlib.Telnet(VM_HOST) # Wait for login prompt and send username tn.read_until(b"Login: ") tn.write(f"{VM_USERNAME}\r\n".encode("ascii")) # Retry loop for password attempts for attempt in range(MAX_RETRY_ATTEMPTS): # Wait for password prompt (matches your b'P...' plan) tn.read_until(b"Password: ") # Securely get password from user input user_password = getpass.getpass(f"Enter password (attempt {attempt+1}/{MAX_RETRY_ATTEMPTS}): ") tn.write(f"{user_password}\r\n".encode("ascii")) # Check if the attempt succeeded # Adjust the timeout and target strings to match your VM's actual output response = tn.read_until(b"Password: ", timeout=2) if b"Password: " not in response: # Success! Proceed with your commands print("✅ Password verified successfully!") tn.write(b"uname -a\r\n") # Example command print(tn.read_all().decode("ascii")) tn.close() return else: print(f"❌ Attempt {attempt+1} failed. Wrong password.") # All retries exhausted print(f"❌ All {MAX_RETRY_ATTEMPTS} attempts failed. Closing connection.") tn.close() if __name__ == "__main__": establish_telnet_connection()
Key Adjustments for Your VM
- Update prompt strings: Replace
b"Login: "andb"Password: "with the exact byte strings your VM outputs. You can get these from your terminal test (copy the exact prompt text). - Add error checks: If your VM outputs
Login incorrecton failure, add that to the failure condition:if b"Password: " in response or b"Login incorrect" in response: # Handle failure - Adjust timeout: The
timeout=2value ensures we don't wait indefinitely—tweak it based on your VM's response speed.
Why This Works
getpass.getpass()hides the password input for security, unlike plaininput().- The loop limits retries to avoid infinite loops.
read_untillets us reliably detect the VM's response to our password attempt.
内容的提问来源于stack exchange,提问作者madcrazydrumma




