抓取kvm虛擬機IP地址功能腳本
腳本如下:
#!/usr/local/python3/bin/python3
import re,os,sys,time
mac_add = []
vir_name = sys.argv[1]
#打開給定的虛擬機名稱的xml文件來查找mac地址
with open('/etc/libvirt/qemu/%s.xml'%vir_name,'r') as f:
for line in f:
line = line.strip('\n')
if "mac address" in line:
mac_add.append(line)
#定用正則查出mac地址格式
result = re.findall(r'[0-9,a-z]+',mac_add[0],re.S)
mac_address = result[2] + result[3] + "." + result[4] + result[5] + "." + result[6] + result[7]
with open('/opt/script/ip_detail.txt','r') as f1:
for line in f1:
line = line.strip('\n')
if mac_address in line:
line = line.split('|')[0]
print(line)
註意:腳本中的ip_detail.txt文件內容是1.1.1.1|20|5254.007b.fc59|GigabitEthernet1/0/4格式為內容的文件,否則就要更改腳本中的line.split('\’)根據自己的情況修改即可。
抓取kvm虛擬機IP地址功能腳本