
我有一個腳本,用於檢查是否有任何虛擬機正在運行,如果有,則優雅地關閉它們(使用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