使用python编写一个统计局域网未关机的脚本,并生成excel表格

#!/udict/bin/env python
# -*- coding: utf_8 -*-
#Date:2016/10/17
#Author:wangpeng
#blog:http://wangpengtai.blog.51cto.com
import subprocess
import nmap
import time,datetime
import xlrd,xlsxwriter,xlwt
import os,sys
from xlutils.copy import copy
from multiprocessing import Pool
def 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‘:dtime}
            #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‘:dtime}
            except:
                dict = {‘status‘:‘up‘,‘IP‘:ip,‘OS‘:‘‘,‘Mac‘:str(nm[ip][‘addresses‘][‘mac‘]),‘Hostname‘:str(nm[ip][‘hostnames‘][0][‘name‘]),‘Datetime‘:dtime}
                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‘:dtime}
        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):
    #pick 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,formatting_info = True)
        newWb = copy(oldWb)
        newWs = newWb.get_sheet(0)
        
        num = count_rows(filename)
        
        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 have 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()
时间: 2024-08-24 12:14:23

使用python编写一个统计局域网未关机的脚本,并生成excel表格的相关文章

用python编写一个仿路由器命令的交互式脚本

刚开始学习python,感觉器功能的强大.因为开始是学网络的因此对路由器交换机的命令行配置比较熟悉,因此简单写了个仿h3c的交互脚本.因为是初学,其中只涉及到简单的while循环和if条件判断.可以作为一个交互程序的思路框架. #!/usr/bin/env python __author__ = 'Administrator' print('\n'+'view-sys',"\n") while True:     usr_view=input("<Router>&

使用Python编写一个渗透测试探测器

本篇将会涉及: 资源探测 一个有用的字典资源 第一个暴力探测器 资源探测 资源探测在渗透测试中还是属于资源的映射和信息的收集阶段. 主要有以下三个类型: 字典攻击 暴力破解 模糊测试 字典攻击,在破解密码或密钥的时候,通过自定义的字典文件,有针对性地尝试字典文件内所有的字典组合. 暴力破解,也叫做穷举法,按照特定的组合,进行枚举所有的组合.简单来说就是将密码进行逐个推算直到找出真正的密码为止. 模糊测试,指通过向目标系统提供非预期性的输入并监视其发生的异常结果来发现目标系统的漏洞. 资源探测的作

用python编写一个高效搜索代码工具

用python编写一个高效搜索代码工具大多码农在linux环境下使用grep+关键词的命令搜索自己想要的代码或者log文件.今天介绍用python如何编写一个更强大的搜索工具,windows下也适用.我们的需求:1, 可以同时指定多个关键词.比如某个文件某一行中有"error: aa bb cc",如果检索关键词error和cc则可以显示该行,避免单一关键词冗余信息太多2, 可以排除某些关键词.对于"error: aa bb cc" ,如果设定排除bb,则不予显示该

python脚本之制作excel表格

#!/usr/bin/python#coding=utf-8 #导入模块import xlsxwriter #新建一个表文件workbook = xlsxwriter.Workbook('sample.xlsx')#新建一个表worksheet = workbook.add_worksheet()#新建一个图表对象chart = workbook.add_chart({'type':'column'}) #定义表头 #定义数据title = [u'业务名称',u'星期一',u'星期二',u'星期

如何用Python编写一个聊天室

一.课程介绍 1.简介 本次项目课是实现简单聊天室程序的服务器端和客户端. 2.知识点 服务器端涉及到asyncore.asynchat和socket这几个模块,客户端用到了telnetlib.wx.time和thread这几个模块. 3.所需环境 本次课中编写客户端需要用到wxPython,它是一个GUI工具包,请先使用下面的命令安装: $ sudo apt-get install python-wxtools 密码为shiyanlou 4.项目效果截图 登录窗口 聊天窗口 5.源代码下载 g

python编写文件统计脚本

思路:用os模块中的一些函数(os.listdir().os.path.isdir().os.path.join().os.path.abspath()等) 实现功能:显示多级目录,以及自己要找的具体文件类型(例:以".py"结尾的文件),并读取每个文件的第一行(一般为注释说明,这样就能大致了解这个文件是干事什么的) 先编写二级目录文件统计脚本 代码如下: #文件统计 os.chdir("F:\\pythonstudy") for fp in os.listdir(

使用python编写一个登录接口

需求: 编写登录接口 输入用户名密码 认证成功后 显示欢迎信息 输入三次后锁定 用户信息文件 黑名单的文件 黑名单里检查,不让登录 用户名密码判定 流程图: 代码: #!/usr/bin/env python tries = 0 lockfile = open('account_lock.txt','r+',encoding='UTF-8') tolockfile = open('account_lock.txt','a',encoding='UTF-8') userfile = open('a

Python编写一个Python脚本

我想要一个可以为我的所有重要文件创建备份的程序.(下面测试环境为python2.7) 1.backup_ver1.py #!/usr/bin/python import os import time # 1. The files and directories to be backed up are specified in a list. source = ['/home/esun'] # If you are using Windows, use source = [r'C:\Documen

Python编写一个简单计算器

一个计算器最主要的功能是加减乘除,那么用 Python 可以怎样实现呢 #!/usr/bin/env python # -*- coding:utf-8 -*- # @Time : 2018/1/22 22:29 # @Author : zhouyuyao # @File : daemonCalculator.py # PyCharm 2017.3.2 (Community Edition) # Build #PC-173.4127.16, built on December 19, 2017