Skip to content

Instantly share code, notes, and snippets.

@rohityadavcloud
Last active April 12, 2019 18:21
Show Gist options
  • Save rohityadavcloud/ddb42c4c7581c4129ca04fbb829f16cf to your computer and use it in GitHub Desktop.
Save rohityadavcloud/ddb42c4c7581c4129ca04fbb829f16cf to your computer and use it in GitHub Desktop.
qemu guest agent based patching
#!/bin/bash
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
set -e
while getopts "n:p:h" opt; do
case ${opt} in
n )
name=$OPTARG
;;
p )
cmdline=$(echo $OPTARG | tr '%' ' ' | base64 -w 0)
;;
h )
echo "Usage: $0 -n [VM name] -p [command line]"
exit 0
;;
esac
done
SOCK_FILE="/var/lib/libvirt/qemu/${name}.agent"
SSHKEY_FILE="/root/.ssh/id_rsa.pub.cloud"
if [ ! -e $SOCK_FILE ]; then
echo "Socket file $SOCK_FILE not found!"
exit 1
fi
if [ ! -e $SSHKEY_FILE ]; then
echo "SSH public key file $SSHKEY_FILE not found!"
exit 1
fi
while ! virsh qemu-agent-command $name '{"execute":"guest-ping"}' >/dev/null 2>&1
do
sleep 0.1
done
while [ $(virsh qemu-agent-command $name '{"execute":"guest-sync","arguments":{"id":1234567890}}' 2>/dev/null) != '{"return":1234567890}' ]
do
sleep 0.1
done
write_file() {
local name=${1}
local path=${2}
local content=${@:3}
fd=$(virsh qemu-agent-command $name "{\"execute\":\"guest-file-open\", \"arguments\":{\"path\":\"$path\",\"mode\":\"w+\"}}" | sed 's/[^:]*:\([^}]*\).*/\1/')
virsh qemu-agent-command $name "{\"execute\":\"guest-file-write\", \"arguments\":{\"handle\":$fd,\"buf-b64\":\"$content\"}}" > /dev/null
virsh qemu-agent-command $name "{\"execute\":\"guest-file-close\", \"arguments\":{\"handle\":$fd}}" > /dev/null
}
# Write cmdline payload
write_file $name "/var/cache/cloud/cmdline" $cmdline
# Write ssh public key
write_file $name "/root/.ssh/authorized_keys" $(cat $SSHKEY_FILE | base64 -w 0)
# Fix ssh public key permission
virsh qemu-agent-command $name '{"execute":"guest-exec","arguments":{"path":"chmod","arg":["go-rwx","/root/.ssh/authorized_keys"]}}' > /dev/null
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment