Scripting libvirt with php on CentOS or Redhat 7
Libvirt is virtualization API used to interact with different hypervisorrs. In this article we will look into scripting with php using libvirt api. This is very basic overview and designed for very basic scripting needs. This particular configuration was tested against KVM on CentOS 7.
In order to script libvirt with php we will need libvirt-php module which is a php module that provides PHP bindings for libvirt virtualization toolkit and therefore you can access libvirt directly from your PHP scripts with no need to have virt-manager or libvirt-based CLI/GUI tools installed.
Installing php lib-virt
First lets Install LAMP stack
#yum install httpd #systemctl start httpd.service #systemctl enable httpd.service #yum install mariadb-server mariadb #systemctl start mariadb #systemctl enable mariadb.service #yum install php php-mysql #systemctl restart httpd.service
Libvirt-php installation
wget http://libvirt.org/sources/php/libvirt-php-0.4.8.tar.gz yum install libvirt-devel yum install libxml2-devel yum install php-devel.x86_64 yum groupinstall "Development tools" yum install libxslt yum install virt-manager yum install ssh-askpass yum install openssh-askpass # on host gunzip -c libvirt-php-0.4.8.tar.gz | tar xvf - cd libvirt-php-0.4.8 ./configure make make install php -m | grep libvirt > /dev/null; echo $? # make sure 0 returned # create file below vi /etc/php.d/libvirt.ini extension=libvirt-php.so
Scripting
Use the following php script to get hostname and print list of active virtual machines.
<?php error_reporting(E_ALL); ini_set('display_errors', 1); $uri="qemu:///system"; $conn = libvirt_connect($uri); print_r(libvirt_connect_get_hostname($conn)); $doms1 = libvirt_list_domains($conn); print_r($doms1); $doms = libvirt_list_active_domains($conn); print_r($doms); ?>
If you want to use php scripts on remote hosts the following has to be done.
1. Create file on the KVM host that you want to control
/etc/polkit-1/localauthority/50-local.d/50-remotessh.pkla The name of the file is up to you, but needs to start with a two digit number and end with .pkla.
[SSH access] Identity=unix-user:user-name Action=org.libvirt.unix.manage ResultAny=yes ResultInactive=yes ResultActive=yes
2. Make sure user that runs httpd has ssh key generated and copied to KVM host. You can optionally chnage apache username with username
that has ssh access. You will also need to add user to apache group.