您好,登录后才能下订单哦!
这期内容当中小编将会给大家带来有关利用Python怎么对tcp端口进行检测,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。
具体如下:
# coding=utf-8 import sys import socket import re def check_server(address, port): s = socket.socket() print 'Attempting to connect to %s on port %s' % (address, port) try: s.connect((address, port)) print 'Connected to %s on port %s' % (address, port) return True except socket.error as e: print 'Connection to %s on port %s failed: %s' % (address, port, e) return False if __name__ == '__main__': from argparse import ArgumentParser parser = ArgumentParser(description=u'TCP端口检测') parser.add_argument( '-a', '--address', dest='address', default='localhost', help='address for the server') parser.add_argument( '-p', '--port', dest="port", default=80, type=int, help='port for the server') args = parser.parse_args() check = check_server(args.address, args.port) print 'check_server returned %s' % check sys.exit(not check)
测试结果:
[hupeng@hupeng-vm Python]$python check_server.py && echo "SUCCESS"
Attempting to connect to localhost on port 80
Connected to localhost on port 80
check_server returned True
SUCCESS
[hupeng@hupeng-vm Python]$python check_server.py -p 81 && echo "Failure"
Attempting to connect to localhost on port 81
Connection to localhost on port 81 failed: [Errno 111] Connection refused
check_server returned False
[hupeng@hupeng-vm Python]$python check_server.py -p 81 || echo "Failure"
Attempting to connect to localhost on port 81
Connection to localhost on port 81 failed: [Errno 111] Connection refused
check_server returned False
Failure
上述就是小编为大家分享的利用Python怎么对tcp端口进行检测了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注亿速云行业资讯频道。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。