基于python的端口扫描_Python实现端口扫描

该博客展示了基于Python的端口扫描代码。通过调用nmap工具,先检测存活IP,再对存活IP进行端口扫描,最后处理扫描结果并将其以JSON格式发送到指定URL。代码包含文件删除、存活IP检测、扫描结果处理等功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#!/usr/bin/env python

# -*- coding: utf-8 -*-

"""

Date:2018-05-14

Author:Bob

Description:Processing nmap scan results

"""

import os

import time

import json

import requests

import subprocess

from xml.etree import ElementTree as ET

url = 'http://10.200.56.80:8000/portscan/portScanInterface/'

def remove_file(del_file):

if os.path.exists(del_file):

os.remove(del_file)

return del_file

def alive_ip():

# Detecting live ip

with open('ip_subnet.txt', 'r') as f:

for ip in f:

ip = ip.strip()

cmd = '/usr/bin/nmap -sP -PI -PT %s >> alive_ip.txt' %ip

p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True)

print p.stdout.read(),

# Scan live ip

ips = []

with open('alive_ip.txt', 'r') as f:

for lines in f:

if lines.startswith('Nmap scan'):

ip = lines.split(' ')

ip = ip[4].strip()

ips.append(ip)

ip_str = ' '.join(ips)

nmap_scan = 'nmap -sV -oX nmap_scan_output.xml %s > /dev/null 2>&1' %ip_str

p = subprocess.Popen(nmap_scan, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True)

print p.stdout.read(),

def deal_scan_xml(xml_file):

# Processing nmap scan results

bd = open(xml_file, 'r').read()

root = ET.fromstring(bd)

data = []

for host in root.findall('host'):

# Print the number of child elements in the host tag

# print len(host),

# Get ip address

ip_ = host[1].get('addr')

# Get ports, protocols, and other information

if len(host) == 5:

for port in host[3][0:]:

# print port

port_ = str(port.get('portid'))

protocol_ = str(port.get('protocol'))

if port[0].tag == 'extrareasons':

continue

state_ = port[0].get('state')

service_ = str(port[1].get('name'))

product_ = str(port[1].get('product'))

version_ = str(port[1].get('version'))

extrainfo_ = str(port[1].get('extrainfo'))

ip_ = ip_

data.append({"ip": ip_, "port": port_, "protocol": protocol_, "state": state_, "service": service_,

"product": product_, "version": version_, "extrainfo": extrainfo_})

json_data = json.dumps({"detail": data})

json_data = requests.post(url, {"detail": json_data})

print json_data.text

def main():

remove_file('alive_ip.txt')

remove_file('nmap_scan_output.xml')

alive_ip()

deal_scan_xml('nmap_scan_output.xml')

if __name__ == '__main__':

main()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值