我的项目要求打开和关闭笔记本电脑的电源。
有没有办法让 Ubuntu 在外部电源丢失时正常关机?它将使用其内部电池运行关机。
答案1
尝试检查on_ac_power
命令。来自man on_ac_power
:
NAME
on_ac_power - test whether computer is running on AC power
SYNOPSIS
on_ac_power
DESCRIPTION
on_ac_power checks whether the system is running on AC power (i.e., mains power) as opposed to battery
power.
OPTIONS
None.
EXIT STATUS
0 (true) System is on mains power
1 (false) System is not on mains power
255 (false) Power status could not be determined
if on_ac_power; then
echo "You are on AC-Power" # System is on mains power
else
echo "Power Lost" # System is not on mains power
fi
您需要每隔 X 个时间间隔检查一次交流电源状态。最简单的方法是在后台运行它,在 while 循环内:
while true
do
if on_ac_power; then
echo "You are on AC-Power" # System is on main power
else
echo "Power Lost" # System is not on main power
fi
sleep [Seconds]
done
保存您的脚本(ChechMainPWR.sh
),如果您想在启动时运行该脚本,请添加一行来/etc/rc.local
调用您的脚本(ChechMainPWR.sh
)+“&”以使其退出。像这样
sh /home/USERNAME/ChechMainPWR.sh $
重新启动并查看更改。
奖金
如果您想在桌面通知上看到丢失或未连接时的警报,您可以使用notify-send
程序。
notify-send "Main Power Lot!" "System is now shutting down"
请参阅man notify-send
以了解更多信息。
NAME
notify-send - a program to send desktop notifications
SYNOPSIS
notify-send [OPTIONS] <summary> [body]
DESCRIPTION
With notify-send you can sends desktop notifications to the user via a notification daemon from the command
line. These notifications can be used to inform the user about an event or display some form of information
without getting in the user's way.
那么最终的脚本将会是这样的:
最终脚本
while true
do
if ! on_ac_power; then # System is not on main power
notify-send "Main Power Lot!" "System is going down after 10 seconds"
sleep 10
echo YOUR_PASSWORD | sudo -kS shutdown -h now
#####^^^^^^^^^^^^^ VERY VERY VERY insecure! ##########
fi
sleep 300 # check main power status every 5 minutes
done
警告:这种echo YOUR_PASSWORD | sudo -kS shutdown -h now
方法虽然有效,但是非常不安全,因为您的密码写在您的历史记录中,并且其他用户也可能通过进程列表看到您的密码。
那么替代解决方案是;您可以将系统配置为sudo someCommand
不需要密码(在我的情况下为sudo shutdown
)。为此,请运行sudo visudo
并在打开的文件的末尾添加以下行:
Your_USERNAME ALL=NOPASSWD: /sbin/shutdown
然后退出编辑器并保存(CTRL+x)。
shutdown
现在您可以从命令行或脚本中使用命令,无需密码。
因此脚本将会是这样的:
while true
do
if ! on_ac_power; then #your system is not on AC-Power
notify-send "Main Power Lost!" "System is going down after 10 seconds"
sleep 10
sudo shutdown -h now # System is not on mains power
fi
sleep 300 # check main power status every 5 minutes
done
外部链接:
答案2
在电源管理偏好设置中,你可以设置当电池电量严重不足。
将其设置在那里关闭:
答案3
通过单击桌面右上角的设置图标并选择“系统设置...”进入系统设置
在系统设置面板中,单击“电源”,您可以看到一个选项“当电量极低时默认为黑屏。选择它并在下拉菜单中选择‘关机’”。