【问题标题】:Run shutdown command inside bash script在 bash 脚本中运行关机命令
【发布时间】:2019-03-15 14:37:35
【问题描述】:

我正在尝试制作一个可执行文件(bash 脚本)以在未找到进程时向我显示通知并关闭我的计算机。

我将把脚本作为启动应用程序运行,并在此脚本中使用notify-sendshutdown 命令。

问题是:
(1) 如果我将myfolder/myscript 添加到启动应用程序列表中,它将无法运行shutdown 命令(此操作需要root 密码)
(2) 如果我添加脚本sudo myfolder/myscript 它无法通过notify-send 应用程序显示通知。

我已经在互联网上进行了大量搜索并尝试了以下步骤:
(1) 通过sudo visudo将脚本路径或/sbin/shutdown添加到sudores
(2)在notify-send命令前添加su - $USER -c "DISPLAY=$DISPLAY DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/$UID/bus(我发现有用户反映root无法发送通知)`

所以......他们都没有工作。我错过了什么? 如何显示通知和关机?

这是我的代码:

#!/bin/bash

#Search for a specific process and sleep if it is found (removed for space saving)

shut_time=$(date --date='10 minutes' +"%T")
notify-send -t 600000 "WARNING:
Program is not running.
Shutting down in 10 minutes (scheduled for $shut_time)."

#ALREADY TESTED BELLOW LINES (DON'T WORK)
#su - $USER -c "DISPLAY=$DISPLAY DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/$UID/bus notify-send -t 600000 'WARNING:
#Program is not running.
#Shutting down in 10 minutes.'"

sudo /sbin/shutdown -h +10 #Tried with our without sudo

我正在运行 MX Linux 18(xfce,基于 Debian)。

【问题讨论】:

  • 你能从命令行启动'sudo /sbin/shutdown -h +10'吗?
  • 为什么不使用 cronjobs?
  • mxlinux.org/forum/viewtopic.php?t=48026 建议systemctl poweroff -idbus-send --system --print-reply --dest=org.freedesktop.login1 /org/freedesktop/login1 "org.freedesktop.login1.Manager.Poweroff" boolean:true
  • @UtLox,如果我从命令行启动它,它工作得很好 如果我提供了 sudo 密码。我希望系统自动执行此脚本,而无需输入密码。但是,如果我将此脚本作为 root 执行,我将无法收到通知。到目前为止,我必须决定......由用户执行 -> 无法关闭......由 root 执行 -> 无法发送通知。
  • @GeorgeAppleton,据我所知,cronjobs是用来在特定时间执行任务的,对吗?我想在打开计算机后每隔一小时执行这个脚本来执行一次进程检查。我认为 cronjob 的问题是,如果我将脚本设置为每小时(12h00、13h00、14h00 ...)从 crontab 执行,并且我在 12h59 打开计算机,它将在 1 分钟后关闭(如果特定进程没有运行)。

标签: bash root sudo shutdown notify-send


【解决方案1】:

我认为它在 sudoers 中缺少关闭条目。请在 /etc/sudoers.d 下创建一个文件 sudo 并输入以下内容:

[YOURUSER] ALL = (ALL) NOPASSWD: /sbin/shutdown

将 [YOURUSER] 替换为您的用户帐户!

【讨论】:

  • 这和通过sudo visudo添加一样吗?如果是,我已经尝试添加:my_user ALL=NOPASSWD: /sbin/shutdown 结果:我收到通知很好,但系统没有关闭。
  • (ALL) 丢失
  • 我将脚本更改为sudo /sbin/shutdown -h +1 以快速关闭,通过sudo visudo 提出您的建议并重新启动... 只收到通知。但是,如果我在 /etc/sudores.d 下添加一个包含您提到的内容的文件,它就可以了!谢谢!
  • 那么为什么在通过sudo visudo添加时它不起作用?
猜你喜欢
  • 1970-01-01
  • 2015-04-11
  • 1970-01-01
  • 2013-07-11
  • 2015-01-09
  • 2018-08-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多