# 在 Ubuntu 上使用 systemd 配置开机执行脚本

**URL:** <https://www.shiwantech.xyz/t/topic/213>\
**Category:** UBUNTU\
**Created:** [2024 年10 月 13 日 11:55 UTC](https://www.shiwantech.xyz/t/topic/213 "2024-10-13T11:55:00Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

作者： ![itpanpan163](https://www.shiwantech.xyz/letter_avatar_proxy/v4/letter/i/ccd318/32.png) [@itpanpan163](https://www.shiwantech.xyz/u/itpanpan163)\
发布日期： [2024 年10 月 13 日 11:55 UTC](https://www.shiwantech.xyz/t/topic/213/1 "2024-10-13T11:55:00Z")

</div>

简述  
在配置自用服务器时，经常需要在开机后启动某些服务。  
人工登录后手动启动服务肯定可行，但本文希望节省人工干预的时间。  
省出来的时间可以用来陪家人、学习、锻炼身体，也可以用来发呆、睡觉，反正就不要花时间进行重复的机械性操作。

为此，本文使用 systemd 配置的方式让 Ubuntu 系统在开机且未登录的的状态下执行特定的 Shell 脚本。

systemd  
systemd 可以看作是 Linux 系统下的服务管理者，已被应用到很多主流的 Linux 发行版中（如 Ubuntu, Debian, Fedora 等）用于系统管理。  
如在 Ubuntu 20.04 上用命令行关机，可直接使用如下 systemd 提供的命令：

sudo systemctl poweroff

本文选取 systemd 实现开机执行 Shell 脚本有两个原因：  
配置方法简便。  
systemd 已被 Linux 发行版广泛采用，使用 systemd 在开机时执行脚本可以认为是一种官方建议做法。

通用操作步骤  
创建希望开机马上执行的脚本，本文举例脚本存放位置为

```auto
/home/tqh/Documents/Example/StartupScipt.sh，脚本内容如下：
#!/bin/sh

```

开机时在脚本的同级目录下创建一个名为 StartupTouch.txt 的文件  
`touch /home/tqh/Documents/Example/StartupTouch.txt`

开机执行的脚本需增加可执行权限才能被 systemd 运行，使用如下命令

```auto
chmod u+x /home/tqh/Documents/Example/StartupScipt.sh
chmod g+x /home/tqh/Documents/Example/StartupScipt.sh

```

进入 systemd 放置 service 的目录，在该目录下可看到大量服务配置文件，命令如下

进入 systemd 的 service 目录  
`cd /etc/systemd/system`

查看文件列表  
ls -al

在该目录创建一个新的 .service 文件用于配置开机启动脚本，本例中的文件名为 StartupExample.service，所执行命令和文件中的配置内容如下：

创建服务配置文件  
`sudo touch /etc/systemd/system/StartupExample.service`

以下为 StartupExample.service 配置文件的内容

```auto
[Unit]
Description=Startup Example

[Service]
ExecStart=/home/tqh/Documents/Example/StartupScipt.sh

[Install]
WantedBy=multi-user.target

```

尝试手动运行新创建的 service，使用如下命令：

手动运行 StartupExample.service  
`sudo systemctl start StartupExample.service`

查看运行日志  
`systemctl status StartupExample.service`

将服务设置为 enable 状态，再重启计算机，看服务是否能正常运行

删除刚测试服务时创建的文件  
`rm -f /home/tqh/Documents/Example/StartupTouch.txt`

设置服务为 enable 状态，使之能开机运行  
`sudo systemctl enable StartupExample.service`

重启机器  
`systemctl reboot`
