SSH远程端口转发与‘GatewayPorts yes’:应配置在哪台机器?
GatewayPorts yes的配置位置说明 Great question—this is one of those SSH config nuances that trips up even experienced users, so let’s break it down with clear roles and reasoning.
First, let’s define the two machines involved in remote port forwarding to avoid confusion:
- Source machine (the one initiating the forward):This is where you run the
ssh -Rcommand. For example, if you typessh -R 8080:localhost:3000 user@your-remote-serveron your laptop, your laptop is the source machine. - Target machine (the remote SSH server):This is the machine you’re SSHing into—the one that will expose the forwarded port to others. In the example above, that’s
your-remote-server.
The short answer
You need to add GatewayPorts yes to the target machine’s /etc/ssh/sshd_config file.
Why this matters
Here’s the breakdown of what this setting controls:
- By default,
GatewayPortsis set tonoon SSH servers. This means any ports forwarded via-Rwill only bind to the target machine’slocalhostinterface. Only processes running directly on the target machine can access those forwarded ports. - When you set
GatewayPorts yes, the SSH server (target machine) allows the forwarded port to bind to all network interfaces on the machine. This lets other devices (whether on the same local network or the public internet, if the target has a public IP) connect to that port and reach the service on your source machine.
Quick post-config step
After adding the line to /etc/ssh/sshd_config, you’ll need to restart the SSH daemon on the target machine to apply the change. On most modern Linux systems, that command is:
sudo systemctl restart sshd
Example scenario to drive it home
Suppose you’re running a local development server on your laptop (source machine) at port 3000, and you want a client to access it via your cloud server (target machine) at port 8080.
- You run
ssh -R 8080:localhost:3000 user@cloud-serveron your laptop. - Without
GatewayPorts yeson the cloud server, only someone logged into the cloud server can visit127.0.0.1:8080to reach your laptop’s server. - After enabling
GatewayPorts yesand restarting sshd on the cloud server, the client can connect tocloud-server-ip:8080and access your local 3000-port service directly.
内容的提问来源于stack exchange,提问作者Brandon Lebedev




