Skip to content

Instantly share code, notes, and snippets.

@hellt
Last active April 1, 2022 00:06
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save hellt/3626a753a74e3e5a950c71e6b294543f to your computer and use it in GitHub Desktop.
Save hellt/3626a753a74e3e5a950c71e6b294543f to your computer and use it in GitHub Desktop.
Virsh interface move
#!/bin/bash
# usage ~/vifmove.sh <virsh_domain_name/id> <interface_name> <new_bridge_name>
tmpxml=$(mktemp /tmp/ifcfg.XXX)
macaddr="$(virsh domiflist $1 | awk "/$2\s/ {print \$NF}")"
cat > "$tmpxml" <<EOF
<interface type='bridge'>
<mac address='$macaddr'/>
<source bridge='$3'/>
<model type='virtio'/>
</interface>
EOF
virsh update-device "$1" "$tmpxml" --live --persistent
rm "$tmpxml"
@Znuff
Copy link

Znuff commented Dec 19, 2021

#!/bin/bash
# usage ~/vifmove.sh <virsh_domain_name/id> <interface_name> <new_bridge_name>
function update_bridge() {
  tmpxml=$(mktemp /tmp/ifcfg.XXX)
  macaddr="$(virsh domiflist $1 | awk "/$2\s/ {print \$NF}")"
  model="$(virsh domiflist $1 | awk "/$2\s/ {print \$4F}")"

  cat > "$tmpxml" <<EOF
<interface type='bridge'>
<mac address='$macaddr'/>
<source bridge='$3'/>
<model type='$model'/>
</interface>
EOF
  virsh update-device "$1" "$tmpxml" --live
  rm "$tmpxml"
}

for domain in $(virsh list --uuid); do
  update_bridge $domain $1 $2
done

I've added some bits to do all VMs in a batch.

@jacob-wm
Copy link

jacob-wm commented Apr 1, 2022

Added this to the end, for interfaces that have DHCP, it will bring it down and back up to refresh network. Note this only works for one interface, assumes you have DHCP in the guest, but the original script only assumes one interface per bridge anyway.

#!/bin/bash
# usage ~/vifmove.sh <virsh_domain_name/id> <interface_name> <new_bridge_name>
tmpxml=$(mktemp /tmp/ifcfg.XXX)
macaddr="$(virsh domiflist $1 | awk "/$2\s/ {print \$NF}")"
cat > "$tmpxml" <<EOF
<interface type='bridge'>
<mac address='$macaddr'/>
<source bridge='$3'/>
<model type='virtio'/>
</interface>
EOF
virsh update-device "$1" "$tmpxml" --live --persistent
rm "$tmpxml"
netintface=`virsh domiflist $1 | grep $3 | awk '{print $1}'`
echo $netintface
virsh domif-setlink "$1" $netintface down
sleep 2
virsh domif-setlink "$1" $netintface up

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