終於審核通過了......第一次用博客,想記錄自己的學習情況,分享知識。
廢話不多說,第一篇blog,大牛請輕噴。
資產清點首先需要進行主機探測,將存活主機統計下來再進行進一步的指紋識別及端口探測。若直接進行全網段IP掃描是很浪費時間的,不如先使用ICMP進行主機存活狀態的探測后,再針對的進行掃描。(基於ping的方式有可能有誤差,但是這里主要考慮的是效率)
python的第三方nmap模塊的安裝,網上有相關教程,不多贅述。
由於需要跟蹤累計PC存活總數,使用了類方法。但同時遇到的問題就是:使用多進程后會出現以下報錯信息:
cPickle.PicklingError: Can't pickle <type 'instancemethod'>: attribute lookup __builtin__.instancemethod failed
查了一下解決方法大概有三種:
- 用線程替換進程
- 可以使用copy_reg來規避上面的異常.
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.
這里使用第一種方法進行修改,直接上代碼:
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現在還沒有跑完,嗯)
保存格式為CSV文件,控制台輸出如下:
后面會嘗試優化,並添加新的功能如端口掃描、系統指紋、漏洞探測等,這次就這樣!水平有限,嘻嘻。