听完这集后复现的脚本,增加了以前学到的的模块,巩固了python内容

【快速入门python安全开发】 https://www.bilibili.com/video/BV1jBD9Y5Euv/?p=6&share_source=copy_web&vd_source=1f5a7bcfe439d21ac9c4e6aca396949f

使用的模块

获得绝对路径

1
2
3
4
def gain_path(filename):
"""把文件名转成相对于脚本所在目录的绝对路径"""
path_dir = os.path.dirname(os.path.abspath(__file__))
return os.path.join(path_dir, filename)

先获取dirname其abspath,再os.path.join拼接返回

timer闭包计时器

1
2
3
4
5
6
7
8
def timer(func):
def wrapper(*args, **kwargs):
start_time = time.time()
result=func(*args, **kwargs)
end_time = time.time()
print(f"{func.__name__}函数执行时间:{end_time - start_time}秒")
return result
return wrapper

func=timer(func)

从这里复习了一下闭包,装饰器。本质上是对函数是对象这一概念的理解

读取文件内容

1
2
3
4
def from_txt(file):
filepath=gain_path(file)
with open(filepath, 'r') as f:
return [i.strip() for i in f.readlines() if i.strip()]

用路径的功能

return用了列表推导式,以后可以多去用用,代替for+更新列表

清洗ip

1
2
3
4
5
6
7
8
9
def ip_clean(ips):
cleaned_ips=[]
for i in ips:
match = re.search(r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}', i)
if not match:
continue
else:
cleaned_ips.append(match.group())
return list(dict.fromkeys(cleaned_ips))

用了正则表达式,return用了字典fromkes来去重,记得转回列表

扫描主体

1
2
3
4
def scan(ip):#没搞清楚scan和main的任务分配
scaner=nmap3.Nmap()
result=scaner.scan_top_ports(ip,default=100,args='-Pn -sV')
return ip,result

主要是调用了nmap3库,使用这些参数开扫

返回的是字典,不用json.loads()

导出结果至excel

1
2
3
4
5
6
7
8
9
def to_excel(ip,result,ws):
scaned_ip=ip
ip_datas = result[scaned_ip].get('ports',[])
for ip_data in ip_datas:
protocol_data = ip_data.get('protocol','')
port_data = ip_data.get('portid','')
state_data = ip_data.get('state','')
service_data = ip_data.get('service', {}).get('name', '')
ws.append([scaned_ip,protocol_data,port_data,state_data,service_data])

用了openpyxl库进行操作

先用.get()读取字典中想要的键值,for+ws.append()保存至表中,而表是在main里创建的

main函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
def main():
try:
wb=openpyxl.Workbook()
ws=wb.active
ws.append(['IP', '协议', '端口号', '状态', '服务'])
filename=input("请输入ip文件名:").strip()
ips=from_txt(filename)
okips=ip_clean(ips)
for ip in okips:
scaned_result=scan(ip)
status=to_excel(scaned_result[0],scaned_result[1],ws)
wb.save(gain_path('scan_result.xlsx'))
print("扫描完成!,结果已存储至scan_result.xlsx")
except Exception as e:
print(f"发生错误:{e}")

创表,获得当前表,创建五个栏

依次执行几个模块,重点是用for,一个个往里送ip,记得return元组需要用下标访问

还需要try except进行错误搜寻报告

完整版代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import nmap3
import json
import time
import openpyxl
import os
import re

def gain_path(filename):
"""把文件名转成相对于脚本所在目录的绝对路径"""
path_dir = os.path.dirname(os.path.abspath(__file__))
return os.path.join(path_dir, filename)

def timer(func):
def wrapper(*args, **kwargs):
start_time = time.time()
result=func(*args, **kwargs)
end_time = time.time()
print(f"{func.__name__}函数执行时间:{end_time - start_time}秒")
return result
return wrapper

@timer
def from_txt(file):
filepath=gain_path(file)
with open(filepath, 'r') as f:
return [i.strip() for i in f.readlines() if i.strip()]

def ip_clean(ips):
cleaned_ips=[]
for i in ips:
match = re.search(r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}', i)
if not match:
continue
else:
cleaned_ips.append(match.group())
return list(dict.fromkeys(cleaned_ips))


@timer
def scan(ip):#没搞清楚scan和main的任务分配
scaner=nmap3.Nmap()
result=scaner.scan_top_ports(ip,default=100,args='-Pn -sV')
return ip,result
@timer
def to_excel(ip,result,ws):
scaned_ip=ip
ip_datas = result[scaned_ip].get('ports',[])
for ip_data in ip_datas:
protocol_data = ip_data.get('protocol','')
port_data = ip_data.get('portid','')
state_data = ip_data.get('state','')
service_data = ip_data.get('service', {}).get('name', '')
ws.append([scaned_ip,protocol_data,port_data,state_data,service_data])


def main():
try:
wb=openpyxl.Workbook()
ws=wb.active
ws.append(['IP', '协议', '端口号', '状态', '服务'])
filename=input("请输入ip文件名:").strip()
ips=from_txt(filename)
okips=ip_clean(ips)
for ip in okips:
scaned_result=scan(ip)
status=to_excel(scaned_result[0],scaned_result[1],ws)
wb.save(gain_path('scan_result.xlsx'))
print("扫描完成!,结果已存储至scan_result.xlsx")
except Exception as e:
print(f"发生错误:{e}")


if __name__ == '__main__':
main()

站内搜索

没有找到内容!