Created
November 15, 2011 03:01
-
-
Save tnmt/1366007 to your computer and use it in GitHub Desktop.
Modify KVM VM (stopped) network setting using libguestfs
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' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment