有什么方法可以将应用程序/脚本添加到 Linux 启动中,以便每次系统启动时都会执行它?
我正在寻找一些自动化的方式,即用户不应该通过 cron 作业或类似的东西添加它。
ccp*_*zza 10
除了系统级启动脚本之外,您的桌面环境可能有自己的自动运行程序方式。该文件夹.config/autostart应该是定义自动运行条目的桌面中立方式。/etc/xdg/autostart用于系统范围的配置。有关规范的详细信息,请访问http://developer.gnome.org/autostart-spec/。
对于 LXDE 自动启动条目也可以在~/.config/lxsession/LXDE/autostart.
如果您需要在网络启动并运行后运行脚本,则情况略有不同。在这种情况下,您应该检查可以为您的网络管理器定义的特殊连接后脚本。这两种网络管理器和WICD有自己指定连接后自动运行项的方式。如果网络是通过 配置的ifupdown,则可以将后期脚本放置在该/etc/network/if-up.d/文件夹中。但是运行后连接脚本的更好方法可能是 systemd(对于支持它的系统,这是大多数现代发行版)。
如果您想要自动启动的不是需要桌面的图形应用程序,那么最好避免使用 xorg 或您当前的桌面环境提供的任何自动启动工具。
systemd 已经在许多现代发行版中无处不在,它在您的服务如何启动和运行方面提供了很多控制和灵活性。
我将总结一些好处(systemd 可以做更多):
User=myuserRestart=on-failure|on-watchdog|on-abnormal|alwaysType=simple|forking|oneshot|notify|dbusWants=network-online.target在[Unit]部分)。启动 telegram-cli 守护进程的示例服务。把它放在/etc/systemd/system/tg.service.
[Unit]
Description=MyDaemon
Wants=network-online.target
After=network-online.target
[Service]
ExecStart=/usr/local/bin/telegram-cli -k /etc/telegram-cli/tg-server.pub -W -P 1234 -d -vvvRC
ExecStop=/usr/bin/pkill -f telegram-cli
User=jicu
[Install]
WantedBy=multi-user.target
Run Code Online (Sandbox Code Playgroud)
现在您可以启用服务自动启动:
sudo systemctl enable tg
Run Code Online (Sandbox Code Playgroud)
启动服务:
sudo systemctl start tg
Run Code Online (Sandbox Code Playgroud)
停止服务:
sudo systemctl stop tg
Run Code Online (Sandbox Code Playgroud)
检查状态:
systemctl status tg
Run Code Online (Sandbox Code Playgroud)
禁用服务:
sudo systemctl disable tg
Run Code Online (Sandbox Code Playgroud)
为了节省您额外的输入,您可以在您~/.bashrc的行中添加,alias sc='sudo systemctl $*'然后您就可以将上面的命令缩短为例如sc start tg。
注意:如果您使用过,
cron那么您应该知道 crontab 条目是在受限环境中运行的——这同样适用于systemd:始终使用绝对路径,并且不对正在定义的任何变量做任何假设。显式设置脚本所依赖的任何变量。systemd不会使用您用户的.bashrc和$PATH。
更多信息:
小智 7
是的,通过定义rc.local驻留在/etc或/etc/rc.d目录中的可执行文件的路径,可以在 Linux 上启动时运行程序,例如:
#!/bin/bash
# THIS FILE IS ADDED FOR COMPATIBILITY PURPOSES
#
# It is highly advisable to create own systemd services or udev rules
# to run scripts during boot instead of using this file.
#
# In contrast to previous versions due to parallel execution during boot
# this script will NOT be run after all other services.
#
# Please note that you must run 'chmod +x /etc/rc.d/rc.local' to ensure
# that this script will be executed during boot.
touch /var/lock/subsys/local
/path/to/executable
Run Code Online (Sandbox Code Playgroud)
注意:不要忘记按照文件文档中的描述分配可执行权限,即 Please note that you must run 'chmod +x /etc/rc.d/rc.local' to ensure that this script will be executed during boot.