写这个的起因是系统测试需要对内网服务器做端口扫描。由于是远程操作,无法在内网交换机连接PC等终端跑nmap。而这台交换机本身内置了Python,因此考虑直接在交换机里跑脚本给服务器发SYN实现端口扫描功能。脚本内容如下:
# -*- coding: utf-8 -*-
# port_scan.py <host> <start_port>-<end_port>
import sys
from socket import *
host = sys.argv[1]
portstrs = sys.argv[2].split('-')
start_port = int(portstrs[0])
end_port = int(portstrs[1])
target_ip = gethostbyname(host)
opened_ports = []
for port in range(start_port, end_port):
str_info = 'Port %d...' % port
sock = socket(AF_INET, SOCK_STREAM)
sock.settimeout(10)
result = sock.connect_ex((target_ip, port))
if result == 0:
opened_ports.append(port)
str_info += 'OPEN'
print(str_info)
print("Opened ports:")
for i in opened_ports:
print(i)
(好吧我承认脚本大部分是从别人那儿抄来的……)