libguestfsを使って停止中のvm(kvm)のネットワーク設定を直接書き換えてみる
Re: 停止中のvm(kvm)のネットワーク設定を書き換える習作
id:lamanotramaがこんなエントリを書いていたので、勉強がてらpythonで書きなおしてみました。
virt-cloneした後のネットワーク設定をスクリプト一発でなんとかするヤツ。
試した環境はCentOS5.6です。
libvirtとlibguestfs使ってるので入ってない時はインストール
sudo yum --enablerepo=epel install libvirt-python python-libguestfs
lxml使ってるので入ってない時はインストール
sudo yum install python-lxml
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/env python | |
import sys | |
import libvirt | |
import guestfs | |
from lxml import etree | |
if (len(sys.argv) != 4): | |
sys.exit('Usage: # sudo python %s domain eth0 eth1' % sys.argv[0]) | |
domain = sys.argv[1] | |
ip0 = sys.argv[2] | |
ip1 = sys.argv[3] | |
uri = 'qemu:///system' #kvm | |
conn = libvirt.open(uri) | |
# check vm is exist | |
try: | |
vm = conn.lookupByName(domain) | |
except libvirt.libvirtError: | |
sys.exit('Domain not found: ' + domain) | |
# check vm is stoped | |
if (vm.isActive() != 0): | |
sys.exit('Domain is active: ' + domain) | |
# get variables from xml | |
devices = etree.fromstring(vm.XMLDesc(0)).findall('devices')[0] | |
disk = devices.find('disk').find('source').attrib["file"] # disk image | |
mac0 = '' # eth0 mac address | |
mac1 = '' # eth1 mac address | |
for interface in devices.findall('interface'): | |
bridge = interface.find('source').attrib["bridge"] | |
mac = interface.find('mac').attrib["address"] | |
if (bridge == 'br0'): | |
mac0 = mac | |
elif (bridge == 'virbr0'): | |
mac1 = mac | |
# new configuration | |
ifcfg='''DEVICE=%s | |
BOOTPROTO=static | |
HWADDR=%s | |
IPADDR=%s | |
NETMASK=255.255.255.0 | |
ONBOOT=yes''' | |
ifcfg0 = ifcfg % ('eth0', mac0, ip0) | |
ifcfg1 = ifcfg % ('eth1', mac1, ip1) | |
print 'New network configuration' | |
print '---------------------------' | |
print ifcfg0 | |
print '---------------------------' | |
print ifcfg1 | |
print '---------------------------' | |
# write variables to vm directly with libguestfs | |
guest = guestfs.GuestFS() | |
guest.add_drive(disk) | |
guest.launch() | |
guest.mount('/dev/mapper/VolGroup00-LogVol00', '/') | |
guest.write_file('/etc/sysconfig/network-scripts/ifcfg-eth0', ifcfg0, 0) | |
guest.write_file('/etc/sysconfig/network-scripts/ifcfg-eth1', ifcfg1, 0) | |
guest.sync() | |
guest.umount_all() | |
print 'Finish' |
やってることは
- domain(vm)が停止してるか確認 ((動いてるVMを直接libguestfsでいじると起動しなくなるみたいなので注意))
- domainのxml定義からイメージファイルのパスとMACアドレスを抜き出す
- libguestfsを使って停止中のvmの設定ファイルを直で上書く(指定したIPと先程のMACアドレス)
外部通信用のbr0と、内部通信用のvirbr0の二つネットワークある環境前提。
libguestfs便利。