Skip to content

Instantly share code, notes, and snippets.

@tomassedovic
Forked from petrblaho/virip
Last active January 18, 2017 10:42
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save tomassedovic/3728817 to your computer and use it in GitHub Desktop.
Save tomassedovic/3728817 to your computer and use it in GitHub Desktop.
Simple script for detecting IP address of running virtual machine
#!/bin/bash
if [[ $# == 0 ]]; then
echo Usage:
echo "virt <command> <vm> args"
echo Command is: ip, ssh, scp, sshfs
exit 1
fi
cmd="$1"; shift
destination="$1"
user=$(echo $destination | awk '{split($0,array,"@")} END {print array[1]}')
domain=$(echo $destination | awk '{split($0,array,"@")} END {print array[2]}')
if [ -z "$domain" ]; then
domain=$user
user=`whoami`
fi
ip=$(virt-ip $domain) || exit 1
shift
host="$user@$ip"
case "$cmd" in
ip)
echo $ip
;;
ssh)
virt-ssh "$host" $@
;;
scp)
virt-scp "$host" $@
;;
sshfs)
virt-sshfs "$host" $@
;;
esac
#!/bin/bash
# Inspired by Lars Kellogg-Stedman's script:
# http://blog.oddbit.com/post/getting-the-ip-address-of-a-libvirt-domain
function virsh_cmd {
virsh -c qemu:///system $@
}
which xmllint &>/dev/null || (echo "xmllint not found, install libxml2 to get it." 1>&2 && exit 1)
if [[ $# == 0 ]]; then
echo Enter a virtual machine name: 1>&2
echo 1>&2
virsh_cmd list 1>&2
exit 1
fi
# Quit if we got an unknown domain name. `virsh` will print the error messages.
domain_xml=$(virsh_cmd dumpxml $1) || exit 1
# Get the MAC address of the first interface.
mac=$(echo "$domain_xml" |
xmllint --xpath //interface'[1]/mac/@address' - |
sed 's/.*="\([^"]*\)"/\1/'
)
# Get the ip address assigned to this MAC from dnsmasq
ip=$(awk -vmac=$mac '$2 == mac {print $3}' /var/lib/libvirt/dnsmasq/default.leases)
echo $ip
#!/bin/bash
scp -o "StrictHostKeyChecking no" -o "UserKnownHostsFile /dev/null" $@
#!/bin/bash
ssh -o "StrictHostKeyChecking no" -o "UserKnownHostsFile /dev/null" $@
#!/bin/bash
sshfs -o "StrictHostKeyChecking=no" -o "UserKnownHostsFile=/dev/null" $@
@tomassedovic
Copy link
Author

Changes from @petrblaho's gist 3607944:

  • no need for sudo
  • simplified getting the bridge name
  • fixed issue where the ifconfig call returned "addr:192.168.1.*" instead of just the IP-formatted text

@tomassedovic
Copy link
Author

Updated to use /var/lib/libvirt/dnsmasq/default.leases where libvirt maintains the leased ip addresses. More robust than parsing the logs and whatnot.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment