Python脚本探测TCP/UDP端口是否连通
TCP
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
探测TCP端口是否连通
python tcp_test.py <host> <port>
支持系统默认自带的python2.6运行.
"""
import socket
import sys
def test_tcp_port(host, port):
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(2)
s.connect((host, port))
s.close()
return True
except:
return False
if len(sys.argv) != 3:
print("Usage: python tcp_test.py <host> <port>")
sys.exit(1)
host = sys.argv[1]
port = int(sys.argv[2])
if test_tcp_port(host, port):
print("TCP port %d on %s is open." % (port, host))
else:
print("TCP port %d on %s is closed." % (port, host))
UDP
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
探测UDP端口是否连通
python tcp_test.py <host> <port>
支持系统默认自带的python2.6运行.
"""
import socket
import sys
def test_udp_port(host, port):
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.settimeout(2)
s.connect((host, port))
data, addr = s.recvfrom(1024)
s.close()
return True
except:
return False
if len(sys.argv) != 3:
print("Usage: python udp_test.py <host> <port>")
sys.exit(1)
host = sys.argv[1]
port = int(sys.argv[2])
if test_udp_port(host, port):
print("UDP port %d on %s is open." % (port, host))
else:
print("UDP port %d on %s is closed." % (port, host))
示例:
[chenyh@kjchukoumq2gzcus ~]$ python udp_test.py 10.201.201.34 12201
UDP port 12201 on 10.201.201.34 is closed.
[chenyh@kjchukoumq2gzcus ~]$ python tcp_test.py 10.196.68.154 8443
TCP port 8443 on 10.196.68.154 is open.
代码参考
1.https://mp.weixin.qq.com/s/pUPOZtrzzkZ6g3PHd5F1KQ