[Libguestfs] Script to read systemd journal of a guest to find its IP address

Kashyap Chamarthy kchamart at redhat.com
Sat Jun 14 06:11:03 UTC 2014


Heya,

Thanks Rich for the hints on IRC about journal bindings for libguestfs.
The below script is what I ended up with. At least I learnt how to
iterate over the systemd journal entries.

    $ sudo python find-ip.py 
    192.162.122.118

Obviously, this only searches for the _first_ occurance of the IP
address and doesn't take into account the guest may have acquired a new
IP on a later reboot. (I guess I'd have to do some thing like 
$ journalctl --lines=500 | egrep -i 'dhclient.*bound').

-------------------------------------------------------------------
#!/usr/bin/python
#-----------------------------------------------------------------
# PURPOSE: To find what IP address a guest has acquired from DHCP
#-----------------------------------------------------------------

image = "/var/lib/libvirt/images/ostack-controller.qcow2"

root_filesystem = "/dev/fedora/root"

import os
import sys
import re
import guestfs

g = guestfs.GuestFS ()

g.add_drive (image, format='qcow2')

g.launch ()
#print g.list_partitions()

# Set trace
#g.set_trace (1)

g.mount_options ("ro", root_filesystem, "/")

# Open the journal
g.journal_open ("/var/log/journal")


# Loop over the journal to find a specific string
count = 0
prog = re.compile("dhclient.*bound")
while g.journal_next():
    count += 1
    output = g.journal_get()
    #print output
    flag = 0
    for i in output:
        if i['attrname']=="MESSAGE" and i['attrval'].startswith("bound"):
            print i['attrval'].split()[2]
            flag = 1
            break
    if flag == 1:
        break

# Close the journal handle
g.journal_close ()

# Unmount all the file system(s)
g.umount_all ()

g.sync ()

sys.exit(0)
-------------------------------------------------------------------

-- 
/kashyap




More information about the Libguestfs mailing list