我有一个脚本,用于检查是否有任何虚拟机正在运行,如果有,则正常关闭它们(使用 VBoxManage),这样做的目的是,如果我被叫离我的机器,那么在虚拟机中运行的数据库在恢复时不会因时间跳跃而出现问题。
该脚本从命令行正确运行,但从我创建的 suspend-to-hibernate.service 文件调用时则无法运行!
应该发生的是,脚本调用 VBoxManage 列出正在运行的机器,将其输入 awk 以提取虚拟机的名称,将其全部转储到另一个文件中,然后调用该文件来关闭机器。
它运行良好,直到调用 VBoxManage - 看起来该命令根本没有运行。 /usr/bin/VBoxManage 实际上是指向调用 /usr/lib/virtualbox/VBoxManage 的脚本的链接。我试过直接调用它,但仍然没有运行。
stop-vms.log 显示“即时”脚本确实运行。
我已经有一段时间没有编写过任何 unix 脚本了,我感觉我错过了一些非常简单的东西......
暂停到休眠.服务:
[Unit]
Description=Script to check for VirtualBox VMs and pause them
Conflicts=hibernate.target hybrid-suspend.target
Before=suspend.target sleep.target
StopWhenUnneeded=true
[Service]
Type=oneshot
RemainAfterExit=yes
ExecStart=/bin/sh /home/steve/Documents/scripts/stop-vms.sh suspend
[Install]
WantedBy=sleep.target
RequiredBy=suspend.target
停止vms.sh:
#!/bin/sh
# some vars:
NEWSCRIPT=/home/steve/Documents/scripts/stopvms
SHELL=/bin/sh
LOGFILE=/home/steve/logs/stop-vms.log
# check if script file exists, if not create & make executable
if [ ! -e $NEWSCRIPT ]
then
touch $NEWSCRIPT
chmod 775 $NEWSCRIPT
fi
# tell the script where the shell is
echo '#!'$SHELL > $NEWSCRIPT
echo '#starting at:' `date` >> $NEWSCRIPT
# get list of running machines and dump into script file
echo 'echo "running vms" >> /home/steve/logs/stop-vms.log' >> $NEWSCRIPT
/usr/bin/VBoxManage list runningvms | awk '{print "/usr/lib/virtualbox/VBoxManage controlvm " substr($line, 1, index($line,"{")-2) " acpipowerbutton >> /home/steve/logs/stop-vms.log "} ' >> $NEWSCRIPT
echo 'vms done, about to run script at ' `date` >> $LOGFILE
# run the script
$NEWSCRIPT
# now wait to make sure the previous command has had time to finish...
sleep 30
# report on last run...
echo >> $NEWSCRIPT
echo '# Last Run: ' `date` >> $NEWSCRIPT
预期的 stopvms 脚本(从终端运行时)
#!/bin/sh
#starting at: Wed 31 Jan 10:24:34 GMT 2018
echo "running vms" >> /home/steve/logs/stop-vms.log
/usr/lib/virtualbox/VBoxManage controlvm "Dev Mysql GlassFish" acpipowerbutton >> /home/steve/logs/stop-vms.log
# Last Run: Wed 31 Jan 10:25:04 GMT 2018
从 suspend-to-hibernate.service 运行时实际情况:
#!/bin/sh
#starting at: Wed 31 Jan 10:59:26 GMT 2018
echo "running vms" >> /home/steve/logs/stop-vms.log
# Last Run: Wed 31 Jan 10:59:56 GMT 2018