如何在Plink中启用保活机制以维持MySQL隧道连接?
Nice question! I’ve dealt with this exact problem when maintaining Plink tunnels for MySQL connections—nothing’s more frustrating than a tunnel dropping mid-query. Let’s go through the reliable fixes to keep that connection alive.
-o Flag to Pass SSH Keepalive Settings Plink doesn’t have a dedicated "keepalive" command-line switch, but it supports passing standard OpenSSH configuration parameters via the -o flag. This is the quickest fix for one-off commands:
Add these two options to your existing command:
ServerAliveInterval=30: Sends a keepalive packet to the bridge server every 30 seconds to keep the connection activeServerAliveCountMax=3: Tells Plink to give up and disconnect if it doesn’t get 3 consecutive responses (prevents hanging on dead connections)
Your updated command will look like this:
plink.exe -L [客户端端口]:[MySQL服务器主机名]:3306 [桥接服务器SSH用户名]@[桥接服务器IP] -i [私钥] -o ServerAliveInterval=30 -o ServerAliveCountMax=3
This works because most firewalls and routers drop idle connections after a set period (usually 5-10 minutes)—the regular keepalive packets trick them into thinking the connection is still in use.
If you’re running this tunnel regularly, setting up a config file will save you from typing all those parameters every time:
- On Windows, create a
.sshfolder in your user directory (e.g.,C:\Users\YourUsername\.ssh) - Inside that folder, make a plain text file named
config(no file extension) - Add the following content, replacing the placeholders with your details:
Host bridge-mysql-tunnel HostName [桥接服务器IP] User [桥接服务器SSH用户名] IdentityFile [full path to your private key] ServerAliveInterval 30 ServerAliveCountMax 3
Now you can run your tunnel with a much simpler command:
plink.exe -L [客户端端口]:[MySQL服务器主机名]:3306 bridge-mysql-tunnel
Plink will automatically pull the keepalive settings and login details from the config file.
If your tunnel still drops occasionally (e.g., the bridge server has aggressive timeout policies), you can use Windows Task Scheduler to automatically restart Plink if it exits:
- Open Task Scheduler and create a new "Task" (not a basic task, for more control)
- Triggers: Add a trigger that runs "On an event"—filter for when the Plink process exits, or use a simple "Every 5 minutes" trigger to check if the process is running
- Actions: Add an action to "Start a program", pointing to
plink.exewith your full tunnel command as arguments - Settings: Check "Run whether user is logged on or not" and "Run with highest privileges" (if needed), and enable "If the task fails, restart every 1 minute"
This acts as a safety net to ensure your tunnel is always up when you need it.
内容的提问来源于stack exchange,提问作者Matioski




