Python学习之十六_virsh批量获取虚拟机IP地址的方法
Linux命令说明
for j in \
$(for i in `virsh list |grep -v Id |grep running |awk '{print $2}'` ; \
do virsh dumpxml $i |grep "mac address"| awk -F\' '{ print $2}' && echo $i ; done) ; \
do echo -n $j && arp -an|grep $j |grep enp ; done
命令说明
双层嵌套循环
内存获取机器名字列表,并且打印.
virsh list |grep -v Id |grep running |awk '{print $2}'
然后利用机器名 获取 xml配置文件信息
virsh dumpxml $vm_name
获取mac地址信息, 并且仅展示mac地址
grep "mac address"| awk -F\' '{ print $2}'
通过arp 列表找出 对应的IP地址信息
arp -an |gerp mac_address
执行效果为:
11-K8S-m20152:54:00:61:01:8a? (xx.xxx.xxx.162) at 52:54:00:61:01:8a [ether] on enp39s0f0
11-K8S-m20352:54:00:a7:cb:c5? (xx.xxx.xxx.161) at 52:54:00:a7:cb:c5 [ether] on enp39s0f0
11-K8S-m20252:54:00:9d:77:0c? (xx.xxx.xxx.163) at 52:54:00:9d:77:0c [ether] on enp39s0f0
11-K8S-w20452:54:00:7d:18:6b? (xx.xxx.xxx.164) at 52:54:00:7d:18:6b [ether] on enp39s0f0
11-K8S-w20552:54:00:96:47:60? (xx.xxx.xxx.165) at 52:54:00:96:47:60 [ether] on enp39s0f0
11-K8S-w20752:54:00:df:06:1a? (xx.xxx.xxx.166) at 52:54:00:df:06:1a [ether] on enp39s0f0
11-K8S-n20852:54:00:04:95:18? (xx.xxx.xxx.167) at 52:54:00:04:95:18 [ether] on enp39s0f0
11-K8S-db21052:54:00:0c:75:e9? (xx.xxx.xxx.169) at 52:54:00:0c:75:e9 [ether] on enp39s0f0
执行时间信息为:
real 0m0.225s
user 0m0.159s
sys 0m0.136s
最近学习python 尝试实现一下.
#!/usr/bin/python3
# coding=utf-8
import os
vmlist = os.popen("virsh list |grep -v Id |grep running |awk '{print $2}'")
for i in vmlist :
print(i[:-1] + "机器的IP地址为: ",end="")
with os.popen("virsh dumpxml " + i[:-1] + " |grep 'mac address'| awk -F \\' '{ print $2}'") as pipe :
mac = pipe.read()
with os.popen("arp -an | grep " + mac[:-1] + " | awk '{print $2}' |head -n 1 " ) as pipe2:
ip = pipe2.read()
print(ip[1:-2])
执行结果为:
11-k8s-w15机器的IP地址为: xx.xxx.xxx.158
11-k8s-w12机器的IP地址为:
11-K8S-m201机器的IP地址为: xx.xxx.xxx.160
11-K8S-m203机器的IP地址为: xx.xxx.xxx.162
11-K8S-m202机器的IP地址为: xx.xxx.xxx.161
11-K8S-w204机器的IP地址为: xx.xxx.xxx.163
11-K8S-w205机器的IP地址为: xx.xxx.xxx.164
11-K8S-w207机器的IP地址为: xx.xxx.xxx.165
11-K8S-n208机器的IP地址为: xx.xxx.xxx.166
11-K8S-db210机器的IP地址为: xx.xxx.xxx.167
11-K8S-r215机器的IP地址为: xx.xxx.xxx.169
执行时间信息为:
real 0m0.274s
user 0m0.198s
sys 0m0.132s
Python命令解析
首先: 最开始三行的作用是指定运行脚本解析器, 以及编码和需要的os包.
#!/usr/bin/python3
# coding=utf-8
import os
其次: 一个命令获取机器列表
vmlist = os.popen("virsh list |grep -v Id |grep running |awk '{print $2}'")
需要注意 os.system() 会直接界面化执行命令, 并不能够返回结果, 需要使用 popen 的方式才能够获取
再次: 建议循环:
for i in vmlist :
循环内处理:
print(i[:-1] + " 机器的IP地址为: ",end="")
通过[:-1] 去掉最后一个回车字符, 通过指定 end="", 不能行默认换行, 便于友好展示.
with os.popen("virsh dumpxml " + i[:-1] + " |grep 'mac address'| awk -F \\' '{ print $2}'") as pipe :
mac = pipe.read()
通过 with as 命令, 将 popen 打开的命令结果集转为pipe
然后通过 read 命令, 将结果转换为字符, 不然会报对象未封装的错误.
注意 shell 命令与linux的命令是一样的.
感想
人生苦短, 要学python
python 的确能够极大的提高展现能力.
我回继续学习python. 提高自己.
虽然速度慢一点点 但是效果要好非常多.
标签:11,Python,54,虚拟机,xxx,xx,virsh,IP地址,K8S
From: https://www.cnblogs.com/jinanxiaolaohu/p/17408775.html