qemu-mount - Tools for mounting QEMU images
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

67 lines
1.4 KiB

  1. #!/bin/sh
  2. #
  3. # show partition table of qemu image file
  4. #
  5. prog=$(basename "$0")
  6. # print error message
  7. error() {
  8. echo "$prog:" "$@" 2>&1
  9. exit 1
  10. }
  11. # check command line
  12. if [ $# -ne 1 ] || [ "$1" = "-h" ] || [ "$1" = "-?" ]; then
  13. cat << EOF >&2
  14. Show partition table of qemu image file
  15. Usage: $prog qemu_image
  16. EOF
  17. exit 1
  18. fi
  19. image="$1"
  20. # use sudo for unprivileged users
  21. SUDO=
  22. [ "$(id -u)" -ne 0 ] && SUDO=sudo
  23. # check image
  24. [ -e "$image" ] || error "$image: no such file"
  25. [ -f "$image" ] || error "$image must be a regular file"
  26. img_fmt=$(qemu-img info "$image" | sed -n 's/^file format: \(.*\)/\1/p')
  27. [ -n "$img_fmt" ] || error "$image has unknown format"
  28. # load kernel module, check if sudo works
  29. $SUDO modprobe nbd nbds_max=16 max_part=31 || exit $?
  30. # lock
  31. umask=$(umask); umask 0
  32. (
  33. flock -w 5 9 || error "Can't get mount lock"
  34. umask "$umask"
  35. # find free nbd device
  36. nbd_size=1
  37. for nbd in /sys/class/block/nbd*; do
  38. [ -n "${nbd##*/nbd[0-9]}" ] && \
  39. [ -n "${nbd##*/nbd[0-9][0-9]}" ] && \
  40. continue
  41. nbd_size=$(cat "${nbd}/size")
  42. [ "$nbd_size" -gt 0 ] || break
  43. done
  44. [ "$nbd_size" -gt 0 ] && error "no free nbd devices"
  45. nbd=$(basename "$nbd")
  46. # qemu-nbd
  47. $SUDO qemu-nbd -c "/dev/$nbd" -r -f "$img_fmt" "$image" || exit
  48. # show partition table
  49. $SUDO fdisk -l "/dev/$nbd"
  50. ret=$?
  51. sync
  52. $SUDO qemu-nbd -d "/dev/$nbd" > /dev/null 2>&1
  53. exit $ret
  54. ) 9>> /var/lock/qemu-mount.lock