From b0a8b60c783bbc26f09e8b22ebf3721631176c72 Mon Sep 17 00:00:00 2001 From: Russell Joyce Date: Fri, 24 Apr 2020 17:16:56 +0100 Subject: [PATCH] Added a check for whether either local port is in use before connecting Helping with #29. --- vlab.py | 22 ++++++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/vlab.py b/vlab.py index 2d731c4..7afb366 100755 --- a/vlab.py +++ b/vlab.py @@ -17,6 +17,7 @@ import argparse import os +import socket import sys import urllib.request import urllib.error @@ -92,6 +93,23 @@ def err(s): if not os.path.isfile(parsed.key[0]): err("Keyfile {} does not exist. Specify a keyfile with --key.".format(parsed.key[0])) +# Check that the requested ports are free to use +local_port = int(parsed.localport[0]) +web_port = int(parsed.webport[0]) +with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: + local_port_in_use = (s.connect_ex(('localhost', local_port)) == 0) +with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: + web_port_in_use = (s.connect_ex(('localhost', web_port)) == 0) + +if local_port_in_use: + print("Local port {} is in use by another user on this machine, or otherwise unavailable. " + "Specify a different port with --localport.".format(local_port)) +if web_port_in_use: + print("Web forward port {} is in use by another user on this machine, or otherwise unavailable. " + "Specify a different port with --webport.".format(web_port)) +if local_port_in_use or web_port_in_use: + exit(1) + # First get a port to use on the relay server if parsed.user is not None: ssh_cmd = ['ssh', '-oPasswordAuthentication=no', '-i', parsed.key[0], '-p', parsed.port[0], '-l', parsed.user[0], @@ -176,8 +194,8 @@ def err(s): ssh_cmd = "ssh -L {}:localhost:9001 -L {}:localhost:{} -o PasswordAuthentication=no -o ExitOnForwardFailure=yes " \ "-e none -i {} {} -p {} -tt {} {}"\ .format( - parsed.webport[0], - parsed.localport[0], + web_port, + local_port, ephemeral_port, parsed.key[0], ssh_user,