我编写了一个bash监视脚本,其中包含期望自动登录到VPN服务的期望。
系统上只有root和User1。当由sudo从终端执行时,它可以按预期工作。
#!/bin/bash
vpn_user=$(getent passwd | grep "/home" | tail -1 | cut -d":" -f1)
write_log(){
echo "$msg" >> "some.log"
}
log_to_vpn(){
/usr/bin/expect -c '
set timeout 10
spawn sudo -u "User1" nordvpn login
expect "Please enter your login details.\r" {
expect "Email / Username: " { send "[email protected]\r" }
sleep 1
expect "*assword*" { send "User1Password\r" }
interact }
'
}
if ( sudo -u "$vpn_user" nordvpn account | grep "Active" ); then
msg="INFO: $vpn_user is already logged to VPN."
else
msg="WARNING: Logging to VPN by $(whoami) as $vpn_user."
log_to_vpn
sleep 1
if ( sudo -u "$vpn_user" nordvpn account | grep "Active" ); then
msg="OK: Logging to VPN as $vpn_user has been successful."
fi
fi
write_log
从终端消息执行时是:“ INFO:User1已经登录到VPN。”或“ OK:以User1成功登录到VPN。”根据情况是否已经登录User1是否。
问题是,当作为crone作业执行时,该作业不起作用。在这种情况下,some.log仅具有条目[[“警告:以root身份作为User1登录到VPN。”
为什么不起作用?#!/bin/bash
.
.
.
log_to_vpn(){
/usr/bin/expect '
set timeout 10
spawn sudo -u "User1" nordvpn login
expect "Please enter your login details.\r" {
expect "Email / Username: " { send "[email protected]\r" }
sleep 1
expect "*assword*" { send "User1Password\r" }
# interact }- to replace with below:
send "exit\r"
}
expect eof
'
}
.
.
问题已解决:)