支持设置密码

This commit is contained in:
CN-JS-HuiBai
2026-04-06 20:05:49 +08:00
parent 048582791d
commit bc78a1f601
3 changed files with 141 additions and 2 deletions

66
Prometheus/add_node.sh Normal file
View File

@@ -0,0 +1,66 @@
#!/bin/bash
# This script adds a new node to the Prometheus configuration file
# Supports optional Basic Authentication (username/password)
# Use: sudo ./add_node.sh <SERVER_IP> [USERNAME] [PASSWORD]
if [ -z "$1" ]; then
echo "--- Prometheus Node Adder ---"
read -p "Enter Target IP/Hostname: " SERVER_IP
if [ -z "$SERVER_IP" ]; then
echo "Error: Target IP is required."
exit 1
fi
read -p "Enable Basic Authentication? [y/N]: " ENABLE_AUTH
if [[ "$ENABLE_AUTH" =~ ^[Yy]$ ]]; then
read -p "Enter Username: " USER_NAME
read -s -p "Enter Password: " PASSWORD
echo "" # New line
fi
else
SERVER_IP=$1
USER_NAME=$2
PASSWORD=$3
fi
CONFIG_FILE="/etc/prometheus/prometheus.yml"
# Ensure the script is run with sudo
if [ "$EUID" -ne 0 ]; then
echo "Please run this script with sudo."
exit 1
fi
if [ ! -f "$CONFIG_FILE" ]; then
echo "Prometheus configuration file not found at $CONFIG_FILE"
exit 1
fi
echo "Adding node $SERVER_IP to $CONFIG_FILE..."
# Build the configuration block
JOB_BLOCK="
- job_name: 'nodes_$SERVER_IP'
static_configs:
- targets: ['$SERVER_IP:9100']"
if [ -n "$USER_NAME" ] && [ -n "$PASSWORD" ]; then
echo "Applying basic authentication for user: $USER_NAME"
JOB_BLOCK="$JOB_BLOCK
basic_auth:
username: '$USER_NAME'
password: '$PASSWORD'"
fi
# Append the new job configuration
echo "$JOB_BLOCK" >> "$CONFIG_FILE"
# Restart Prometheus to apply changes
if [ -x "/usr/bin/restart_prometheus" ]; then
/usr/bin/restart_prometheus
else
systemctl restart prometheus
fi
echo "Done. node $SERVER_IP added. Prometheus restarted."