查询KVM虚拟主机信息

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了查询KVM虚拟主机信息相关的知识,希望对你有一定的参考价值。

脚本目的:脚本主要用查询KVM虚拟机主机名对应的IP地址及MAC地址,并且统计虚拟主机数量。

#!/bin/bash
#Creation Date : 2018-8-23
#Script Purpose : Query  KVM virtual host IP, hostname, MAC and Supports virtual host statistics.
#ARP Function : Arp is mainly used for address resolution, which makes it easy to query more complete IP information

CONFDIR=/etc/libvirt/qemu
ARPDIR=/usr/bin/virsh
LISTNAME=`$ARPDIR list --all |awk -F" " ‘{print $2}‘|sed 1d |grep -v "^$"`
HOSTNUM=`$ARPDIR list --all |awk -F" " ‘{print $2}‘|sed 1d |grep -v "^$"|wc -l`
RUNNUM=`$ARPDIR list --all |sed 1,2d |grep running |wc -l`
NORUNNUM=`$ARPDIR list --all |sed 1,2d |grep  "shut off" |wc -l`

arp(){
echo "ARP parsing is underway. Please wait for about 5-10 minutes."
for i in 192.168.122.{1..253}
do
ping -c2 $i > /dev/null 2>&1 &
done
}

all_query(){
for list in $LISTNAME
do
 MAC=`less $CONFDIR/$list.xml |grep "mac address"|awk -F"‘" ‘{print $2}‘`
 IP=`/sbin/arp -ne |grep virbr|grep ether|grep "$MAC" |awk -F" " ‘{print $1}‘`
 if [ "$IP" = "" ]
 then
  echo "HostName:$list IP:Empty Mac:$MAC"
 else
  echo "HostName:$list IP:$IP Mac:$MAC"
 fi
done
}

ip_query(){
MAC=`less $CONFDIR/$1.xml |grep "mac address"|awk -F"‘" ‘{print $2}‘`
IP=`/sbin/arp -ne |grep virbr|grep ether|grep "$MAC" |awk -F" " ‘{print $1}‘`
 if [ "$IP" = "" ]
 then
  echo "HostName:$1 IP:Empty Mac:$MAC"
 else
  echo "HostName:$1 IP:$IP Mac:$MAC"
 fi
}

name_query(){
MAC=`/sbin/arp -en |grep "$1" |awk -F" " ‘{print $3}‘`
CONFFILE=`grep  -rn "$MAC" $CONFDIR |awk -F":" ‘{print $1}‘`
NAME=`cat $CONFFILE |grep "<name>" |awk -F ">" ‘{print $2}‘|awk -F"<" ‘{print $1}‘`
echo "HostName:$NAME IP:$1 Mac:$MAC"
}

all_count(){
echo "The host number:$HOSTNUM"
echo "Number of running hosts:$RUNNUM"
echo "Number of hosts not running:$NORUNNUM"
}

case "$1" in
 query)
  all_query
 ;;
 count)
  all_count
 ;;
 arp)
  arp
 ;;
 name)
 ip_query $2
 ;;
 ip)
 name_query $2
 ;;
*)
    echo "Usage : {query|arp|count|name|ip}" >&2
    echo "name : Reverse check the IP and MAC through name."
    echo "ip : Reverse check the host name and MAC through IP."
    exit 3
;;
esac
exit 0

欢迎大家指点迷津,如有更好的方式请于下方留言。谢谢!

以上是关于查询KVM虚拟主机信息的主要内容,如果未能解决你的问题,请参考以下文章

VMware 中安装KVM,模块不加载

通过python获取kvm虚拟机的监控信息(基于libvirt API)

kvm热添加磁盘,且停机重启kvm虚拟机,文件信息不丢失

KVM虚拟化===》安装kVM创建网桥创建虚拟机克隆虚拟机vnc远程连接

一文告诉你Linux如何配置KVM虚拟化--安装篇

KVM管理