Reputation: 189
Im using a python script to open tunnels automaticly and im searching for a way to see if tunnel is being used.
python code:
from sshtunnel import SSHTunnelForwarder
server = ( SSHTunnelForwarder(
'main_server_ip',
ssh_username="username",
ssh_pkey="~/.ssh/id_rsa",
local_bind_address=('0.0.0.0', randomPort),
remote_bind_address=(host_ip, 3389)
) )
I used sshtunnel
options :
server.skip_tunnel_checkup = False
server.start()
server.check_tunnels()
print(server.tunnel_is_up, flush=True)
But it only shows if tunnel is open \ active not used, i have looked for a way before posting this but all examples shows only if tunnel is active\ open.
i need an option to see if tunnel is used \ not used so i can close it if it has not being used for X time.
The tunnels are for rdp connections and for me used is if someone is connected through the tunnel to an rdp connection and working on it. if rdp session is closed then it means tunnel is not used.
Thanks
Upvotes: 2
Views: 2556
Reputation: 189
This was my solution :
import subprocess, re, socket
ip_address = (([ip for ip in socket.gethostbyname_ex(socket.gethostname())[2] if not ip.startswith("127.")] or [[(s.connect(("8.8.8.8", 53)), s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1]]) + ["no IP found"])[0]
ports_used = []
p = subprocess.Popen(["netstat", "-na"], stdout=subprocess.PIPE)
out = p.stdout.read()
lines = out.decode('utf-8').split('\n')
for line in lines:
is_open = re.match(rf'tcp.*{ip_address}:([0-9][0-9]*).*ESTABLISHED\s*$', line)
if is_open is not None:
ports_used.append(is_open[1])
Ruining netstat command to find on machine all ESTABLISHED
ports, and from there to filter by host\container ip, and then match it to the ports i know are open in my db data.
(ssh tunnel ports that are active\ open are all listed in my database.)
so then, i could see if port is not in is_open
means connection has been closed.
Upvotes: 1