使用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

相关推荐

  • 路由设置

    路由

    Linux笔记 2018-05-05
  • 日志管理

    日志介绍 日志配置 日志管理 远程日志 基于MYSQL的日志

    Linux笔记 2018-06-25
  • 计算机原理与Linux基础

    计算机的组成及功能 1、其实计算机的组织分为内部设备和外部设备, 内部设备:         CPU:运算器、寄存器、缓存         存储器:内存,RAM(Random Access Memory)         控制器:控制器是整个计算机系统的控制中心,它指挥计算机各部分协调地工作,保证计算机按照预先规定的目标和步骤有条不紊地进行操作及处理。 外部…

    Linux笔记 2018-05-13
  • nginx实现请求转发

    反向代理适用于很多场合,负载均衡是最普遍的用法。 nginx 作为目前最流行的web服务器之一,可以很方便地实现反向代理。 nginx 反向代理官方文档: NGINX REVERSE PROXY 当在一台主机上部署了多个不同的web服务器,并且需要能在80端口同时访问这些web服务器时,可以使用 nginx 的反向代理功能: 用 nginx 在80端口监听所…

    Linux笔记 2018-07-08
  • 第七周

    总结

    Linux笔记 2018-05-13
  • ansible httpd

    卸载服务ansible all -m shell -a ‘yum -y remove nginx’ 检查用户 组 uid gidansible all -m shell -a ‘getent passwd nginx’ansible all -m shell -a ‘getent group ngi…

    Linux笔记 2018-07-23