Last active
October 22, 2016 19:07
-
-
Save montj2/a2c25f066b1fc929107cdc8f2b7814e6 to your computer and use it in GitHub Desktop.
Python TCP port check
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
import socket # socket module | |
import sys # exit method(s) | |
def check_server(address, port): | |
# Create TCP Socket | |
s = socket.socket() | |
print "Attempting to connect to {0} on port {1}.".format(address, port) | |
try: | |
s.connect((address, port)) | |
print "Connected to {0} on port {1}.".format(address, port) | |
return True | |
except socket.error, e: | |
print "Connection to {0} on port {1} failed: {2}".format(address, port, e) | |
return False | |
if __name__ == '__main__': | |
from optparse import OptionParser # Maximum compatibility 2.6.x, deprecated 2.7+ | |
parser = OptionParser() | |
parser.add_option("-a", "--address", dest="address", default='localhost', help="Address of server", metavar="ADDRESS") | |
parser.add_option("-p", "--port", dest="port", default="80", type="int", help="Port to test", metavar="PORT") | |
(options, args) = parser.parse_args() | |
check = check_server(options.address, options.port) | |
sys.exit(not check) # Standard return 0 requires inversion of True/False values |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment