Linux: How to port forward only while a process uses a port.

I work in an environment where the email servers are behind an SSH gateway, and sending emails through them is a pain since we need to do…

Linux: How to port forward only while a process uses a port.

I work in an environment where the email servers are behind an SSH gateway, and sending emails through them is a pain since we need to do many steps:

  1. Establish the port forward
  2. Do the task
  3. Destroy the tunnel

I was looking for a solution that would establish a port forward only while the process would run; Icould not find something ready and well-tested, so i created my own tool, which has served me well so far.

kpatronas/with-tunnel: Create an SSH tunnel and keep-it running as long as your process that will use the tunnel. (github.com)

This tool allows you to port forward only while a process is running and uses the following syntax

with-tunnel --proxy_host ssh_gateway \ 
            --proxy_user username    \ 
            --target_port 25         \ 
            --target_host target_srv \ 
            --local_port 25000       \ 
            --process 'echo "Please find attached the files" | mailx -v -a /home/kpatronas/myfiles.zip -r "kpatronas@example.com" -s "files bundle" -S smtp="127.0.0.1:25000" -S ssl-verify=ignore takis@example.com'

Options explanation:

SSH Proxy options

  • — proxy_host: The ssh proxy to be used (Required).
  • — proxy_port: The port of the ssh proxy to be used (Not required, default is port 22).
  • — proxy_user: The user to be connected to ssh proxy (Not required, default is the running user).
  • — proxy_pass: The password to be used to connect to the ssh proxy (Not required).
  • — proxy_key: The ssh key to connect to the ssh proxy (Not required).

Note: if no proxy_pass or proxy_key is given with-tunnel will try to use the default ssh key of the running user. Giving at the same time, proxy_pass and proxy_key are not allowed.

Target options

  • — target_host: The host on the end of the tunnel that we want to establish a connection (Required).
  • — target_port: The port of the host on the end of the tunnel that we want to establish the connection (Required).

Local options

  • — local_ip: A local machine ip to be used to create the start of the tunnel (Not required, default is 127.0.0.1).
  • — local_port: A port of the local machine to be used to create the start of the tunnel (Required).

Process options

— process: The program to be executed with-tunnel will exit when the program is completed; if the process option is not given, with-tunnel will keep the tunnel open until it is terminated with a ctrl+c.

Note: if your program has parameters, you need to pass the program and its parameters surrounded with quotes.

Join Medium with my referral link - Konstantinos Patronas
As a Medium member, a portion of your membership fee goes to writers you read, and you get full access to every story…