systemd 开机启动服务

2024-03-01 20:49:05 浏览数 (1)

代码语言:shell复制
#!/bin/bash 
# systemd 开机启动服务

os_release()
{
    if [ $USER = "root" ]
    then 
        sudoc=" "
        # 判断字符串的等号要加空格,否则无法判断
    else
        sudoc="sudo"
        echo "当前为普通用户,需要输入root 密码...  $sudoc"
        $sudoc date   ;
    fi

    xitong=` cat /etc/os-release  | grep -w ID | awk -F"=" '{print $2}' | sed "s/"//g" `
    case "$xitong" in
        "centos" ) aptc="yum" ; dpkgc="rpm -qa " ; echo "当前是 centos 系统"   ;;
        "ubuntu" ) aptc="apt" ; dpkgc="dpkg -l " ; echo "当前是 ubuntu 系统"   ;;
    esac
    
}
os_release

kaiji_web_service(){
# ubuntu  以 systemd 服务方式,自动启动服务软件 

   systemdDir="/usr/lib/systemd/system"
   ServiceName="eisc_web_start.service"
   cd $systemdDir ; $sudoc touch $ServiceName ; $sudoc chmod 777 $ServiceName 
#----- 写入 start.service 服务 -----#
   echo "
[Unit] 
Description=start web
 
[Service]
Type=forking
ExecStart=/etc/init.d/shell/start.sh
ExecReload=/bin/kill -SIGHUP $MAINPID
ExecStop=/bin/kill -SIGINT $MAINPID

[Install] 
WantedBy=multi-user.target
   " > $ServiceName

   $sudoc apt install dos2unix -y
   $sudoc dos2unix $ServiceName
   # 转为 unix 格式,否则可能出现字符乱码

   $sudoc chmod 644 $ServiceName
   $sudoc systemctl daemon-reload
   $sudoc systemctl disable $ServiceName
   $sudoc systemctl enable $ServiceName

cd 

}

kaiji_start_web_sh(){

    $sudoc mkdir -p /etc/init.d/shell/ ; $sudoc chmod 777 /etc/init.d/shell/ 

    if [ ! -e /etc/init.d/shell/openvpn_connect.sh ]
    then 
        wget eisc.cn/file/ubuntu/shell/server/openvpn_connect.sh -O /etc/init.d/shell/openvpn_connect.sh
	fi

    read -p "是否继续进行配置 systemd 开机启动? y/n: " kaijisz
    if [ "$kaijisz" = "y" ]
    then
    kaiji_web_service
    # 启动这个函数
    $sudoc mkdir -p $installdir/shell ; $sudoc chmod 777 -R $installdir/shell

    # 将脚本授权给 root 用户

    echo "#!/bin/bash
        # bash 解释器 一定要在第一行 开头写,否则下面脚本不执行,开机启动不成功。 由于是 service服务,因此此脚本是 root 用户执行

        #mount -t nfs -o rw,hard,intr 192.168.122.1:/datadisk/eisc /datadisk/eisc/ ; sleep 2

        /datadisk/eisc/server/nginx/nginx199/sbin/nginx &
        /datadisk/eisc/server/gitea/gitea &

        touch $HOME/log_start_web.txt ; chmod 777 $HOME/log_start_web.txt
    " > /etc/init.d/shell/start.sh
      

   echo "#----------------- 查看写入的开机启动脚本 -------------------#"
   cat /etc/init.d/shell/start.sh

   $sudoc chmod  x /etc/init.d/shell/*  
   $sudoc chown -R root:root /etc/init.d/shell/*  ; $sudoc chmod 777 -R /etc/init.d/shell/*

  else
    echo "[ok]目前不配置systemd "
  fi
}
kaiji_start_web_sh

0 人点赞