脚本源文件为:
# cat tcp_checker.py #!/usr/bin/env python import socket import re import sys def check_server(address, port): # Create a TCP socket s = socket.socket() print "\033[33mAttempting to connect to %s on port %s\033[0m" % (address, port) try: s.connect((address, port)) print "\033[32mConnected to %s on port %s\033[0m" % (address, port) return True except socket.error, e: print "\033[31mConnection to %s on port %s failed: %s\033[0m" % (address, port, e) return False if __name__ == "__main__": from optparse import OptionParser parser = OptionParser() parser.add_option("-a", "--address", dest="address", default=‘localhost‘, help="ADDRESS for server, default is localhost", metavar="ADDRESS") parser.add_option("-p", "--port", dest="port", type="int", default=80, help="PORT for server, default is 80", metavar="PORT") (options,args) = parser.parse_args() print "options: %s, args: %s" % (options, args) check = check_server(options.address, options.port) print "check_server returned %s" % check sys.exit(not check)
运行结果为:
# python tcp_checker.py -a 192.168.56.108 -p 4000 options: {‘port‘: 4000, ‘address‘: ‘192.168.56.108‘}, args: [] Attempting to connect to 192.168.56.108 on port 4000 Connected to 192.168.56.108 on port 4000 check_server returned True
本文出自 “天道酬勤” 博客,请务必保留此出处http://lavenliu.blog.51cto.com/5060944/1690415
原文地址:http://lavenliu.blog.51cto.com/5060944/1690415