客户端疑难点及获取流程

1、linux客户端支持2就可以,python3就是很麻烦

难道你要求所有的客户端都上pytho3吗?

现在从bin的入口进去

HouseStark.ArgvHandler(sys.argv)

2、 core import HouseStark

from core import HouseStark

3、class InfoCollection(object):

def Linux(self):
sys_info = plugin_api.LinuxSysInfo() return sys_info

4、from plugins import plugin_api

5、磁盘是如何获取的

客户端代码如下:

#_*_coding:utf-8_*_

import os,sys,subprocess
import commands
import re def collect():
filter_keys = ['Manufacturer','Serial Number','Product Name','UUID','Wake-up Type']
raw_data = {}
''' asset无法自动判断,WINDOWS只能写死,收到数据写到字典,我们获取信息只能写死,收到数据写到字典,我们获取信息''' for key in filter_keys:
try:
#cmd_res = subprocess.check_output("sudo dmidecode -t system|grep '%s'" %key,shell=True)
cmd_res = commands.getoutput("sudo dmidecode -t system|grep '%s'" %key)
cmd_res = cmd_res.strip() res_to_list = cmd_res.split(':')
if len(res_to_list)> 1:#the second one is wanted string
raw_data[key] = res_to_list[1].strip()
else: raw_data[key] = -1
except Exception as e:
print(e)
raw_data[key] = -2 #means cmd went wrong
''' asset无法自动判断,WINDOWS只能写死,收到数据写到字典,我们获取信息只能写死,收到数据写到字典,我们获取信息'''
data = {"asset_type":'server'}
data['manufactory'] = raw_data['Manufacturer']
data['sn'] = raw_data['Serial Number']
data['model'] = raw_data['Product Name']
data['uuid'] = raw_data['UUID']
data['wake_up_type'] = raw_data['Wake-up Type']
''' 更信息信息 '''
data.update(cpuinfo())
data.update(osinfo())
data.update(raminfo())
data.update(nicinfo())
data.update(diskinfo())
return data def diskinfo():
obj = DiskPlugin()
return obj.linux() def nicinfo():
#tmp_f = file('/tmp/bonding_nic').read()
#raw_data= subprocess.check_output("ifconfig -a",shell=True)
raw_data = commands.getoutput("ifconfig -a") raw_data= raw_data.split("\n") nic_dic = {}
next_ip_line = False
last_mac_addr = None
for line in raw_data:
if next_ip_line:
#print last_mac_addr
#print line #, last_mac_addr.strip()
next_ip_line = False
nic_name = last_mac_addr.split()[0]
mac_addr = last_mac_addr.split("HWaddr")[1].strip()
raw_ip_addr = line.split("inet addr:")
raw_bcast = line.split("Bcast:")
raw_netmask = line.split("Mask:")
if len(raw_ip_addr) > 1: #has addr
ip_addr = raw_ip_addr[1].split()[0]
network = raw_bcast[1].split()[0]
netmask =raw_netmask[1].split()[0]
#print(ip_addr,network,netmask)
else:
ip_addr = None
network = None
netmask = None
if mac_addr not in nic_dic:
nic_dic[mac_addr] = {'name': nic_name,
'macaddress': mac_addr,
'netmask': netmask,
'network': network,
'bonding': 0,
'model': 'unknown',
'ipaddress': ip_addr,
}
else: #mac already exist , must be boding address
if '%s_bonding_addr' %(mac_addr) not in nic_dic:
random_mac_addr = '%s_bonding_addr' %(mac_addr)
else:
random_mac_addr = '%s_bonding_addr2' %(mac_addr) nic_dic[random_mac_addr] = {'name': nic_name,
'macaddress':random_mac_addr,
'netmask': netmask,
'network': network,
'bonding': 1,
'model': 'unknown',
'ipaddress': ip_addr,
} if "HWaddr" in line:
#print line
next_ip_line = True
last_mac_addr = line nic_list= []
for k,v in nic_dic.items():
nic_list.append(v) return {'nic':nic_list}
def raminfo():
#raw_data = subprocess.check_output(["sudo", "dmidecode" ,"-t", "17"])
raw_data = commands.getoutput("sudo dmidecode -t 17")
raw_list = raw_data.split("\n")
raw_ram_list = []
item_list = []
for line in raw_list: if line.startswith("Memory Device"):
raw_ram_list.append(item_list)
item_list =[]
else:
item_list.append(line.strip()) ram_list = []
for item in raw_ram_list:
item_ram_size = 0
ram_item_to_dic = {}
for i in item:
#print i
data = i.split(":")
if len(data) ==2:
key,v = data if key == 'Size':
#print key ,v
if v.strip() != "No Module Installed":
ram_item_to_dic['capacity'] = v.split()[0].strip() #e.g split "1024 MB"
item_ram_size = int(v.split()[0])
#print item_ram_size
else:
ram_item_to_dic['capacity'] = 0 if key == 'Type':
ram_item_to_dic['model'] = v.strip()
if key == 'Manufacturer':
ram_item_to_dic['manufactory'] = v.strip()
if key == 'Serial Number':
ram_item_to_dic['sn'] = v.strip()
if key == 'Asset Tag':
ram_item_to_dic['asset_tag'] = v.strip()
if key == 'Locator':
ram_item_to_dic['slot'] = v.strip() #if i.startswith("")
if item_ram_size == 0: # empty slot , need to report this
pass
else:
ram_list.append(ram_item_to_dic) #get total size(mb) of ram as well
#raw_total_size = subprocess.check_output(" cat /proc/meminfo|grep MemTotal ",shell=True).split(":")
raw_total_size = commands.getoutput("cat /proc/meminfo|grep MemTotal ").split(":")
ram_data = {'ram':ram_list}
if len(raw_total_size) == 2:#correct total_mb_size = int(raw_total_size[1].split()[0]) / 1024
ram_data['ram_size'] = total_mb_size
#print(ram_data) return ram_data
def osinfo():
#distributor = subprocess.check_output(" lsb_release -a|grep 'Distributor ID'",shell=True).split(":")
distributor = commands.getoutput(" lsb_release -a|grep 'Distributor ID'").split(":")
#release = subprocess.check_output(" lsb_release -a|grep Description",shell=True).split(":")
release = commands.getoutput(" lsb_release -a|grep Description").split(":")
data_dic ={
"os_distribution": distributor[1].strip() if len(distributor)>1 else None,
"os_release":release[1].strip() if len(release)>1 else None,
"os_type": "linux",
}
#print(data_dic)
return data_dic
def cpuinfo():
base_cmd = 'cat /proc/cpuinfo' raw_data = {
'cpu_model' : "%s |grep 'model name' |head -1 " % base_cmd,
'cpu_count' : "%s |grep 'processor'|wc -l " % base_cmd,
'cpu_core_count' : "%s |grep 'cpu cores' |awk -F: '{SUM +=$2} END {print SUM}'" % base_cmd,
} for k,cmd in raw_data.items():
try:
#cmd_res = subprocess.check_output(cmd,shell=True)
cmd_res = commands.getoutput(cmd)
raw_data[k] = cmd_res.strip() #except Exception,e:
except ValueError as e:
print(e) data = {
"cpu_count" : raw_data["cpu_count"],
"cpu_core_count": raw_data["cpu_core_count"]
}
cpu_model = raw_data["cpu_model"].split(":")
if len(cpu_model) >1:
data["cpu_model"] = cpu_model[1].strip()
else:
data["cpu_model"] = -1 return data class DiskPlugin(object): def linux(self):
result = {'physical_disk_driver':[]} try:
script_path = os.path.dirname(os.path.abspath(__file__))
shell_command = "sudo %s/MegaCli -PDList -aALL" % script_path
output = commands.getstatusoutput(shell_command)
result['physical_disk_driver'] = self.parse(output[1])
except Exception as e:
result['error'] = e
return result def parse(self,content):
'''
解析shell命令返回结果
:param content: shell 命令结果
:return:解析后的结果
'''
response = []
result = []
for row_line in content.split("\n\n\n\n"):
result.append(row_line)
for item in result:
temp_dict = {}
for row in item.split('\n'):
if not row.strip():
continue
if len(row.split(':')) != 2:
continue
key,value = row.split(':')
name =self.mega_patter_match(key);
if name:
if key == 'Raw Size':
raw_size = re.search('(\d+\.\d+)',value.strip())
if raw_size: temp_dict[name] = raw_size.group()
else:
raw_size = '0'
else:
temp_dict[name] = value.strip() if temp_dict:
response.append(temp_dict)
return response def mega_patter_match(self,needle):
grep_pattern = {'Slot':'slot', 'Raw Size':'capacity', 'Inquiry':'model', 'PD Type':'iface_type'}
for key,value in grep_pattern.items():
if needle.startswith(key):
return value
return False if __name__=="__main__":
print(DiskPlugin().linux())

  

CMDB资产管理系统开发【day26】:linux客户端开发的更多相关文章

  1. Python之CMDB资产管理系统

    最近正好在给公司做CMDB资产管理系统,现在做的也差不多了,现在回头吧思路整理下. CMDB介绍 CMDB --Configuration Management Database 配置管理数据库, C ...

  2. CMDB资产管理系统开发【day26】:数据正式存入待存区

    1.from表单提交 1.数据提交到哪里呢? 提交到assets/new_assets_approval.html这了 2.Yes, I'm sure提交了什么?          为什么没有下拉框了 ...

  3. CMDB资产管理系统开发【day26】:CMDB上节回顾

    一.上节知识点回顾 服务器设计了一个表结构 开发了一个客户端 二.后台创建缓存区表 客户端连接服务器,在服务器的下面看报错信息 因为URL都没有写,所以我找不到呀 1.在MadKing\url.py ...

  4. CMDB资产管理系统开发【day25】:表结构设计1

    资产表 # _*_coding:utf-8_*_ __author__ = 'jieli' from assets.myauth import UserProfile from django.db i ...

  5. C#.NET 大型通用信息化系统集成快速开发平台 4.0 版本 - 多系统开发接口 - 苹果客户端开发接口

    最近工作上需要,给苹果客户端开发接口,实现集中统一的用户管理,下面是接口调用参考. 1: 获取OpenId? http://127.0.0.1/GetOpenId.ashx?username=Admi ...

  6. CMDB资产管理系统开发【day25】:windows客户端开发

    1.目录结构 PS Y:\MadkingClient> tree /f 卷 netgame 的文件夹 PATH 列表 卷序列号为 ACE3-896E Y:. ├─bin │ NedStark.p ...

  7. CMDB资产管理系统开发【day26】:实现资产自动更新

    1.需求分析 1.比对分析 比对的时候以那个数据源为主? old [1,2,3 ] db数据库 new [2,3,4 ] 客户端汇报过来的 当然以客户端汇报过来的数据为主 2.更新分析 不同的表到底拿 ...

  8. CMDB资产管理系统开发【day26】:批准资产入库

    刚才都是一条像内存,硬盘,网卡.多条的话如何操作 只有一条数据 下面的是有多条数据的 硬盘必须字段的验证 def __create_disk_component(self): disk_info = ...

  9. CMDB资产管理系统开发【day26】:02-数据写入待存区

    一.资产自动回报数据及个更新流程图 二.表结构注释(NewAssetApprovalZone) class NewAssetApprovalZone(models.Model): "&quo ...

随机推荐

  1. 【原】Java学习笔记008 - 方法(函数)

    package cn.temptation; public class Sample01 { public static void main(String[] args) { // 方法/函数 Met ...

  2. c/c++ 多线程 利用条件变量实现线程安全的队列

    多线程 利用条件变量实现线程安全的队列 背景:标准STL库的队列queue是线程不安全的. 利用条件变量(Condition variable)简单实现一个线程安全的队列. 代码: #include ...

  3. 一天一个Linux命令--find

    文件查找:(以find为主)  which:查找命令字所在的位置  locate:模糊匹配(只要包含关键字的文件都查找出来)         不是实时的,基于数据库查找, updatedb升级loca ...

  4. 我超级推荐的Navicat Premium 12的下载,破解方法

    今天给大家推荐一款炒鸡好用的数据库管理工具,使用它,可以很方便的连接各种主流数据库软件----Navicat Premium 12 但是,它是要钱的,不过我们可以使用破解机来破解它,步骤稍有些复杂,简 ...

  5. web开发-Django博客系统

    项目界面图片预览 项目代码github地址 项目完整流程 项目流程: 1 搞清楚需求(产品经理) (1) 基于用户认证组件和Ajax实现登录验证(图片验证码) (2) 基于forms组件和Ajax实现 ...

  6. UVA - 10917 - Walk Through the Forest(最短路+记忆化搜索)

    Problem    UVA - 10917 - Walk Through the Forest Time Limit: 3000 mSec Problem Description Jimmy exp ...

  7. nginx上配置phpmyadmin

    Nginx配置phpmyadmin流程如下: 一.准备软件和环境(这里我以ubuntu16.04为例) 1.安装php7.1 sudo LC_ALL=C.UTF- add-apt-repository ...

  8. c++面经积累<2>

    4.类成员初始化方式:列表初始化和赋值初始化 赋值初始化通过在函数体内进行赋值,列表初始化,在构造函数后面加上冒号,使用初始化列表进行初始化.在函数体内进行初始化,是在所有的数据成员被分配内存空间后进 ...

  9. C语言的3种参数传递方式

    参数传递,是在程序运行过程中,实际参数就会将参数值传递给相应的形式参数,然后在函数中实现对数据处理和返回的过程,方法有3种方式 值传递 地址传递 引用传递 tips: 被调用函数的形参只有函数被调用时 ...

  10. input 各种限制

    test 1.限制只能输入或黏贴11位长度的数字 <input onkeyup="this.value=this.value.replace(/\D/g,'')" onaft ...