终于审核通过了......第一次用博客,想记录自己的学习情况,分享知识。
废话不多说,第一篇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文件,控制台输出如下:
后面会尝试优化,并添加新的功能如端口扫描、系统指纹、漏洞探测等,这次就这样!水平有限,嘻嘻。