如何在 FreeBSD Bourne shell 上创建和处理字符串?

如何在 FreeBSD Bourne shell 上创建和处理字符串?

我正在 FreeBSD 下编写一个脚本来备份所有正在运行的 bhyve 虚拟机。目标是识别所有正在运行的虚拟机,逐一停止,等待其 PID 完成、备份并重新启动。

我知道我可以从 shell 命令vm list并获取:

root@mellonas:/ # vm list
NAME            DATASTORE       LOADER      CPU    MEMORY    VNC                  AUTOSTART    STATE
dockers         default         grub        2      4096M     -                    No           Stopped
freebsd         default         bhyveload   1      256M      -                    No           Stopped
guacamole       default         grub        1      512M      -                    No           Stopped
mediaserver     default         grub        4      3048M     -                    Yes [2]      Running (2046)
mx-server       default         grub        1      1024M     -                    Yes [3]      Running (2609)
nextcloud       default         bhyveload   1      1024M     -                    Yes [4]      Running (2783)
pf              default         bhyveload   2      1512M     -                    Yes [1]      Running (1766)
zm              default         grub        4      2548M     -                    Yes [5]      Running (2957)

由于我没有脚本编码经验,因此我在下面编写了此脚本,该脚本需要手动更新虚拟机列表以添加/删除新的虚拟机列表:

#!/bin/sh
#

#
# Variables

now=$(date +"%Y-%m-%d_%H:%M:%S")                # Run date
maindir=/raid/vm/                               # bhyve VM's directory
vmbkpdir=/raid/cifs/vmbackups/$now              # Back-up directory
log_file=$maindir"/vmcopy.log"                  # Log file
vm_list="pf mediaserver mx-server nextcloud zm" # List of VMs to back-up

#
# Process log entries

log()
{
timestamp=$(date +"[%Y-%m-%d %H:%M:%S]")
parm="$1"
  if [ -e $log_file ];
     then
     echo "$timestamp copy bhyve VMs: $parm" >> $log_file
  else
    echo "$timestamp copy bhyve VMs: Log file created" > $log_file
    echo "$timestamp copy bhyve VMs: $parm" >> $log_file
  fi
}

#
# Process VM back-up

save()
{
vm=$1
vmdir=$maindir$vm
log "vm directory $vmdir"
log "Stopping $vm"
vm stop $vm
sleep 60
cd $vmbkpdir
log "Creating tar ball"
tar -zcvf $vm.tar.gz $vmdir                     # Change to zfs snapshot if desired
log "Restarting vm"
vm start $vm
log "*** Copy completed ***"
}


#
# Main

log "*** Script started ***"
log "vm backup directory $vmbkpdir"
log "Creating back-up directory"
mkdir $vmbkpdir

for vms in $vm_list; do                         # Loop through VMs
        log "${vms}"
        save "${vms}"
done

log "*** End of script ***"

我想:

  1. 从输出中捕获 VM 列表虚拟机列表

  2. 捕获正在运行的虚拟机进行处理(停止、等待 PID、备份、重新启动)

答案1

你的第二个问题不明确。问题1很简单。这将获取相关的进程 ID:

PIDS=`vm list | grep ' Running ' | sed -e 's;.* Running ;;' | tr -d '()'`
echo $PIDS
for PID in $PIDS; do ps wwup $PID; done

相关内容