如何用Python程序连接GCP上的Windows虚拟机?含密钥生成指导
Hey there! Let’s work through your problem step by step—connecting to your GCP Windows Server 2019 VM from Windows 10 using Python 3.7 without RDP, including fixing the key generation issue.
First: Generate & Import SSH Keys (Since You Can’t Do It Directly in GCP)
You can generate keys locally on your Windows 10 machine, then import the public key into GCP. Here’s how:
Generate keys locally
- Open Command Prompt, PowerShell, or Git Bash (all work since Windows 10 includes OpenSSH by default).
- Run this command to create an RSA key pair (replace the email with your own for identification):
ssh-keygen -t rsa -b 4096 -C "your-email@example.com" - Press Enter through all prompts (you can set a passphrase for extra security, or skip it for easier scripting). This will create two files in
C:\Users\YourUsername\.ssh:id_rsa: Your private key (keep this secure—never share it!)id_rsa.pub: Your public key (we’ll import this to GCP)
Import the public key to GCP
- Go to your GCP Console, navigate to your VM instance, and click Edit.
- Scroll down to the SSH keys section, click Add item.
- Paste the entire contents of
id_rsa.pubinto the text box, then save the changes.
Recommended Python Packages & Scripts
Two solid options here: Paramiko (for SSH-based connections, perfect for key auth) and WinRM (Windows-native remote management). Let’s break both down:
Option 1: Paramiko (SSH Connection)
This is the most straightforward way to use your SSH keys to connect and run commands on the Windows VM. First, enable OpenSSH Server on your GCP VM:
- On the Windows Server 2019 VM, go to Settings > Apps > Optional features > Add a feature.
- Find OpenSSH Server, install it, then start the service (set it to start automatically so it persists after reboots).
Install Paramiko:
pip install paramiko
Sample script to connect and execute a command:
import paramiko # Update these values with your own details PRIVATE_KEY_PATH = "C:/Users/YourUsername/.ssh/id_rsa" VM_PUBLIC_IP = "your-vm-public-ip-address" VM_USERNAME = "your-vm-admin-username" # The one you set when creating the VM # Load your private key private_key = paramiko.RSAKey.from_private_key_file(PRIVATE_KEY_PATH) # Initialize SSH client ssh_client = paramiko.SSHClient() # Auto-add the VM's host key (for testing—verify manually in production!) ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) try: # Connect to the VM ssh_client.connect(hostname=VM_PUBLIC_IP, username=VM_USERNAME, pkey=private_key) print("Connected to GCP VM successfully!") # Example: Run a command to get OS version info stdin, stdout, stderr = ssh_client.exec_command( "systeminfo | findstr /B /C:\"OS Name\" /C:\"OS Version\"" ) # Print output and errors (if any) output = stdout.read().decode("utf-8") error = stderr.read().decode("utf-8") if output: print("\nCommand Output:\n", output) if error: print("\nError:\n", error) finally: # Always close the connection when done ssh_client.close()
Option 2: WinRM (Windows Native Remote Management)
If you prefer using Windows’ built-in remote tooling, WinRM works well. Note that key-based auth here requires extra certificate setup, so we’ll cover password auth first (we can expand to key auth if needed).
First, configure WinRM on your GCP VM:
- Open PowerShell as admin on the VM and run:
Enable-PSRemoting -Force Set-NetFirewallRule -Name "WINRM-HTTP-In-TCP" -RemoteAddress Any
Install the pywinrm package:
pip install pywinrm
Sample script to run a command via WinRM:
import winrm # Update these values with your own details VM_PUBLIC_IP = "your-vm-public-ip-address" VM_USERNAME = "your-vm-admin-username" VM_PASSWORD = "your-vm-admin-password" # Create a WinRM session session = winrm.Session(VM_PUBLIC_IP, auth=(VM_USERNAME, VM_PASSWORD)) # Run a command to get OS version info result = session.run_cmd( "systeminfo", ["|", "findstr", "/B", "/C:\"OS Name\"", "/C:\"OS Version\""] ) # Print the results print(f"Exit Code: {result.status_code}") print("\nOutput:\n", result.std_out.decode("utf-8")) print("\nError:\n", result.std_err.decode("utf-8"))
Critical Notes
- GCP Firewall Rules: Make sure you add inbound rules to allow:
- SSH (port 22) for Paramiko
- WinRM HTTP (port 5985) or HTTPS (port 5986) for WinRM
- Restrict the source IP to your Windows 10 machine’s public IP for better security.
- Private Key Permissions: On Windows, ensure only your user has access to
id_rsa(right-click the file > Properties > Security > Advanced > Remove all other users, add only your account with read access). Paramiko will throw errors if permissions are too open.
内容的提问来源于stack exchange,提问作者Ajinkya

