SSH Port Forwarding – How to Clear Local SSH Port for Remote Forwarding

portssh

I'm using ssh forwarding local port to a bastion server(10.20.30.40), connect to remote RDS database.

ssh -i ~/.ssh/id_rsa -f -N -L 5432:db1.cluster-1.region.rds.amazonaws.com:5432 10.20.30.40 -v
...
Authenticated to 10.20.30.40 ([10.20.30.40]:22).
debug1: Local connections to LOCALHOST:5432 forwarded to remote address db1.cluster-1.region.amazonaws.com:5432
debug1: Local forwarding listening on ::1 port 5432.
debug1: channel 0: new [port listener]
debug1: Local forwarding listening on 127.0.0.1 port 5432.
debug1: channel 1: new [port listener]
debug1: Requesting [email protected]
debug1: forking to background
debug1: Entering interactive session.
debug1: pledge: network
debug1: client_input_global_request: rtype [email protected] want_reply 0

The 5432 on local port will be used. If create a new forwarding

ssh -i ~/.ssh/id_rsa -f -N -L 5433:db1.cluster-1.region.rds.amazonaws.com:5432 10.20.30.40 -v

The 5433 port will be used.

If start 5432 in a new terminal, it will be failed because already in use.

Authenticated to 10.20.30.40 ([10.20.30.40]:22).
debug1: Local connections to LOCALHOST:5432 forwarded to remote address db1.cluster-1.region.rds.amazonaws.com:5432
debug1: Local forwarding listening on ::1 port 5432.
bind [::1]:5432: Address already in use
debug1: Local forwarding listening on 127.0.0.1 port 5432.
bind [127.0.0.1]:5432: Address already in use
channel_setup_fwd_listener_tcpip: cannot listen to port: 5432
Could not request local forwarding.
debug1: Requesting [email protected]
debug1: forking to background
debug1: Entering interactive session.
debug1: pledge: network
debug1: client_input_global_request: rtype [email protected] want_reply 0

How to release these ports connection?

Best Answer

The port is going to be blocked as long as your SSH session is active. If you weren't spawning it into the background with the -f parameter you could just log out or hit ctrl-c, you can't do that with the session in the background.

You can list running processes with ps. Then you kan kill the process.

$ ps  -af |grep ssh
username    2113    1822  0 10:19 pts/0    00:00:00 ssh -L 5433:db1.cluster-1.region.rds.amazonaws.com:5432 host
$ kill 2113