I recently needed to set up a connection test so that an outside vendor could verify that firewall rules had been set up correctly on both ends and that a connection which originated at a specific IP address on the vendor’s end was able to resolve a DNS address on our end and make a connection.
I remembered that Python has a simple way to set up a web server, so I decided to use this to create a script which creates a connection listener by setting up a web server on the desired port. For more details, please see below the jump.
Pre-requisites:
- Python 3
The script does the following:
- Creates a temporary directory
- Changes location into the temporary directory
- Creates an index.html file inside the temporary directory
- Starts Python 3’s web service using the content inside the temporary directory
Once running, you should be able to run connection tests against the port number defined in the script. In this example, port 8080 is being used.
Note: If you need to use a privileged port number between 0 – 1023, be aware that you will need to run this script with root privileges or by using authbind.
When the address being checked is connected to, you should see results similar to what’s shown below:
Note: In this case, localhost is being used as the address to check:
Curl connection test:
username@computername ~ % curl -v localhost:8080 | |
* Trying ::1… | |
* TCP_NODELAY set | |
* Connected to localhost (::1) port 8080 (#0) | |
> GET / HTTP/1.1 | |
> Host: localhost:8080 | |
> User-Agent: curl/7.64.1 | |
> Accept: */* | |
> | |
* HTTP 1.0, assume close after body | |
< HTTP/1.0 200 OK | |
< Server: SimpleHTTP/0.6 Python/3.8.2 | |
< Date: Tue, 14 Sep 2021 18:02:32 GMT | |
< Content-type: text/html | |
< Content-Length: 86 | |
< Last-Modified: Tue, 14 Sep 2021 18:01:59 GMT | |
< | |
<html> | |
<head> | |
<title>Hello World</title> | |
</head> | |
<body> | |
Hello World | |
</body> | |
</html> | |
* Closing connection 0 | |
username@computername ~ % |
Telnet connection test using curl:
username@computername ~ % curl -v telnet://localhost:8080 | |
* Trying ::1… | |
* TCP_NODELAY set | |
* Connected to localhost (::1) port 8080 (#0) | |
^C | |
username@computername ~ % |
As a web page is also being created by the script, you can also try connecting via a web browser. If successful, you should see a Hello World message as shown below.
The connection test script is available below:
#!/bin/bash | |
webdirectory=$(mktemp -d) | |
# Set port number for web service | |
port_number="8080" | |
# Create temporary directory and change directory | |
# into the temporary directory | |
cd "$webdirectory" | |
cat > "$webdirectory"/index.html << 'Index' | |
<html> | |
<head> | |
<title>Hello World</title> | |
</head> | |
<body> | |
Hello World | |
</body> | |
</html> | |
Index | |
# Run webservice | |
/usr/bin/python3 -m http.server "$port_number" |