masscan快速扫开放端口+nmap扫描鉴别服务(单IP)

零、debian/ubuntu环境安装:

apt update && apt-get install clang git gcc make libpcap-dev nmap -y && cd /root/ && git clone https://github.com/robertdavidgraham/masscan && cd masscan && make && ln -s /root/masscan/bin/masscan /bin/masscan && masscan

一、基础信息:
1.masscan快速扫描,rate不敢设置太大,免得漏掉端口

masscan 1.2.3.4 -p 1-65535 --rate 5000 --open-only

2.nmap扫描具体端口

nmap -T4 -Pn -sV -n 1.2.3.4 -p 21,80,1433,...

二、用python3搞个脚本自动实现上面过程,bash脚本不会。。。

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os,re,sys

def exec_return(command):
    with os.popen(command) as r:
        text = r.read()
    #print(text)
    return text

def nmap_scan(ip, ports):
    commands = 'nmap -T4 -Pn -sV -n '+ ip + ' -p ' + ports
    print('[*] %s' % commands)
    with os.popen(commands) as r:
        res = r.read()
    print(res)
    return res

def write_log(logstring, logfile):
  try:
    with open(logfile, 'a') as f:
      f.write(logstring)
  except Exception as e:
    print('[-] write log error:', e)

def main():
  ip = ''
  if len(sys.argv) != 2:
    exit('[-] xxxx.py ip')
  else:
    ip = sys.argv[1]
  print('[*] masscaning %s ...' % ip)
  mascmd = 'masscan '+ ip +' -p 1-65535 --rate 5000 --open-only'
  print('[*] %s' % mascmd)
  res = exec_return(mascmd)
  ports = re.findall('port (.*?)/tcp on', res, re.S)
  if len(ports) == 0:
    exit('[-] not found open port...')
  port_nmap_format = ','.join(ports)
  print('[+] open ports: %s ' % port_nmap_format)
  print('[*] nmap scaning port service...')
  res = nmap_scan(ip, port_nmap_format)
  if res:
    write_log(res, ip+'_ports.txt')

if __name__ == '__main__':
  main()

参考信息:
Bash实现快速端口识别与服务监控
记录我的masscan安装、研究、测试之旅