使用前提
需要先安装nmap程序
windows 安装
centos7 安装
ubuntu 安装
tcp端口判断脚本 --可以用中间件程序进行验证
import subprocess
import re
def is_tcp_port_open(target_host, port):
"""
判断目标主机指定TCP端口是否被占用。
参数:
target_host (str): 目标主机IP地址或域名。
port (int): 待检查的TCP端口号。
返回:
bool: 如果端口被占用,返回True;否则返回False。
"""
# 构造nmap命令
nmap_cmd = f'nmap -p {port} {target_host}'
# 执行nmap命令并获取输出
output = subprocess.check_output(nmap_cmd, shell=True, text=True)
# 使用正则表达式匹配开放端口行
open_port_pattern = r'open'.format(re.escape(target_host))
match = re.search(open_port_pattern, output)
return match is not None
# 使用示例
target = '192.168.10.85'
port = 5000
is_open = is_tcp_port_open(target, port)
if is_open:
print(f"端口 {port} 在主机 {target} 上处于开放状态.")
else:
print(f"端口 {port} 在主机 {target} 上未被占用或不可达.")
udp端口判断脚本 --可以用回传服务和调度服务进行验证
import subprocess
import re
def is_tcp_port_open(target_host, port):
"""
判断目标主机指定TCP端口是否被占用。
参数:
target_host (str): 目标主机IP地址或域名。
port (int): 待检查的TCP端口号。
返回:
bool: 如果端口被占用,返回True;否则返回False。
"""
# 构造nmap命令
nmap_cmd = f'nmap -sU -p {port} {target_host}'
# 执行nmap命令并获取输出
output = subprocess.check_output(nmap_cmd, shell=True, text=True)
# 使用正则表达式匹配开放端口行
open_port_pattern = r'open'.format(re.escape(target_host))
match = re.search(open_port_pattern, output)
return match is not None
# 使用示例
target = '192.168.10.85'
port = 8550
is_open = is_tcp_port_open(target, port)
if is_open:
print(f"端口 {port} 在主机 {target} 上处于开放状态.")
else:
print(f"端口 {port} 在主机 {target} 上未被占用或不可达.")