使用Systemd把自作脚本服务化(加入开机启动)

Systemd的出现,使得自己编写的脚本可更容易的添加进系统服务,进而实现开机启动。

例如,我们可以把最简单的hello world脚本进行扩展,将其添加进系统服务,使之开机自启动。

1、编写脚本

编写一个 /opt/hello.sh 脚本

sudo vim /opt/hello.sh
/opt/hello.sh
#!/bin/bash
while true
do
   echo hello world >> /tmp/hello.log
   sleep 1
done

赋予执行权限。

sudo chmod 0755 /opt/hello.sh

2、在/etc/systemd/system/ 下创建Unit定义文件

sudo vim /etc/systemd/system/hello.service

内容如下

/etc/systemd/system/hello.service
[Unit]
Description = hello daemon

[Service]
ExecStart = /opt/hello.sh
Restart = always
Type = simple

[Install]
WantedBy = multi-user.target

ExecStart中填写想要执行的脚本。
Restart = always 是指进程或服务意外故障的时候可以自动重启的模式。

※Unit文件的详细写法会另外给出。

(Type = simple 指默认的选项没有必要填写,或可理解成其余选项均为系统默认。)

3、把Unit添加进Service

使用systemctl list-unit-files --type=service命令,出现如下图所示即为正常。

$ sudo systemctl list-unit-files --type=service | grep hello
hello.service                              disabled

OK!

4、enable服务后使之start

之后系统将以一般服务的形式对待它。

# 开机自启动on
$ sudo systemctl enable hello
# 单次启动
$ sudo systemctl start hello

运行状态确认

$ sudo systemctl status hello

hello.service - hello daemon
   Loaded: loaded (/etc/systemd/system/hello.service; enabled)
   Active: active (running) since 2018-05-19 09:02:19 UTC; 2min 54s ago
 Main PID: 551 (hello.sh)
   CGroup: /system.slice/hello.service
           ├─ 551 /bin/bash /opt/hello.sh
           └─2062 sleep 1

 6月 19 09:02:19 localhost.localdomain systemd[1]: Started hello daemon.

打开日志文件看看脚本是否正常运作。

[vagrant@localhost ~]$ tailf /tmp/hello.log
hello world
hello world
hello world
hello world
hello world

成功了!

5、重启机器,查看服务是否正常自动启动

$ sudo reboot

重启后,如正常显示hello服务即为操作政工。

本文来自投稿,不代表Linux运维部落立场,如若转载,请注明出处:http://www.178linux.com/100909

(27)
无名无名
上一篇 2018-06-12 15:40
下一篇 2018-06-12 15:45

相关推荐

  • awk的使用

    awk -v设置变量 -F 指定分隔符 内置变量 FS:输入字段分隔符,默认为空白字符,读入内容的分隔符 OFS:输出字段的分隔符 RS:指定行(记录)分隔符 ORS:输出记录分隔符 NF:字段数量 NR:记录的数量 ARGC:命令行参数的个数 ARGV:数组,保存的是命令行所有的参数   例1:不依赖文件和标准输入 [root@centos7 ~…

    Linux笔记 2018-05-21
  • 文件实时查找工具-find

    find:命令 实时查找工具,通过遍历指定路径完成文件查找 工作特点:查找速度慢,精确查找,实时查找,可能只搜索用户具备读取和执行的目录 用法:  find【OPTION]…[查找路径】【查找条件】【处理动作】 查找路径:指定具体目标路径;默认为当前目录查找条件:指定的查找标准,可以文件名、大小、类型、权限等标准进行;默认为找出指定路径下的所有文…

    2018-04-13
  • N31第四周作业

    本周(7.9–7.15)第4周 1、复制/etc/skel目录为/home/tuser1,要求/home/tuser1及其内部文件的属组和其它用户均没有任何访问权限。 [a@localhost ~]$ sudo cp -r /etc/skel /home/tuser1 [a@localhost ~]$ sudo chmod -R go= /hom…

    Linux笔记 2018-07-16
  • DNS服务

    1、相关原理概念
    2、配置主DNS服务器
    3、配置从DNS服务器

    2018-06-03
  • rpm与yum

    rpm yum sed and crontab

    Linux笔记 2018-06-11