【Linux】设置程序开机启动

Posted by 西维蜀黍 on 2021-08-21, Last Modified on 2022-03-25

修改开机启动文件 - /etc/rc.local

  • 或者/etc/rc.d/rc.local

  • 修改rc.local文件,在 exit 0 前面加入以下命令

    # mysql开机启动
    /etc/init.d/mysqld start                                         
    /bin/bash /server/scripts/test.sh >/dev/null 2>/dev/null
    
  • 最后修改rc.local文件的执行权限

    [root@localhost ~]# chmod +x  /etc/rc.local
    [root@localhost ~]# chmod 755 /etc/rc.local
    

添加至 /etc/profile.d/

将写好的脚本(.sh文件)放到目录 /etc/profile.d/ 下,系统启动后就会自动执行该目录下的所有shell脚本。

修改权限

$ sudo chmod 755 ./ha.sh

/etc/profile 文件

*/etc/profile*:对所有用户生效;此文件为系统的每个用户设置环境信息,当用户第一次登录时,该文件被执行;并从/etc/profile.d目录的配置文件中搜集shell的设置

/etc/init.d 文件夹

Put a script containing the command in your /etc directory. Create a script such as “startup.sh” using your favorite text editor.

$ sudo vim startup.sh
#! /bin/sh
nohup /srv/homeassistant/bin/hass -c /home/homeassistant/.homeassistant >/dev/null 2>&1 &
exit 0

# Since the chkconfig command is not available on Debian systems, update-rc.d can be used as an alternative there:
$ update-rc.d  ha.sh defaults

Save the file in your /etc/init.d/ directory.

Change the permissions of the script (to make it executable):

$ sudo chmod +x /etc/init.d/mystartup.sh

Add a Service

We can now add a user to handle the exporting of our metrics. This user will be a system user (-r) who will be unable to get a shell (-s /bin/false)

sudo useradd -rs /bin/false node_exporter

Setting up the Node Exporter as a service

Now we can create a service for the node exporter. We can do this by creating a file

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

with the following contents

[Unit]
Description=Node Exporter
After=network.target

[Service]
# don't need the following two if don't wanna specify an user
# User=node_exporter
# Group=node_exporter
Type=simple
ExecStart=/usr/local/bin/node_exporter
# or
# ExecStart=/bin/bash -c "nohup /srv/homeassistant/bin/hass -c /home/homeassistant/.homeassistant >/dev/null 2>&1 &"

[Install]
WantedBy=multi-user.target

Start the service

We can now start the service, enable it so it starts on boot and view the status to make sure it started correctly

sudo systemctl daemon-reload
sudo systemctl start node_exporter
sudo systemctl enable node_exporter
sudo systemctl status node_exporter

If all goes well, you can access the metrics at

http://<server-IP>:9100/metrics

crontab

每次开机的时候都执行的一个脚本

$ sudo crontab -e
@reboot sh /home/user/test.sh

Reference