使用Python的Paramiko实现Windows机器间远程桌面连接及报错排查
Let me break down the most likely fixes for this error—since you're working with Windows machines, there are several platform-specific checks that often resolve this "connection forcibly closed" issue:
First, confirm the remote Windows machine has SSH properly set up
Windows doesn't include an SSH server by default. You need to install OpenSSH Server:- Go to Settings > Apps > Optional features > Add a feature
- Search for "OpenSSH Server", install it, then start the service via Services (look for
OpenSSH SSH Serverand set its startup type to Automatic) - Test local connectivity on the remote machine by running
ssh localhostin Command Prompt—if this fails, the SSH service itself is broken, not your Paramiko code.
Check firewall and network rules
This is the #1 culprit for WinError 10054:- On the remote machine: Add an inbound firewall rule to allow TCP traffic on port 22 (default SSH port). You can do this via Windows Defender Firewall > Advanced Settings > Inbound Rules > New Rule.
- On your local machine: Ensure outbound traffic on port 22 isn't blocked by your firewall.
- If connecting over a network, confirm both machines can ping each other, and there's no router/switch blocking port 22 traffic.
Validate your Paramiko connection parameters
Double-check you're using the right credentials and settings:- Use the correct Windows username: For local accounts, just use the username (e.g.,
john); for domain accounts, format it asDOMAIN\john. - If you changed the default SSH port on the remote machine, make sure to specify
port=your_custom_portinssh.connect(). - Here's a minimal working example to test with:
import paramiko ssh_client = paramiko.SSHClient() ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) try: # Replace with your remote IP, username, password ssh_client.connect("192.168.1.100", username="win_user", password="your_pass", port=22) print("Connection successful!") ssh_client.close() except Exception as e: print(f"Connection failed: {str(e)}")
- Use the correct Windows username: For local accounts, just use the username (e.g.,
Inspect the remote SSH server configuration
Navigate toC:\ProgramData\ssh\sshd_config(note: ProgramData is a hidden folder) and check:PasswordAuthentication yesis uncommented if you're using password login.- The
Bannerdirective isn't pointing to a non-existent file—this can cause protocol banner reading errors. - After making changes, restart the
OpenSSH SSH Serverservice to apply them.
Dig deeper into system logs
If none of the above works, check the remote machine's Event Viewer (Windows Logs > Application) for OpenSSH-related errors. This can reveal if the SSH service is crashing due to resource issues or misconfiguration. Also, try connecting with a standard SSH client like PuTTY—if PuTTY fails too, the problem is definitely system/network-related, not your code.
内容的提问来源于stack exchange,提问作者User2014

