終於審覈經過了......第一次用博客,想記錄本身的學習狀況,分享知識。python
廢話很少說,第一篇blog,大牛請輕噴。app
資產清點首先須要進行主機探測,將存活主機統計下來再進行進一步的指紋識別及端口探測。若直接進行全網段IP掃描是很浪費時間的,不如先使用ICMP進行主機存活狀態的探測後,再針對的進行掃描。(基於ping的方式有可能有偏差,可是這裏主要考慮的是效率)學習
python的第三方nmap模塊的安裝,網上有相關教程,很少贅述。優化
因爲須要跟蹤累計PC存活總數,使用了類方法。但同時遇到的問題就是:使用多進程後會出現如下報錯信息:ui
cPickle.PicklingError: Can't pickle <type 'instancemethod'>: attribute lookup __builtin__.instancemethod failedspa
查了一下解決方法大概有三種:線程
dill
或pathos.multiprocesssing
:use pathos.multiprocesssing, instead of multiprocessing. pathos.multiprocessing is a fork of multiprocessing that uses dill. dill can serialize almost anything in python, so you are able to send a lot more around in parallel.這裏使用第一種方法進行修改,直接上代碼:excel
1 import nmap 2 from multiprocessing.pool import ThreadPool as Pool 3 import time 4 import csv 5 6 7 class Scan(object): 8 def __init__(self): 9 self.count = 0 10 11 def scan(self, ip): 12 csv_write =[] 13 nm = nmap.PortScanner() 14 nm.scan(hosts=ip, arguments='-n -sn -PE') 15 hosts_list = [(x, nm[x]['status']['state']) for x in nm.all_hosts()] 16 for host, status in hosts_list: 17 # print '{0}:{1}'.format(host, status) 18 csv_write.append([host, status]) 19 name = ip.split('/')[0] + '.csv' 20 # print name 21 with open(name, 'wb') as csvfile: 22 fieldnames = ['ip', 'status'] 23 w = csv.writer(csvfile, dialect='excel') 24 w.writerow(fieldnames) 25 w.writerows(csv_write) 26 print '[+]\"%s\" have saved, %d PC is up' % (name, len(hosts_list)) 27 self.count += len(hosts_list) 28 29 def get_ips(self, file): 30 ipList = [] 31 with open(file) as f: 32 for line in f.readlines(): 33 ipList.append(line.strip()) 34 return ipList 35 36 def run(self): 37 startTime = time.time() 38 print '[+]Scanning...' 39 ip_txt = 'C:\zichan.txt' 40 ipList = self.get_ips(ip_txt) 41 # print ipList 42 pool = Pool(5) 43 resultList = pool.map(self.scan, ipList) 44 pool.close() 45 pool.join() 46 endTime = time.time() 47 print '------------------------------------------------------' 48 print '[+]Scanning cost %ss, %d PC is up.' % (endTime - startTime, self.count) 49 print '[+]Done.' 50 51 if __name__ == '__main__': 52 myScan = Scan() 53 myScan.run()
比較簡單的方法實現,實際狀況下掃描7個內網B段大概不到一個半小時,講道理比直接使用nmap快不少(對比的nmap如今尚未跑完,嗯)code
保存格式爲CSV文件,控制檯輸出以下:orm
後面會嘗試優化,並添加新的功能如端口掃描、系統指紋、漏洞探測等,此次就這樣!水平有限,嘻嘻。