cmdb python 采集虚拟机_CMDB学习之八,完成所有资产采集信息的收集
#!/usr/bin/env python#-*- coding:utf-8 -*-
importos,refrom .base importBasePluginfrom lib.response importBaseResponseimporttracebackfrom lib.log importloggerclassNetwork(BasePlugin):defwin(self,handler,hostname):'''执行命令拿到结果-网卡
:return:'''
print("执行win方法")
ret= handler.cmd('ipconfig',hostname)[0:10]returnret#def linux(self,handler,hostname):
#'''
#执行命令拿到结果-网卡
#:return:
#'''
#print("执行Linux方法")
#ret = handler.cmd('ifconfig',hostname)[0:10]
#return ret
deflinux(self, handler, hostname):
reponse=BaseResponse()try:ifself.debug:
output= open(os.path.join(self.base_dir, 'files', 'nic.out'), 'r').read()
interfaces_info=self._interfaces_ip(output)else:
interfaces_info=self.linux_interfaces(handler)
self.standard(interfaces_info)
reponse.data=interfaces_info#reponse.data = self.standard(interfaces_info)
#print(reponse.data)
exceptException as e:
error_msg=traceback.format_exc()
reponse.status=False
reponse.error=error_msg#记录错误日志
logger.error(error_msg)returnreponse.dictdeflinux_interfaces(self, handler):'''Obtain interface information for *NIX/BSD variants'''ifaces=dict()
ip_path= 'ip'
ifip_path:
cmd1= handler.cmd('sudo {0} link show'.format(ip_path))
cmd2= handler.cmd('sudo {0} addr show'.format(ip_path))
ifaces= self._interfaces_ip(cmd1 + '\n' +cmd2)returnifacesdefwhich(self, exe):def_is_executable_file_or_link(exe):#check for os.X_OK doesn't suffice because directory may executable
return (os.access(exe, os.X_OK) and(os.path.isfile(exe)oros.path.islink(exe)))ifexe:if_is_executable_file_or_link(exe):#executable in cwd or fullpath
returnexe#default path based on busybox's default
default_path = '/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin'search_path= os.environ.get('PATH', default_path)
path_ext= os.environ.get('PATHEXT', '.EXE')
ext_list= path_ext.split(';')
search_path=search_path.split(os.pathsep)ifTrue:#Add any dirs in the default_path which are not in search_path. If
#there was no PATH variable found in os.environ, then this will be
#a no-op. This ensures that all dirs in the default_path are
#searched, which lets salt.utils.which() work well when invoked by
#salt-call running from cron (which, depending on platform, may
#have a severely limited PATH).
search_path.extend(
[
xfor x indefault_path.split(os.pathsep)if x not insearch_path
]
)for path insearch_path:
full_path=os.path.join(path, exe)if_is_executable_file_or_link(full_path):returnfull_pathreturnNonedef _number_of_set_bits_to_ipv4_netmask(self, set_bits): #pylint: disable=C0103
'''Returns an IPv4 netmask from the integer representation of that mask.
Ex. 0xffffff00 -> '255.255.255.0''''
returnself.cidr_to_ipv4_netmask(self._number_of_set_bits(set_bits))defcidr_to_ipv4_netmask(self, cidr_bits):'''Returns an IPv4 netmask'''
try:
cidr_bits=int(cidr_bits)if not 1 <= cidr_bits <= 32:return ''
exceptValueError:return ''netmask= ''
for idx in range(4):ifidx:
netmask+= '.'
if cidr_bits >= 8:
netmask+= '255'cidr_bits-= 8
else:
netmask+= '{0:d}'.format(256 - (2 ** (8 -cidr_bits)))
cidr_bits=0returnnetmaskdef_number_of_set_bits(self, x):'''Returns the number of bits that are set in a 32bit int'''
#Taken from http://stackoverflow.com/a/4912729. Many thanks!
x -= (x >> 1) & 0x55555555x= ((x >> 2) & 0x33333333) + (x & 0x33333333)
x= ((x >> 4) + x) & 0x0f0f0f0fx+= x >> 8x+= x >> 16
return x & 0x0000003f
def_interfaces_ip(self, out):'''Uses ip to return a dictionary of interfaces with various information about
each (up/down state, ip address, netmask, and hwaddr)'''ret=dict()
right_keys= ['name', 'hwaddr', 'up', 'netmask', 'ipaddrs']defparse_network(value, cols):'''Return a tuple of ip, netmask, broadcast
based on the current set of cols'''brd=Noneif '/' in value: #we have a CIDR in this address
ip, cidr = value.split('/') #pylint: disable=C0103
else:
ip= value #pylint: disable=C0103
cidr = 32
if type_ == 'inet':
mask=self.cidr_to_ipv4_netmask(int(cidr))if 'brd' incols:
brd= cols[cols.index('brd') + 1]return(ip, mask, brd)
groups= re.compile('\r?\n\\d').split(out)for group ingroups:
iface=None
data=dict()for line ingroup.splitlines():if ' ' not inline:continuematch= re.match(r'^\d*:\s+([\w.\-]+)(?:@)?([\w.\-]+)?:\s+', line)ifmatch:
iface, parent, attrs=match.groups()if 'UP' in attrs.split(','):
data['up'] =Trueelse:
data['up'] =Falseif parent and parent inright_keys:
data[parent]=parentcontinuecols=line.split()if len(cols) >= 2:
type_, value= tuple(cols[0:2])
iflabel= cols[-1:][0]if type_ in ('inet',):if 'secondary' not incols:
ipaddr, netmask, broadcast=parse_network(value, cols)if type_ == 'inet':if 'inet' not indata:
data['inet'] =list()
addr_obj=dict()
addr_obj['address'] =ipaddr
addr_obj['netmask'] =netmask
addr_obj['broadcast'] =broadcast
data['inet'].append(addr_obj)else:if 'secondary' not indata:
data['secondary'] =list()
ip_, mask, brd=parse_network(value, cols)
data['secondary'].append({'type': type_,'address': ip_,'netmask': mask,'broadcast': brd,
})delip_, mask, brdelif type_.startswith('link'):
data['hwaddr'] =valueififace:if iface.startswith('pan') or iface.startswith('lo') or iface.startswith('v'):deliface, dataelse:
ret[iface]=datadeliface, datareturnretdefstandard(self, interfaces_info):for key, value ininterfaces_info.items():
ipaddrs=set()
netmask=set()if not 'inet' invalue:
value['ipaddrs'] = ''value['netmask'] = ''
else:for item in value['inet']:
ipaddrs.add(item['address'])
netmask.add(item['netmask'])
value['ipaddrs'] = '/'.join(ipaddrs)
value['netmask'] = '/'.join(netmask)del value['inet']
cmdb python 采集虚拟机_CMDB学习之八,完成所有资产采集信息的收集相关推荐
- 采集虚拟机_系列文章:Kubernetes日志采集最佳实践
前言 上一期主要介绍Kubernetes日志输出的一些注意事项,日志输出最终的目的还是做统一的采集和分析.在Kubernetes中,日志采集和普通虚拟机的方式有很大不同,相对实现难度和部署代价也略大, ...
- Python 初学者的最佳学习资源
Python 社区在分享学习资源和帮助初学者掌握语言方面总是很积极的.但也就是因为资源过多,导致人们很难知道如何找到. 本文整理了最好.最通用的 Python 资源,并且简述了其内容.[伯乐在线注:译 ...
- 【Python基础】GitHub 星标 8.8w+,Python 小白 100 天学习计划,从新手到大师!
本篇给大家介绍一个Python骨灰级别的学习项目. 2019年10月份的时候,一个<Python-100-days>的GitHub项目火了,霸榜GitHub热榜.此项目截止目前已经8.8万 ...
- Python Web框架Django学习(二)
python web框架Django学习(二) 目录: 三.Django创建APP 四.创建登录页面,实现用户交互,后台管理用户(非数据库方式) ========================= ...
- Python paromiko每日生活学习感悟(第一次写,紧张hahaha)
Python paromiko每日生活学习感悟(第一次写,紧张hahaha) 学习篇 生活篇 学习篇 今天整天实习,解决了虚拟机通过SSH进行远程登录,需求还增加一项就是要采用多个接入多个设备,采用了 ...
- java虚拟机预先加载哪些类_Java虚拟机JVM学习02 类的加载概述
Java虚拟机JVM学习02 类的加载概述 类的加载 类的加载指的是将类的.class文件中的二进制数据读入到内存中,将其放在运行时数据区的方法区内,然后在堆区创建一个java.lang.Class对 ...
- python cookbook 豆瓣_学习python求推荐一波书籍?
豆瓣最受好评的20本Python书 No.1 Fluent Python(豆瓣评分:9.6)Many programmers who learn Python basics fall into the ...
- Python实现的深度学习技术在水文水质领域应用
当前,深度学习作为人工智能的热门技术发展迅速,以其强大的非线性和不确定性处理能力在图像识别.语音识别.自然语言处理等领域取得了显著的成效.它是一种端到端的处理方法,在训练算法的指导下,深层神经网络自发 ...
- 为什么说Python是最值得学习的编程语言
不知道从什么时候开始,这句话开始流行.不过也从侧面反映出 Python 语言的特点:简单.高效. 如果你对python感兴趣,我这有个学习Python基地,里面有很多学习资料,感兴趣的+Q群:6882 ...
最新文章
- 【ASP.NET北大青鸟】-总结(二)
- 【洛谷 P1896】[SCOI2005]互不侵犯(状压dp)
- kaggle中zillow比赛中模型融合的方法及其代码
- Controller中请求数据的方式
- c 语言 00字符串 截断,c语言截断字符串
- WinPE作为启动硬盘
- Go语言栈定义及相关方法实现
- LoadRunner踩坑记录:服务器“127.0.0.1”在尝试协商 SSL 会话时关闭连接
- LINUX 添加xp虚拟机
- 深入理解JavaScript系列
- 视频时代的下一幕 ABC Inspire:读懂视频
- 【JAVASCRIPT】-【AES加密解密】01、前端AES加密解密的方式
- 计算机2级都有哪些,计算机二级考试内容有哪些
- 简单上手理解Dav框架
- android qmui教程,QMUI-Android
- 2021全球十大外盘期货交易平台排名
- Android蓝牙开发——经典蓝牙的连接
- OpenJudge1758 二叉树
- 深入理解递归:美丽的科赫雪花
- 图的存储结构(邻接矩阵和邻接表)