Use Python to write a script that counts LAN shutdowns and generate Excel tables (sample code)

Source: Internet
Author: User
Tags local time
This article describes a script that uses Python to write a statistical LAN that is not shut down and generates an Excel table (sample code)

#!/udict/bin/env python#-*-coding:utf_8-*-#Date: 2016/10/17#author:wangpeng#blog:http:// Wangpengtai.blog.51cto.comimport subprocessimport nmapimport time,datetimeimport xlrd,xlsxwriter,xlwtimport OS, Sysfrom xlutils.copy Import copyfrom multiprocessing import pooldef ip_scan (IP): global nm p = subprocess. Popen ("ping-c 1-t 1" +ip,stdin = subprocess. PIPE, stdout = subprocess. PIPE, stderr = subprocess.  PIPE, Shell = True) output = P.stdout.read () #print output #the local time Dtime = Time.strftime ("%y/%m/%d %x ", Time.localtime ()) nm = Nmap.            Portscanner () If "100% packet loss" not in Output:nm.scan (ip,arguments= '-o-ss-su-f ') Try: Dict = {' status ': ' Up ', ' IP ': IP, ' OS ': str (nm[ip][' osmatch '][0][' name ') ', ' Mac ': str (nm[ip][' Vendor '].keys () [0]), ' Hostname ': str (nm[ip][' hostnames '][0][' name '), ' Datetime ':d time} #print dict #addResult (dict,filename           , table) #print ' ip:%s,dict:%s '% (ip,dict) except: Try:dict = {' status ': ' Up ', ' IP ': IP, ' OS ': str (nm[ip][' osmatch '][0][' name ') ', ' Mac ': ', ' Hostname ': str (nm[ip][') Hostnames '][0][' name ']), ' Datetime ':d time} except:dict = {' status ': ' Up ', ' IP ': IP, ' OS ': ', ' Mac ': St            R (nm[ip][' addresses ' [' mac ']), ' Hostname ': str (nm[ip][' hostnames '][0][' name ']), ' Datetime ':d time} print IP         #print "# # #error!####" #print dict #pass addresult (dict,filename,table) Else: print ' ip:%s--->down! '%ip dict = {' status ': ' Down ', ' IP ': IP, ' OS ': ', ' Mac ': ', ' Hostname ': ', ' Datetime ':d ti Me} addresult (dict,filename,table) def count_rows (filename): data = xlrd.open_workbook (filename) table = data. Sheets () [0] nrows = table.nrows return nrows#create a Excel table Def addresult (dict,filename,table): #pic K up the key from Dict and make it title to excel title = Dict.keys () #sort the key title.sort () Clo_num = Len (Dict.keys ()) Styleboldred = xlwt.easyxf (' Font:color-index red, Bold on ') HeaderStyle = styleboldred if not os.path.exists (filename): WB = XLWT.             Workbook () ws = Wb.add_sheet (' count ') for I in Range (Clo_num): Ws.write (0,i,title[i],headerstyle) Ws.write (1,i,dict[title[i]]) wb.save (table) ELSE:OLDWB = Xlrd.open_workbook (table,f Ormatting_info = True) NEWWB = Copy (OLDWB) NEWWS = newwb.get_sheet (0) num = count_rows (filen AME) for I in Range (Clo_num): Newws.write (Num,i,dict[title[i]]) Newwb.save (  Table) def start (): Global filename Global Table t_date = Datetime.date.today (). Strftime ("%y_%m_%d") t_name        = ' Report_%s.xls '% (t_date) filename = R '/home/python/%s '% (t_name) ip_list = [] for I in range (1,255): Ip_list.append (' 172.20.113. ') +str (i)) #print ip_list print ("Please wait ...") #计算时间 time_start=time.time () #创建线程    For IP in ip_list: # pid = Os.fork () # If not Pid:ip_scan (IP) #sys. exit () Time_end=time.time () t=time_end-time_start print ' * ' *48 print ' \ntime: ' +str (t) + ' s ' print ' Scan results has been saved to test.\    n ' print ' * ' *48 if __name__ = = ' __main__ ': "" "filename = R '/home/wangpeng/python/test1.xls ' Table = ' Test1.xls ' ip_list = [' 172.20.113.57 ', ' 172.20.113.47 ', ' 172.20.113.10 '] for IP in Ip_list:ip_scan ( IP) "" "Start ()

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.