Skip to content

Instantly share code, notes, and snippets.

@libcrack
Created May 11, 2016 20:58
Show Gist options
  • Select an option

  • Save libcrack/5d0a62e2b60ab1dbc2bcd924f8742a01 to your computer and use it in GitHub Desktop.

Select an option

Save libcrack/5d0a62e2b60ab1dbc2bcd924f8742a01 to your computer and use it in GitHub Desktop.
libvirtctl.py
#!/usr/bin/env python
# coding: utf-8
# mié may 11 22:01:32 CEST 2016
# http://pylint-messages.wikidot.com/all-codes
# pylint: disable-msg=C0103
# pylint: disable-msg=C0301
# pylint: disable-msg=W0611
# pylint: disable-msg=W0612
# pylint: disable-msg=W0702
# pylint: disable-msg=W0703
# pylint: disable-msg=W0621
# pylint: disable-msg=R0913
"""
This script helps carrying out several libvirt tasks
"""
__author__ = "Null Device <devnull [at] libcrack [dot] so>"
__date__ = "Date: Wed Jan 28 16:35:57 CET 2015"
__version__ = 0.1
import os
import sys
import time
import string
import random
import libvirt
import logging
import argparse
import datetime
import subprocess
logname = 'libvirtctl'
logfile = '{0}.log'.format(logname)
logging.basicConfig(level=(logging.INFO))
logger = logging.getLogger(logname)
# LOG_FORMAT = '%(asctime)s [%(levelname)s] %(module)s.%(funcName)s : %(message)s'
# __formatter = logging.Formatter(LOG_FORMAT)
# __streamhandler = logging.StreamHandler()
# __streamhandler.setFormatter(__formatter)
# logger.addHandler(__streamhandler)
def detect_platform():
if sys.platform.startswith("linux") or sys.platform == "darwin":
logging.info("Detected platform: %s", sys.platform)
elif sys.platform == "win32":
raise Exception("Use a proper OS, biatch!")
else:
raise Exception("Cannot detect underlying operating system")
return sys.platform
# def execute_action(cmdline=None):
# # cmdline = ["ip", "route", action, args.device, "essid", args.essid, "key", "off"]
# action = "add"
# target = "default"
# gateway = "172.19.19.254"
# cmdline = ["ip", "route", action, target, "via", gateway]
# logging.info("Executing action \"${cmdline}\"")
# try:
# subprocess.call(cmdline)
# except subprocess.CalledProcessError as e:
# logging.error("Cannot execute: {0}".format(e))
# return 20
# # logging.error("Exiting program")
# # sys.exit(20)
# def libvirt_execute_action(cmdline=None, uri=None):
# conn = libvirt.open(uri)
# for domid in conn.listDomainsID():
# dom = conn.lookupByID(domid)
# print("Dom {0} State {1}".format(dom.name(), dom.info()[0]))
# dom.suspend()
# print("Dom {0} State {1} (after suspend)".format(dom.name(),dom.info()[0]))
# dom.resume()
# print("Dom {0} State {1} (after resume)".format(dom.name(),dom.info()[0]))
# dom.destroy()
if __name__ == '__main__':
libvirt_uri = "qemu:///system/"
try:
libvirt_uri = os.environ.get(variable["LIBVIRT_DEFAULT_URI"])
except: pass
parser = argparse.ArgumentParser(
formatter_class=argparse.RawDescriptionHelpFormatter,
description="Libvirtd control: Additional libvirt tasks the easy way.",
epilog="Example:\n\t{0} --start -d eth0\n\t{0} --start -d eth0".format(__file__),
add_help=True)
parser.add_argument("-c", "--uri", action="store", dest="uri", required=True,
type=str, help="connect to URI", default=libvirt_uri)
parser.add_argument("-t", "--timemsec", action="store", dest="msec", required=False,
type=int, help="sleep msec (default=10)", default=10)
parser.add_argument("-u", "--username", action="store", dest="user", required=False,
type=str, help="username to use", default=None)
parser.add_argument("-s", "--server", action="store", dest="server", required=False,
type=str, help="server to connect to", default=None)
parser.add_argument("-l", "--loglevel", action="store", dest="loglevel", required=False,
type=int, help="log level (10-50;default=20)", default=20)
parser.add_argument("-p", "--proxy", action="store", dest="proxy", required=False,
type=str, help="HTTP proxy server", default=None)
parser.add_argument("-r", "--rebuild", action="store_true", dest="rebuild", required=False,
help="Rebuild snapshots", default=False)
# parser.add_argument("-h", "--help", action="store_true", dest="help", required=False, type=bool, help="This help", default=False)
# parser.add_argument("-x", "--xxx", action="store", dest="xxx", required=False, type=str, help="do xxx (default=\"xxx\")", default="xxx")
# try:
# subprocess.check_call(cmdline)
# except Exception as e:
# logging.error("%s : %s", e.code, e.msg)
# finally:
# logging.warning("Sleeping %s", args.msec)
# time.sleep(args.msec)
# libvirt_uri = "{1}://{2}@{3}/{4}".format(proto,user,host,path)
start_time = time.strftime("%d-%m-%Y %H:%M:%S")
logging.info("Starting at {0}".format(start_time))
args = parser.parse_args()
logging.basicConfig(level=args.loglevel)
logging.info("Setting loglevel={0}".format(args.loglevel))
# if args.uri is not "qemu:///system/":
if args.uri is not libvirt_uri:
libvirt_uri = args.uri
logging.info("Using URI %s", libvirt_uri)
logging.info("Connecting to %s", libvirt_uri)
try:
conn = libvirt.open(libvirt_uri)
except libvirtError as e:
# logging.error("%s : %s", e.code, e.msg)
logging.exception(e)
sys.exit(1)
else:
logging.info("Getting vm details")
try:
for domid in conn.listDomainsID():
try:
dom = conn.lookupByID(domid)
logging.info("Dom {0} State {1}".format(dom.name(), dom.info()[0]))
dom.suspend()
logging.info("Dom {0} State {1} (after suspend)".format(dom.name(), dom.info()[0]))
dom.resume()
logging.info("Dom {0} State {1} (after resume)".format(dom.name(), dom.info()[0]))
dom.destroy()
except libvirtError as e:
# logging.exception(e)
logging.error("%s : %s", e.code, e.msg)
logging.warning("Sleeping %s", args.msec)
time.sleep(args.msec)
except Exception as e:
conn.close()
logging.error("%s : %s", e.code, e.msg)
logging.exception("Exception received when listing domains: %s : %s", e.code, e.msg)
conn.close()
end_time = time.strftime("%d-%m-%Y %H:%M:%S")
logging.info("Ending at {0}".format(end_time))
logging.info("Disconnecting")
sys.exit(0)
# vim:ts=4 sts=4 tw=100:
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment