定义ip列表文件
cat ip_list.tx
##按照这个格式定义多个ip
192.168.1.1
192.168.1.2
脚本1 :一键telnet ip列表的9100端口可达性
# cat telnet.sh
#!/bin/bash
# Set the file name
filename="ip_list.txt"
# Read the file content into a variable
ip_list=$(cat $filename)
# Declare arrays to store successful and failed IPs
successful_ips=()
failed_ips=()
# Define the expect script in a variable
expect_script='
set timeout 5
puts "ip=$env(IP)"
spawn telnet $env(IP) 9100
expect {
"No route to host" { send_user "$env(IP) failed to connect - No route to host\n"; exit 1 }
timeout { send_user "$env(IP) failed to connect\n"; exit 1 }
"Connected" { send "quit\r"; exit 0 }
}
expect eof
'
# Loop through each IP in the list
for ip in $ip_list
do
# Export the IP as an environment variable
export IP="$ip"
# Run the expect script and check the exit status
if expect -c "$expect_script" > /dev/null 2>&1
then
# If telnet succeeds, add the IP to the successful_ips array
successful_ips+=("$ip")
else
# If telnet fails, add the IP to the failed_ips array
failed_ips+=("$ip")
fi
done
# Print the successful and failed IPs
echo "Successful IPs:"
for ip in "${successful_ips[@]}"; do
echo "$ip"
done
echo "Failed IPs:"
for ip in "${failed_ips[@]}"; do
echo "$ip"
done
脚本2:一键添加多个ip 并且保证格式可用
# cat add_ips.sh
#!/bin/bash
# Set the file names
ip_filename="ip_list.txt"
config_filename="/data/prometheus/prometheus.yml"
# Read the file content into an array
read -a ip_list < $ip_filename
# Get the existing targets line
targets_line=$(grep -m 1 -A1 "job_name: 'aws-pro-ec2-node-exporter'" $config_filename | grep "targets:")
# Extract the existing IPs
existing_ips=$(echo $targets_line | grep -oP "'[^']+'" | tr -d ',')
# Format the new IP addresses for the config file
new_ips=$(printf ", '%s:9100'" "${ip_list[@]}")
# Combine the existing IPs with the new IPs
all_ips="$existing_ips$new_ips"
# Use sed to append the new IPs to the targets line in the config file
sed -i "/targets:/ s#]#$all_ips]#" $config_filename
#docker restart prometheus
脚本3 :一键删除多个ip 并且保证格式可用
# cat del_ips.sh
#!/bin/bash
# 从 ip_list.txt 中读取 IP 列表
ips=$(cat ip_list.txt)
# 创建一个临时文件用于存储修改后的 Prometheus 配置
temp_file=$(mktemp)
# 逐行处理 Prometheus 配置文件
while IFS= read -r line; do
modified_line=$line
# 对每个 IP,删除匹配的部分
for ip in $ips; do
modified_line=$(echo "$modified_line" | sed "s/'$ip:9100', //g" | sed "s/, '$ip:9100'//g" | sed "s/'$ip:9100'//g")
done
# 清除多余的逗号和空格
modified_line=$(echo "$modified_line" | sed "s/, \]/\]/g" | sed "s/\[, /\[/g" | sed "s/\[,/\[/g" | sed "s/,,/,/g")
# 清除开头多余的逗号
modified_line=$(echo "$modified_line" | sed "s/\[,\+/\[/g")
# 将修改后的行写入临时文件
echo "$modified_line" >> "$temp_file"
done < prometheus.yml
# 进一步清理 targets 列表中的多余逗号
sed -i "s/,,*/,/g" "$temp_file"
sed -i "s/,\]/\]/g" "$temp_file"
# 将修改后的配置文件覆盖原始配置文件
mv "$temp_file" prometheus.yml
echo "配置文件已更新。"
#docker restart prometheus