Shell:修改目录所属者,组并重启进程

注意:请检查对应目录下是否有start.sh

#!/bin/bash

# 目标用户和组
USER="your_user"
GROUP="your_group"

# node_exporter 的目录路径
NODE_EXPORTER_DIR="/path/to/node_exporter"
START_SCRIPT="$NODE_EXPORTER_DIR/start.sh"

# 检查目标用户和组是否存在
if id "$USER" &>/dev/null; then
    echo "User $USER exists."
else
    echo "User $USER does not exist. Please create the user first."
    exit 1
fi

if getent group "$GROUP" &>/dev/null; then
    echo "Group $GROUP exists."
else
    echo "Group $GROUP does not exist. Please create the group first."
    exit 1
fi

# 修改 node_exporter 目录及文件的用户和组(仅在必要时提权)
echo "Checking ownership of $NODE_EXPORTER_DIR..."
CURRENT_OWNER=$(stat -c "%U:%G" "$NODE_EXPORTER_DIR")

if [ "$CURRENT_OWNER" != "$USER:$GROUP" ]; then
    echo "Changing ownership of $NODE_EXPORTER_DIR to $USER:$GROUP..."
    sudo chown -R $USER:$GROUP "$NODE_EXPORTER_DIR"
    if [ $? -eq 0 ]; then
        echo "Ownership successfully changed to $USER:$GROUP."
    else
        echo "Failed to change ownership. Please check the directory path and permissions."
        exit 1
    fi
else
    echo "Ownership already set to $USER:$GROUP. No changes needed."
fi

# 重启 node_exporter 进程
echo "Restarting node_exporter..."

# 停止现有的 node_exporter 进程(如果有的话)
sudo pkill -f node_exporter

# 等待几秒以确保进程已停止
sleep 2

# 直接执行 start.sh 以重启 node_exporter,不切换用户,也不提权
cd "$NODE_EXPORTER_DIR"
./start.sh

# 确认 node_exporter 是否已启动
if pgrep -f node_exporter > /dev/null; then
    echo "node_exporter successfully restarted."
else
    echo "Failed to restart node_exporter."
    exit 1
fi