quick script to use to check whether or not a port is open using python standard library, good for when telnet is unavailable and it's too much trouble to install it
#!/usr/bin/env python | |
''' | |
quick script to use to check whether or not a port is open using python standard library, | |
good for when telnet is unavailable and it's too much trouble to install it | |
Usage: ./check_port.py 127.0.0.1 5601 | |
Thanks to mrjandro on SO | |
http://stackoverflow.com/questions/19196105/python-how-to-check-if-a-network-port-is-open-on-linux | |
sample output: | |
{"exit_code": 1, "results": "Port not open", "port": 5672, "host_ip": "['11.22.111.200']", "address": "internal-lb-1912362693.us-east-1.elb.amazonaws.com"} | |
{"exit_code": 0, "results": "Port open", "port": 443, "host_ip": "['11.22.111.200']", "address": "www.google.com"} | |
''' | |
import socket; | |
import sys | |
import json | |
ip = sys.argv[1] | |
prt = sys.argv[2] | |
hostips = [x for x in socket.gethostbyname_ex(socket.gethostname())[2] if not x.startswith("127.")][:1] | |
dresult = {'address': ip, 'port': 0, 'results': '', 'exit_code': 1, 'host_ips': hostips} | |
def dumpresult(d): | |
print(json.dumps(d)) | |
try: | |
int_prt = int(prt) | |
dresult['port'] = int_prt | |
except: | |
msg = ("Error processing port number, is it a number?") | |
dresult['results'] = msg | |
dumpresult(dresult) | |
sys.exit(1) | |
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | |
sock.settimeout(2) | |
result = sock.connect_ex((ip,int_prt)) | |
if result == 0: | |
msg = "Port open" | |
dresult['results'] = msg | |
dresult['exit_code'] = 0 | |
dumpresult(dresult) | |
sys.exit(0) | |
else: | |
msg = "Port not open" | |
dresult['results'] = msg | |
dresult['exit_code'] = 1 | |
dumpresult(dresult) | |
sys.exit(1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment