1.安装python3.6.6

# 安装依赖,一定要安装,否则后面可能无法安装一些python插件
yum -y install zlib-devel bzip2-devel openssl-devel ncurses-devel sqlite-devel readline-devel tk-devel gdbm-devel db4-devel libpcap-devel xz-devel
mkdir /usr/local/python36
tar -zxf Python-3.6.6.tgz
cd Python-3.6.6
./configure --prefix=/usr/local/python36
make && make install
ln -s /usr/local/python36/bin/python3 /usr/bin/python3
ln -s /usr/local/python36/bin/pip3 /usr/bin/pip3 # pip3 install --upgrade pip
# yum install -y git # 安装监控vmware的sdk pyvmomi
[root@wondershareID_web03:/usr/local/python36]# git clone https://github.com/vmware/pyvmomi.git
[root@wondershareID_web03:/usr/local/python36]# cd pyvmomi/
[root@wondershareID_web03:/usr/local/python36/pyvmomi]# ls
docs LICENSE.txt MANIFEST.in NOTICE.txt pyVim pyVmomi README.rst requirements.txt sample setup.cfg setup.py test-requirements.txt tests tox.ini
[root@wondershareID_web03:/usr/local/python36/pyvmomi]# python3 setup.py install 3.编写通过pyvmomi插件获取虚拟机信息的脚本 #!/opt/python3/bin/python3
#coding:utf-8 """
获取所有的vcenter相关信息
包括exsi的硬件资源信息和vmware客户端的硬件分配信息
"""
from pyVmomi import vim
from pyVim.connect import SmartConnect, Disconnect, SmartConnectNoSSL
import atexit
import argparse def get_args():
parser = argparse.ArgumentParser(
description='Arguments for talking to vCenter') parser.add_argument('-s', '--host',
required=True,
action='store',
help='vSpehre service to connect to') parser.add_argument('-o', '--port',
type=int,
default=443,
action='store',
help='Port to connect on') parser.add_argument('-u', '--user',
required=True,
action='store',
help='User name to use') parser.add_argument('-p', '--password',
required=True,
action='store',
help='Password to use') args = parser.parse_args()
return args def get_obj(content, vimtype, name=None):
'''
列表返回,name 可以指定匹配的对象
'''
container = content.viewManager.CreateContainerView(content.rootFolder, vimtype, True)
obj = [ view for view in container.view]
return obj def main():
esxi_host = {}
args = get_args()
# connect this thing
si = SmartConnectNoSSL(
host=args.host,
user=args.user,
pwd=args.password,
port=args.port)
# disconnect this thing
atexit.register(Disconnect, si)
content = si.RetrieveContent()
esxi_obj = get_obj(content, [vim.HostSystem])
for esxi in esxi_obj:
esxi_host[esxi.name] = {'esxi_info':{},'datastore':{}, 'network': {}, 'vm': {}} esxi_host[esxi.name]['esxi_info']['厂商'] = esxi.summary.hardware.vendor
esxi_host[esxi.name]['esxi_info']['型号'] = esxi.summary.hardware.model
for i in esxi.summary.hardware.otherIdentifyingInfo:
if isinstance(i, vim.host.SystemIdentificationInfo):
esxi_host[esxi.name]['esxi_info']['SN'] = i.identifierValue
esxi_host[esxi.name]['esxi_info']['处理器'] = '数量:%s 核数:%s 线程数:%s 频率:%s(%s) ' % (esxi.summary.hardware.numCpuPkgs,
esxi.summary.hardware.numCpuCores,
esxi.summary.hardware.numCpuThreads,
esxi.summary.hardware.cpuMhz,
esxi.summary.hardware.cpuModel)
esxi_host[esxi.name]['esxi_info']['处理器使用率'] = '%.1f%%' % (esxi.summary.quickStats.overallCpuUsage /
(esxi.summary.hardware.numCpuPkgs * esxi.summary.hardware.numCpuCores * esxi.summary.hardware.cpuMhz) * 100)
esxi_host[esxi.name]['esxi_info']['内存(MB)'] = esxi.summary.hardware.memorySize/1024/1024
esxi_host[esxi.name]['esxi_info']['可用内存(MB)'] = '%.1f MB' % ((esxi.summary.hardware.memorySize/1024/1024) - esxi.summary.quickStats.overallMemoryUsage)
esxi_host[esxi.name]['esxi_info']['内存使用率'] = '%.1f%%' % ((esxi.summary.quickStats.overallMemoryUsage / (esxi.summary.hardware.memorySize/1024/1024)) * 100)
esxi_host[esxi.name]['esxi_info']['系统'] = esxi.summary.config.product.fullName for ds in esxi.datastore:
esxi_host[esxi.name]['datastore'][ds.name] = {}
esxi_host[esxi.name]['datastore'][ds.name]['总容量(G)'] = int((ds.summary.capacity)/1024/1024/1024)
esxi_host[esxi.name]['datastore'][ds.name]['空闲容量(G)'] = int((ds.summary.freeSpace)/1024/1024/1024)
esxi_host[esxi.name]['datastore'][ds.name]['类型'] = (ds.summary.type)
for nt in esxi.network:
esxi_host[esxi.name]['network'][nt.name] = {}
esxi_host[esxi.name]['network'][nt.name]['标签ID'] = nt.name
for vm in esxi.vm:
esxi_host[esxi.name]['vm'][vm.name] = {}
esxi_host[esxi.name]['vm'][vm.name]['电源状态'] = vm.runtime.powerState
esxi_host[esxi.name]['vm'][vm.name]['CPU(内核总数)'] = vm.config.hardware.numCPU
esxi_host[esxi.name]['vm'][vm.name]['内存(总数MB)'] = vm.config.hardware.memoryMB
esxi_host[esxi.name]['vm'][vm.name]['系统信息'] = vm.config.guestFullName
if vm.guest.ipAddress:
esxi_host[esxi.name]['vm'][vm.name]['IP'] = vm.guest.ipAddress
else:
esxi_host[esxi.name]['vm'][vm.name]['IP'] = '服务器需要开机后才可以获取' for d in vm.config.hardware.device:
if isinstance(d, vim.vm.device.VirtualDisk):
esxi_host[esxi.name]['vm'][vm.name][d.deviceInfo.label] = str((d.capacityInKB)/1024/1024) + ' GB' f = open(args.host + '.txt', 'w')
for host in esxi_host:
print('ESXI IP:', host)
f.write('ESXI IP: %s \n' % host)
for hd in esxi_host[host]['esxi_info']:
print(' %s: %s' % (hd, esxi_host[host]['esxi_info'][hd]))
f.write(' %s: %s' % (hd, esxi_host[host]['esxi_info'][hd]))
for ds in esxi_host[host]['datastore']:
print(' 存储名称:', ds)
f.write(' 存储名称: %s \n' % ds)
for k in esxi_host[host]['datastore'][ds]:
print(' %s: %s' % (k, esxi_host[host]['datastore'][ds][k]))
f.write(' %s: %s \n' % (k, esxi_host[host]['datastore'][ds][k]))
for nt in esxi_host[host]['network']:
print(' 网络名称:', nt)
f.write(' 网络名称:%s \n' % nt)
for k in esxi_host[host]['network'][nt]:
print(' %s: %s' % (k, esxi_host[host]['network'][nt][k]))
f.write(' %s: %s \n' % (k, esxi_host[host]['network'][nt][k]))
for vmachine in esxi_host[host]['vm']:
print(' 虚拟机名称:', vmachine)
f.write(' 虚拟机名称:%s \n' % vmachine)
for k in esxi_host[host]['vm'][vmachine]:
print(' %s: %s' % (k, esxi_host[host]['vm'][vmachine][k]))
f.write(' %s: %s \n' % (k, esxi_host[host]['vm'][vmachine][k]))
f.close() if __name__ == '__main__':
main() # 脚本使用方法:
python3 aa.py -s 192.168.254.69 -o 443 -u zabbixmonitor -p zabbixmonitor >> aa.txt # 结果 ESXI IP: 192.168.254.73
厂商: Dell Inc. 型号: PowerEdge R730 处理器: 数量:2 核数:24 线程数:48 频率:2200(Intel(R) Xeon(R) CPU E5-2650 v4 @ 2.20GHz) 处理器使用率: 0.8% 内存(MB): 130978.28125 可用内存(MB): 18003.3 MB 内存使用率: 86.3% 系统: VMware ESXi 6.5.0 build-5969303 存储名称: Localdatastore1_73
总容量(G): 5017
空闲容量(G): 2382
类型: VMFS
网络名称:Prod_63.159.217.X
标签ID: Prod_63.159.217.X
网络名称:VM Network_192.168.254.X
标签ID: VM Network_192.168.254.X
虚拟机名称:platform_slave_db2
电源状态: poweredOn
CPU(内核总数): 12
内存(总数MB): 20480
系统信息: CentOS 6 (64-bit)
IP: 服务器需要开机后才可以获取
Hard disk 1: 50.0 GB
Hard disk 2: 700.0 GB
虚拟机名称:cbs_web04_new
电源状态: poweredOn
CPU(内核总数): 12
内存(总数MB): 12288
系统信息: CentOS 4/5 or later (64-bit)
IP: 服务器需要开机后才可以获取
Hard disk 1: 1000.0 GB
虚拟机名称:rabbitmq_01
电源状态: poweredOn
CPU(内核总数): 4
内存(总数MB): 8192
系统信息: CentOS 6 (64-bit)
IP: 服务器需要开机后才可以获取
Hard disk 1: 50.0 GB
虚拟机名称:dlcbs02
电源状态: poweredOn
CPU(内核总数): 4
内存(总数MB): 8192
系统信息: CentOS 6 (64-bit)
IP: 服务器需要开机后才可以获取
Hard disk 1: 50.0 GB
Hard disk 2: 400.0 GB
虚拟机名称:web_redis02
电源状态: poweredOn
CPU(内核总数): 8
内存(总数MB): 22528
系统信息: CentOS 6 (64-bit)
IP: 服务器需要开机后才可以获取
Hard disk 1: 50.0 GB
... 监控磁盘的脚本: #!/usr/bin/python3
#coding:utf-8
#Author: ziming """
只用于模拟开发功能测试
"""
from pyVmomi import vim
from pyVim.connect import SmartConnect, Disconnect, SmartConnectNoSSL
import sys
import atexit
import argparse
from optparse import OptionParser
import json class Exsi(object): # 获取vcenter的相关参数
def __init__(self, host = '192.168.254.69', port=443, user = 'zabbixmonitor', password='zabbixmonitor'):
self._host = host
self._port = port
self._user = user
self._password = password def get_obj(self,content, vimtype, name=None):
'''
列表返回,name 可以指定匹配的对象
'''
container = content.viewManager.CreateContainerView(content.rootFolder, vimtype, True)
obj = [ view for view in container.view]
return obj def get_conn(self):
# 连接vcenter
si = SmartConnectNoSSL(
host=self._host,
user=self._user,
pwd=self._password,
port=self._port)
# disconnect this thing
atexit.register(Disconnect, si)
content = si.RetrieveContent()
return content # 获取exsi的信息ip,磁盘使用情况等
def get_esxi_host(self):
esxi_host = {}
content = self.get_conn()
esxi_obj = self.get_obj(content, [vim.HostSystem])
for esxi in esxi_obj:
esxi_host[esxi.name] = {'datastore':{}} # for ds in esxi.datastore:
# esxi_host[esxi.name]['datastore'][ds.name] = {}
# esxi_host[esxi.name]['datastore'][ds.name]['总容量(G)'] = int((ds.summary.capacity)/1024/1024/1024)
# esxi_host[esxi.name]['datastore'][ds.name]['空闲容量(G)'] = int((ds.summary.freeSpace)/1024/1024/1024)
# esxi_host[esxi.name]['datastore'][ds.name]['类型'] = (ds.summary.type) total_capacity = 0
free_capacity = 0
for ds in esxi.datastore:
# esxi_host[esxi.name]['datastore'][ds.name] = {}
esxi_host[esxi.name] = {}
total_capacity += int((ds.summary.capacity)/1024/1024/1024)
free_capacity += int((ds.summary.freeSpace)/1024/1024/1024) esxi_host[esxi.name]['sotrage_used_percent'] = 100*(total_capacity - free_capacity)/total_capacity
# print(esxi_host)
return esxi_host # 获取exsi的host即ip列表
def get_esxi_iplist(self):
esxi_host = self.get_esxi_host()
data = list()
for exsi_ip in esxi_host:
data.append({"{#EXSI_IP}": exsi_ip}) return json.dumps({'data': data}, sort_keys=True, indent=7, separators=(",",":")) # 获取指定esxi的磁盘信息
def get_esxi_storageinfo(self, exsi_ip):
esxi_host = self.get_esxi_host() return esxi_host[exsi_ip]['sotrage_used_percent'] def main():
try: usage = "usage: %prog [options]\ngGet exsi Stat"
parser = OptionParser(usage) # 接收参数
parser.add_option("-l", "--list",
action="store_true", dest="is_list", default=False, help="if list all exsi ip") parser.add_option("--ip", "--ipaddr",
action="store", dest="ipaddr", type="string",
default="192.168.254.56", help="execute 'exsi info' to see more infomation") (options, args) = parser.parse_args()
if 1 >= len(sys.argv):
parser.print_help()
return #exsi_ins = Exsi(options.ipaddr)
exsi_ins = Exsi()
if options.is_list == True:
print(exsi_ins.get_esxi_iplist())
return # print(redis.ins.get_esxi_storageinfo(optins.ip, exsi_ip = ip))
print(exsi_ins.get_esxi_storageinfo(options.ipaddr)) except Exception as expt:
import traceback
tb = traceback.format_exc()
print(tb) if __name__ == '__main__':
main()

python结合pyvmomi 监控esxi的磁盘等信息的更多相关文章

  1. python获取esxi的磁盘使用率信息

    #!/usr/bin/python3 #coding:utf-8 #Author: ziming """ 只用于模拟开发功能测试 """ f ...

  2. zabbix使用自动发现监控esxi的磁盘存储storage

    zabbix使用自动发现监控esxi的磁盘存储storage 在任意一台可以访问vcenter的zabbix-agent服务器上添加exsi的磁盘监控模板即可 创建模板过程: custom.esxi. ...

  3. python简单的监控脚本-利用socket、psutil阻止远程主机运行特定程序

    python简单的监控脚本-利用socket.psutil阻止远程主机运行特定程序 psutil是一个跨平台的库(http://code.google.com/p/psutil/),能够轻松的实现获取 ...

  4. 通过SSIS监控远程服务器磁盘空间并发送邮件报警!

    由于之前ESB是供应商部署的,且部署在C盘(C盘空间很小,还添加了很多ESB的windows服务日志在C盘,很容易把C盘空间占满,导致ESB服务运行宕机,几乎每隔几周发生一次事故,需要人工干预处理,不 ...

  5. zabbix 使用问题两个--中文乱码,以及监控ESXi下的虚拟机

    1. 中文乱码 最开始中文显现 长方形不显示文字.解决办法: c:\windows\fonts 下面复制 楷体的字体(字体随意看自己喜欢) 文件名一般为: simkai.ttf 2.将simkai.t ...

  6. ESXI虚拟机磁盘管理(精简-厚置-精简)

    VMwareESX/ESXi 精简置备(thin)与厚置备(thick)虚拟机磁盘之间转换 VMwareESX/ESXi 虚拟机磁盘thin与thick之间转换 注意:转换前请先关闭虚拟机!!! 一. ...

  7. 利用shell监控cpu、磁盘、内存使用率

    利用shell监控cpu.磁盘.内存使用率,达到警报阈值发邮件进行通知 并配合任务计划,即可及时获取报警信息 #!/bin/bash ################################# ...

  8. ESXI5.5开启snmp+zabbix 监控esxi 需要开启的服务

    esxcli system snmp set --communities public esxcli system snmp set --enable trueesxcli network firew ...

  9. linux监控平台搭建-磁盘

    linux监控平台搭建-磁盘 磁盘:随着大数据快速发展.人工智能.自动化.云平台.数据量指数的增长.磁盘的使用量也在增长.目前的机器基本上采用SSD或者SATA盘,一直有人比较那个好.会不会使用时间短 ...

随机推荐

  1. redis安全问题【原】

    前提 假设redis安装在 IP 地址为 192.168.0.123 的linux服务器 . 我的本机Win10操作系统 IP地址为 192.168.0.45 , 有一套java客户端代码可调用lin ...

  2. minio golang client使用

    初始化 var ( endpoint = "127.0.0.1:8888" accessKeyID = "YXU5IXETKKPX171K4Z6O" secre ...

  3. 【c++】编译器为我们实现了几个类成员函数?

    #include <cassert> #include <complex> #include <iostream> class Empty{}; Empty e; ...

  4. Hibernate主键生成策略及选择

    1 .increment:适用于short,int,long作为主键,不是使用数据库自动增长机制 这是hibernate中提供的一种增长机制 在程序运行时,先进行查询:select max(id) f ...

  5. 图像分类中max-pooling和average-pooling之间的异同

    池化操作时在卷积神经网络中经常采用过的一个基本操作,一般在卷积层后面都会接一个池化操作,但是近些年比较主流的ImageNet上的分类算法模型都是使用的max-pooling,很少使用average-p ...

  6. JS/javaScript 获取div内容

    jquery: 例如<div id="abc"><a>内容</a></div>$("#abc").html(); ...

  7. [C++]PAT乙级1003. 我要通过!(17/20)

    /* 1003. 我要通过!(20) “答案正确”是自动判题系统给出的最令人欢喜的回复.本题属于PAT的“答案正确”大派送 —— 只要读入的字符串满足下列条件,系统就输出“答案正确”,否则输出“答案错 ...

  8. 15款Java程序员必备的开发工具(转)

    如果你是一名Web开发人员,那么用膝盖想也知道你的职业生涯大部分将使用Java而度过.这是一款商业级的编程语言,我们没有办法不接触它 对于Java,有两种截然不同的观点: 一种认为Java是最简单功能 ...

  9. DeepLearning.ai-Week3-Autonomous driving-Car detection

    1 - Import Packages import argparse import os import matplotlib.pyplot as plt from matplotlib.pyplot ...

  10. Django学习手册 - ORM sqlit基础数据库操作

    步骤阐述:( splitDB 是Django自带的一个数据库) 1.在APP01 中的 models.py 配置DB信息  userinfo 相当于数据表的表名,而 uname.pwd 相当于 表中的 ...