作為一個運(yùn)維人員,內(nèi)部有大量的主機(jī)肚医,如何發(fā)現(xiàn)哪些主機(jī)是存活的仓手,最好的工具還是nmap,但是nmap輸出的數(shù)據(jù)太多,如何過濾自己需要的數(shù)據(jù)业踢。本來主要介紹利用Python腳本 過濾nmap 輸出結(jié)果栗柒,存入csv文件中。
0x00 nmap 掃描命令
- 參考資料
(1)nmap中文手冊
(2)NMAP 輸出XML文件詳解
- nmap ping探測掃描知举,以xml格式輸出結(jié)果
nmap -sP -ox nping.xml 192.168.2.0/24
ping 模式掃描192.168.2.0/24 網(wǎng)段瞬沦,并以xml格式輸出結(jié)果,輸出結(jié)果文件為nping.xml
nmap -sP -iL test.txt -oX ceshi.xml XML輸出
ping 模式掃描test.txt 文件中的地址雇锡,并以xml格式輸出結(jié)果逛钻,輸出結(jié)果文件為nping.xml
0x01 Python代碼解析xml文件,存入csv文件
此腳本未寫異常處理锰提,如需要處理請自行編寫
#coding:utf-8
import csv
from xml.etree import ElementTree as et
# version Python 2.7.14 (v2.7.14:84471935ed, Sep 16 2017, 20:25:58) [MSC v.1500 64 bit (AMD64)] on win32
def Get_ip(f_xml): #清洗xml數(shù)據(jù)
file_xml=f_xml #XML文件名
sum=[] #返回結(jié)果列表變量
data=open(file_xml).read()
root=et.fromstring(data)
t1= root.findall("host")
for t2 in t1:
#s2=[] # s2[0] save hosts ip address, s2[1] save hosts status
s2={"ip":"null","status":"null"} #存放主機(jī)IP地址和狀態(tài)
for t3 in t2:
if(t3.tag=="status"):
#s2.append(t3.attrib["state"]) # Get hosts status
s2["status"]=t3.attrib["state"] #存放主機(jī)狀態(tài)
elif(t3.tag=="address"):
if(t3.attrib["addrtype"]=="ipv4"):
#s2.append(t3.attrib["addr"])
s2["ip"]=t3.attrib["addr"] #存放主機(jī)IP地址
#sum.append(s2[::-1]) # Get hosts IP address,s2[::-1]:Reverse s2
sum.append(s2) #將字典s2存入列表sum變量中
return sum
def Write_csv(f_csv,datas): #寫入csv文件中
file_csv=f_csv #csv文件名
datas=datas #需要寫入文件的數(shù)據(jù)
headers=["ip","status"]
f=open(file_csv,"wb")
writer = csv.DictWriter(f,fieldnames=headers)
writer.writerows(datas)
f.close()
if __name__ == '__main__':
file_xml="nping.xml" #需要清洗的xml文件
file_csv="test.csv" #需要保存到的csv文件
s1=Get_ip(file_xml)
Write_csv(file_csv,s1)
0x02 格式化數(shù)據(jù)
- Get_ip方法曙痘,清洗后格式
[{'status': 'up', 'ip': '192.168.2.1'}, {'status': 'up', 'ip': '192.168.2.2'}]
-
Write_csv方法,存入csv格式為
圖片.png
0x03 其他方法實現(xiàn)
其實Python 有一個python-nmap包可以直接調(diào)用nmap欲账,可以參考
https://thief.one/2017/05/02/1/
https://pypi.org/project/python-nmap/
https://xael.org/pages/python-nmap-en.html