How can i check specific server running or not(using virsh commands), before I start | restart it?

Rajendra Maharjan picture Rajendra Maharjan · May 26, 2016 · Viewed 8.7k times · Source

I'm trying to restart, start, shutdown a specific virtual machine. Here, at first I want to check if the virtual machine is already in required state or not before I run the script.

These are the list of VMs.

[root@demohost05 ~]# virsh list --all
Id    Name                           State
----------------------------------------------------
5     OwnCloud01                     running
6     OwnCloud02                     running
7     SiteMon                        running
-     vmtest                         shut off

I want to check if vmtest is runnnig or not before I implement

virsh start vmtest

How can check the status using if condition in shell script ?

How can I avoid to enter password when I've to use sudo command.

sudo virsh start vmtest

I also tried to give root permission using

sudo -i
virsh start vmtest

But script ends without implementing 2nd line. How can I use both commands in same script file?

if [conditions]
then
{

}
fi

I couldnt figure out how to check conditions for such scripts.

Thank you.

Answer

Sharad picture Sharad · May 26, 2016

Try this:


tmp=$(virsh list --all | grep " vmtest " | awk '{ print $3}')
if ([ "x$tmp" == "x" ] || [ "x$tmp" != "xrunning" ])
then
    echo "VM does not exist or is shut down!"
    # Try additional commands here...
else
    echo "VM is running!"
fi

# For passwordless sudo:
sudo cat /etc/sudoers

# You'll see this:

# User privilege specification
root    ALL=(ALL:ALL) ALL

# To add user sharad as a sudo user:

# User privilege specification
root    ALL=(ALL:ALL) ALL
sharad  ALL=(ALL:ALL) ALL

# To add user sharad as a sudo user such that it doesn't ask for password (note the NOPASSWD):

# User privilege specification
root    ALL=(ALL:ALL) ALL
sharad  ALL=(ALL:ALL) NOPASSWD: ALL

# Read this for reference: http://www.ducea.com/2006/06/18/linux-tips-password-usage-in-sudo-passwd-nopasswd/