Python资产扫描分类

以下环境为python2.7,所需模块

pip install python-nmap
pip install pyyaml
pip install pysnmp
---------------------scanhosts.yaml---------------------
# -*- coding:utf-8 -*-
#####
#扫描主机配置信息
#Auth:ying
#####
hostinfo :
# 主机段,EXP:['192.168.6'] or ['192.168.1',192.168.2]
            net : ['192.168.1.1']
# 指定端口,可以多个
            ports : "22,"
# SSH key文件列表
            ssh_key_file : []
# 执行命令获取系统相关信息
            syscmd_list : ["cat /etc/issue",
                           "cat /etc/redhat-release",
                           "hostname",
                           "cat /sys/class/net/[^vtlsb]*/address",
#                           "cat /sys/class/net/[^vtlsb]*/address||esxcfg-vmknic -l|awk '{print $8}'|grep ':'",
                           "dmidecode -s system-serial-number",
                           "dmidecode -s system-manufacturer",
                           "dmidecode -s system-product-name",
                           "df -h |grep -w '/' |awk '{print $2}'",
                           "free | grep 'Mem:' | awk '{print substr(($2)/1000/1000,1,4)}' |sed 's/$/&G/g'",
                           "cat /proc/cpuinfo|grep 'processor'|wc -l|sed 's/$/&核/g'",
#                           "free | grep 'Mem:' | awk '{print $2,$4}' | awk '{print ($2/$1)*100}'",
#                           "w |grep 'load average:' | awk -F 'load average:' '{print $2}'",
                          ]
#####
# SSH登录密码列表
            ssh_user : ['登录主机的用户名列表']
            ssh_pass : ['登录主机的密码列表']
# 网络设备信息列表(以下是以华为交换机为例,其他类型交换机需要去官网找他的MIB值)
# 华为:https://support.huawei.com/enterprise/zh/doc/EDOC1100066226/7726b9dd
netinfo :
# 获取交换机主机名
           sysname_oid : ["1.3.6.1.2.1.1.5.0"]
# 获取交换机型号信息
           modle_oids : ["iso.3.6.1.2.1.47.1.1.1.1.2.201326593","iso.3.6.1.2.1.47.1.1.1.1.2.67108867"]
# 获取剩余内存
           mem_oids: ['iso.3.6.1.4.1.2011.5.25.31.1.1.1.1.7.67108873','iso.3.6.1.4.1.2011.5.25.31.1.1.1.1.7.603979777']
# 获取温度
           temp_oids : ['iso.3.6.1.4.1.2011.5.25.31.1.1.1.1.11.67108873','iso.3.6.1.4.1.2011.5.25.31.1.1.1.1.11.603979777']
# 获取cpu
           cpu_oids : ['iso.3.6.1.4.1.2011.5.25.31.1.1.1.1.5.67108873','iso.3.6.1.4.1.2011.5.25.31.1.1.1.1.5.603979777']

#团队名(用于SNMP认证)
           community : "public"
---------------------nmap_all_host.py---------------------
#!/usr/bin/env python
#coding:utf8
#++++++++++++description++++++++++++#
"""
@author:ying
@contact:1074020480@qq.com
@site: 
@software: PyCharm
@static_file: nmap_all_host.py
@time: 2019/5/14 上午7:52
"""
#+++++++++++++++++++++++++++++++++++#

import yaml,nmap,os,time,json,paramiko #导入相关模块
os.environ['DJANGO_SETTINGS_MODULE'] = 'YingOps.settings'
import django
django.setup()
from ScanHost import models
from pysnmp.entity.rfc3413.oneliner import cmdgen
PROJECT_ROOT = os.path.realpath(os.path.dirname(__file__))


"""加载配置文件"""
s_conf=yaml.load(open('scanhosts.yaml'))

'''服务器参数'''
net = s_conf['hostinfo']['nets'][0]
nets = s_conf['hostinfo']['nets'][0]+'.0/24'
ssh_pass = s_conf['hostinfo']['ssh_pass']
ssh_user = s_conf['hostinfo']['ssh_user']
syscmd_list = s_conf['hostinfo']['syscmd_list']
ports = s_conf['hostinfo']['ports']
ssh_key_file = s_conf['hostinfo']['ssh_key_file']

'''交换机参数'''
cpu_oids =s_conf['netinfo']['cpu_oids']
mem_oids =s_conf['netinfo']['mem_oids']
temp_oids =s_conf['netinfo']['temp_oids']
modle_oids =s_conf['netinfo']['modle_oids']
sysname_oid =s_conf['netinfo']['sysname_oid']
community = s_conf['netinfo']['community']

"""开始扫描"""
class ScanHostMethod(object):
    """初始化数据"""
    def __init__(self,nets):
        self.nets=nets

    """扫描出所有的ip"""
    def allHost(self):
        nm=nmap.PortScanner()
        nm.scan(self.nets,arguments='-n sP PE')
        all_host=nm.all_hosts()
        with open('all_host.txt','w') as f:
            f.write(json.dumps(all_host))
        # print('-'*20,all_host)
        return all_host

    """对扫描出来的所有IP进行分类"""
    def hostItems(self):
        unknow_list=[]
        linux_dic={}
        windows_dic={}
        nm = nmap.PortScanner()
        nm.scan(self.nets, arguments='-n sP PE')
        all_host = nm.all_hosts()
        for host in all_host:
            try:
                if nm[host]['tcp'][22]['state'] == 'open':
                    ports=nm[host]['tcp'].keys()
                    print('{0} is linux system...There are some ports opening --> {1}'.format(host,ports))
                    linux_dic[host]=ports
                else:
                    try:
                        if nm[host]['tcp'][3389]['state'] == 'open':
                            ports = nm[host]['tcp'].keys()
                            print('%s is windows system..... There are some ports opening --> %s' %(host,ports))
                            windows_dic[host] = ports
                        else:
                            unknow_list.append(host)
                    except KeyError:
                        unknow_list.append(host)
                        continue
            except KeyError:
                try:
                    if nm[host]['tcp'][3389]['state'] == 'open':
                        ports = nm[host]['tcp'].keys()
                        print('%s is windows system.....!!!!!!! There are some ports opening --> %s' %(host,ports))
                        windows_dic[host]=ports
                    else:
                        unknow_list.append(host)
                except KeyError:
                    unknow_list.append(host)
                    # print('--------> %s KeyError' %host)

        '''扫描出所有的ip,并返回linux,windows,unknown写入对应的文件内'''
        with open('all_host.txt','w') as f:
            f.write(json.dumps(all_host))
        with open('linux_host.txt','w') as f:
            f.write(json.dumps(linux_dic))
        with open('windows_host.txt','w') as f:
            f.write(json.dumps(windows_dic))
        with open('unknow_host.txt','w') as f:
            f.write(json.dumps(unknow_list))

        return all_host,linux_dic,windows_dic,unknow_list


class SwitchMethod(object):
    '''交换机 初始化参数'''
    def __init__(self,unknow_li,cpu_oids,mem_oids,temp_oids,modle_oids,sysname_oid,community):
        self.sw_li=unknow_li
        self.cpu_oids=cpu_oids
        self.mem_oids=mem_oids
        self.temp_oids=temp_oids
        self.modle_oids=modle_oids
        self.sysname_oid=sysname_oid
        self.community=community
    '''交换机总执行方法'''
    def swMethod(self,sw_ip,oids):
        try:
            '''这里使用到pysnmp模块,主要是通过snmp去扫描交换机的一些状态信息'''
            cg = cmdgen.CommandGenerator()
            errorIndication,errorStatus,errorIndex,varBinds = cg.getCmd(
                cmdgen.CommunityData('server',self.community,1),
                cmdgen.UdpTransportTarget((sw_ip,161)),
                oids
            )
            result = str(varBinds[0][1]) if varBinds[0][1] else ""
        except Exception as e:
            result = None
            print sw_ip + ' is not switch or snmp not enable!'
        except IndexError:
            result = None
            print sw_ip + ' is not switch or snmp not enable!'
        return result
    '''获取cpu使用率'''
    def cpuInfo(self,swip):
        for oid in self.cpu_oids:
            cpu_usage=self.swMethod(swip,oid)
            if cpu_usage:
                print '--------cpu_usage',cpu_usage
                return cpu_usage
            else:
                print '------++++++++++++--',cpu_usage
    '''获取mem使用率'''
    def memInfo(self,swip):
        for oid in self.mem_oids:
            mem_usage=self.swMethod(swip,oid)
            if mem_usage:
                return mem_usage
    '''获取交换机名称'''
    def sysnameInfo(self,swip):
        for oid in self.sysname_oid:
            sysname = self.swMethod(swip,oid)
            if sysname:
                return sysname
    '''获取交换机型号'''
    def modleInfo(self,swip):
        for oid in self.modle_oids:
            modle_usage=self.swMethod(swip,oid)
            if modle_usage:
                return modle_usage
    '''获取温度'''
    def tempInfo(self,swip):
        for oid in self.temp_oids:
            temp_usage=self.swMethod(swip,oid)
            if temp_usage:
                return temp_usage
    '''run'''
    def run(self):
        dic={}
        obj = models.SwitchInfo.objects.all()
        for swip in self.sw_li:
            ip=swip
            sysname = self.sysnameInfo(swip)
            if sysname:
                cpu = self.cpuInfo(swip)

                mem = self.memInfo(swip)
                temp = self.tempInfo(swip)
                sysname = self.sysnameInfo(swip)
                modle = self.modleInfo(swip)

                dic['cpu']=cpu
                dic['ip']=ip
                dic['mem']=mem
                dic['temp']=temp
                dic['sysname']=sysname
                dic['modle']=modle
                if cpu or mem or temp or  sysname or modle:
                    print '{0} switch ---> cpu:{1},mem:{2},temp:{3},sysname:{4},modle:{5}'.format(swip,cpu,mem,temp,sysname,modle)
                # print temp,mem,sysname
                    obj.create(**dic)

class LinuxMethod(object):
    def __init__(self, linux_dic, ssh_user, ssh_pass):
        self.linux_dic=linux_dic
        self.ssh_user=ssh_user
        self.ssh_pass=ssh_pass

    '''这里用到paramiko模块,通过上面扫描出来的ip,已经设置好的用户名密码,通过paramiko模块去登录服务器,并执行相关命令,返回你所需要的一些数据信息'''
    def try_ssh_login(self):
        ##因为这里用的是django框架,最后需要将所有扫描出来的信息写入数据库
        obj2 = models.LinuxInfo.objects.all()
        # # 创建SSH对象
        ssh = paramiko.SSHClient()
        # # 允许连接不在know_hosts文件中的主机
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        infos = {}
        for host in self.linux_dic.keys():
            for user in self.ssh_user:
                for pas in self.ssh_pass:
                    # # 连接服务器
                    info = []
                    try:
                        ssh.connect(hostname=host, port=22, username=user, password=pas)
                        info.append(user)
                        info.append(pas)
                        # # 执行命令
                        for cmd in syscmd_list:
                            # print cmd
                            stdin, stdout, stderr = ssh.exec_command(cmd)
                            # # 获取命令结果
                            result = stdout.read()
                            # print(result)
                            res=str((result).replace('//n','').replace('//l','').replace('/S','').replace('//','').strip().replace('Kernel r on an m',''))
                            info.append(res)
                        infos[host] = info
                        break
                    except paramiko.ssh_exception.AuthenticationException:
                        # pass
                        print host,user,pas,'用户名密码错误....'
                    except paramiko.ssh_exception.SSHException:
                        print host, user, pas, '用户名密码错误....'
                    except EOFError:
                        print 'EOFError'

                    # # # 关闭连接
        print('-------------------->>>>>>', infos)
        ssh.close()
        dicc={}
        for host_ip, j in infos.items():
            # print("ip地址:", i, '操作系统:', j[0], j[1], '主机名:', j[2], 'MAC地址:', j[3], 'SN序列号:', j[4], '制造商:', j[5], '型号:',
            #       j[6], '根磁盘使用率:', j[7], '内存使用率:', j[8], 'G', '负载:', j[9])
            print ("ip地址:",host_ip,'操作系统:',j[2],j[3],'主机名:',j[4],'MAC地址:',j[5],'SN序列号:',j[6].replace(' ',''),'制造商:',j[7].replace(' ',''),'型号:',j[8].replace(' ',''),'根磁盘使用率:',j[9],'内存使用率:',j[10],'G','负载:',j[11])
            # print(i,j)
            obj2.create(
                ip=host_ip,
                hostname=j[4],
                system_ver=j[2]+j[3],
                ssh_port=22,
                ssh_user=j[0],
                ssh_passwd=j[1],
                mac_address=j[5],
                sn=j[6],
                manufacturer=j[7],
                cpu_cores=j[11],
                mem_total=j[10],
                disk_total=j[9]
            )

class WindowsMethod(object):
    def __init__(self,windows_dic):
        self.windows_dic=windows_dic
    def windowsInfo(self):
        dic={}
        obj3=models.WindowsInfo.objects.all()
        for ip,port in self.windows_dic.items():
            print ip,port
            # dic[ip]=str(port)

            obj3.create(
                ip=ip,
                port=str(port),
            )

---------------------modles.py---------------------
#coding:utf8
from django.db import models

# Create your models here.
class LinuxInfo(models.Model):

    ip = models.CharField(max_length=64, null=True, verbose_name=u"主机IP信息", default="")
    hostname = models.CharField(max_length=256, null=True, verbose_name=u"操作系统主机名", default="")
    system_ver = models.CharField(max_length=256, null=True, verbose_name=u"操作系统版本", default="")
    ssh_port = models.CharField(max_length=32, null=True, verbose_name=u"ssh登录的端口", default="")
    ssh_user = models.CharField(max_length=32, null=True, verbose_name=u"ssh登录的用户", default="")
    ssh_passwd = models.CharField(max_length=64, null=True, verbose_name=u"ssh登录的用户", default="")
    mac_address = models.CharField(max_length=512, null=True,verbose_name=u"mac地址列表", default="")
    sn = models.CharField(max_length=256, null=True,verbose_name=u"SN-主机的唯一标示", default="")
    manufacturer = models.CharField(max_length=256, null=True,verbose_name=u"制造商", default="")
    cpu_cores = models.CharField(max_length=256, null=True,verbose_name=u"cpu核数", default="")
    # cpu_useage = models.CharField(max_length=256, null=True,verbose_name=u"cpu使用率", default="")
    mem_total = models.CharField(max_length=256, null=True,verbose_name=u"内存总大小", default="")
    disk_total = models.CharField(max_length=256, null=True,verbose_name=u"磁盘总大小", default="")

    class Meta:
        verbose_name = u'linux信息表'
        verbose_name_plural = verbose_name
        db_table = "linuxinfos"

class SwitchInfo(models.Model):

    ip = models.CharField(max_length=64, null=True, verbose_name=u"交换机IP信息", default="")
    modle = models.CharField(max_length=256, null=True, verbose_name=u"交换机型号", default="")
    sysname = models.CharField(max_length=256, null=True, verbose_name=u"交换机名称", default="")
    cpu = models.CharField(max_length=32, null=True, verbose_name=u"cpu使用率", default="")
    mem = models.CharField(max_length=32, null=True, verbose_name=u"内存使用率", default="")
    temp = models.CharField(max_length=64, null=True, verbose_name=u"当前温度", default="")


    class Meta:
        verbose_name = u'交换机信息表'
        verbose_name_plural = verbose_name
        db_table = "switchinfos"


class WindowsInfo(models.Model):

    ip = models.CharField(max_length=64, null=True, verbose_name=u"主机IP信息", default="")
    port = models.CharField(max_length=32, null=True, verbose_name=u"开放的端口", default="")

    class Meta:
        verbose_name = u'windows信息表'
        verbose_name_plural = verbose_name
        db_table = "windowsinfos"

给TA打赏
共{{data.count}}人
人已打赏
开发

1.算法引入

2023-9-11 18:08:15

开发

Python第二天 文件类型变量

2023-9-11 18:21:02

0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索