自学内容网 自学内容网

Linux设置开机自动执行脚本 rc-local

使用/etc/rc.local

1、启动rc-local服务

首先授予执行权限

chmod +x /etc/rc.d/rc.local

设置开启自启并启动

sudo systemctl enable rc-local
sudo systemctl start rc-local

查看状态

sudo systemctl status rc-local

在这里插入图片描述

2、编写要执行的脚本

vim /home/start.sh

#!/bin/bash

echo "--------开始--------"
sleep 20
echo "===================="

# 定义目标主机和端口
HOST1="199.10.100.81"
PORT1="8848"

HOST2="199.10.100.81"
PORT2="3306"

export JAVA_HOME=/usr/local/jdk-17.0.11
export JRE_HOME=${JAVA_HOME}/jre
export CLASSPATH=.:${JAVA_HOME}/lib:${JRE_HOME}/lib
export PATH=${JAVA_HOME}/bin:$PATH

# 尝试通过Telnet连接第一个目标,直到连接成功
echo "Trying to connect to $HOST1:$PORT1..."
while true; do
    if timeout 5 telnet $HOST1 $PORT1 < /dev/null | grep -q "Connected to"; then
        echo "Telnet connection to $HOST1:$PORT1 successful."
        break
    else
        echo "Telnet connection to $HOST1:$PORT1 failed, retrying in 5 seconds..."
        sleep 5
    fi
done

# 尝试通过Telnet连接第二个目标,直到连接成功
echo "Trying to connect to $HOST2:$PORT2..."
while true; do
    if timeout 5 telnet $HOST2 $PORT2 < /dev/null | grep -q "Connected to"; then
        echo "Telnet connection to $HOST2:$PORT2 successful."
        break
    else
        echo "Telnet connection to $HOST2:$PORT2 failed, retrying in 5 seconds..."
        sleep 6
    fi
done

# 执行启动服务命令
nohup java -jar test.jar > /nohup.out &
# 检查命令执行是否成功
if [ $? -eq 0 ]; then
    echo "服务启动成功"
else
    echo "服务启动失败"
fi

编辑启动文件

编辑启动文件

vim /etc/rc.local

在这里插入图片描述

重启linux服务器会自动执行脚本


原文地址:https://blog.csdn.net/qq_39766779/article/details/143860647

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!