Bootstrap

ElasticSearch操作之重置密码脚本

ElasticSearch操作之重置密码脚本

在这里插入图片描述

#!/bin/bash
# 使用样例 ./ES密码重置.sh 旧密码 新密码

# 输入旧密码
es_old_password=$1

# 设置新的密码变量
es_password=$2

# 正确响应
es_reponse='{"acknowledged":true}'

# 检查Elasticsearch是否在运行
if pgrep -f elasticsearch > /dev/null; then
    echo "Elasticsearch is running, proceeding with password setup."
else
    echo "Elasticsearch is not running. Please start Elasticsearch and try again."
    exit 1
fi
# 清除原来密码
# 发送请求并保存响应状态码
response=$(curl -X DELETE -u elastic:"$es_old_password" "http://127.0.0.1:9200/.security-7")

echo "清除原来密码"
echo "$response"

# 检查响应状态码
if [ "$response" != $es_reponse ]; then
    echo "请求失败,终止操作"
    exit 0
fi
echo "请求成功,继续下一步操作"

# 进入Elasticsearch的bin目录
cd /home/zfes/elasticsearch/bin || { echo "Elasticsearch bin directory not found."; exit 1; }

# 使用expect脚本自动输入密码
/usr/bin/expect <<EOF
# 设置永不超时
set timeout -1
# 详细内容打印
# exp_internal 1
spawn ./elasticsearch-setup-passwords interactive

# 忽略不相关的输出
expect {
    "N\]" { send "y\r"; exp_continue }
    -re "elastic\]:" { send "$es_password\r" ; exp_continue }
    -re "elastic\]:" { send "$es_password\r"; exp_continue }
    -re "kibana_system\]:" { send "$es_password\r"; exp_continue }
    -re "kibana_system\]:" { send "$es_password\r"; exp_continue }
    -re "logstash_system\]:" { send "$es_password\r"; exp_continue }
    -re "logstash_system\]:" { send "$es_password\r"; exp_continue }
    -re "beats_system\]:" { send "$es_password\r"; exp_continue }
    -re "beats_system\]:" { send "$es_password\r"; exp_continue }
    -re "apm_system\]:" { send "$es_password\r"; exp_continue }
    -re "apm_system\]:" { send "$es_password\r"; exp_continue }
    -re "remote_monitoring_user\]:" { send "$es_password\r"; exp_continue }
    -re "remote_monitoring_user\]:" { send "$es_password\r"; exp_continue }
}

expect eof
EOF

echo "Password has been updated for all users."

;