运行 Elasticsearch python 脚本时收到 401 错误状态

问题描述 投票:0回答:1

我正在编写一个 python 脚本,我需要使用我的 Elasticsearch 凭据来删除 doc.count 为 0 的所有索引。

我创建了一个测试用户,该用户已被授予对以名称“test”开头的所有索引进行delete_index 的权限。

这里是部分帮助代码:

ELASTIC_SEARCH_USER = _secret_client.get_secret("Elastic--User").value
ELASTIC_SEARCH_PASSWORD = _secret_client.get_secret("Elastic--Password").value
ELASTIC_SEARCH_URL = _secret_client.get_secret("Elastic--URL").value

elastic_auth_uri = f"https://{ELASTIC_SEARCH_URL}/security/_authenticate"
response = requests.get(elastic_auth_uri, auth=(ELASTIC_SEARCH_USER, ELASTIC_SEARCH_PASSWORD), verify=False)
              
# Defining a params dict for the paramaters to be sent to the API
search_url_ending = "_cat/indices/test*"
url_ending_deletion = "_cat/indices"

params_dict = {
"h":"index,docs.count",
"s":"docs.count:asc",
"format":"json"
}

# Elastic authentication to list the indices
elastic_console = f"https://{ELASTIC_SEARCH_URL}/{search_url_ending}"
print(elastic_console)
getRequestElasticSearch = requests.get(elastic_console, auth=(ELASTIC_SEARCH_USER, ELASTIC_SEARCH_PASSWORD), verify=False, params=params_dict)
content = json.loads(getRequestElasticSearch.text)

# Elastic url required to index deletion
elastic_console_delete = f"https://{ELASTIC_SEARCH_URL}/"
elasticsearch_url = requests.get(elastic_console_delete, auth=(ELASTIC_SEARCH_USER, ELASTIC_SEARCH_PASSWORD), verify=False)
print(elasticsearch_url.url)


# List indices with doc.count 0
for index in content:
    indiciesList = index
    collectdoccount = index['docs.count']
    search_int = int(collectdoccount)
    if search_int == 0:
       print(index['index'] , index['docs.count'])
       index_name = index['index']
       delete_url = f"{elastic_console_delete}{index_name}"
       response = requests.delete(delete_url)
       if  response.status_code == 200:
           print(index['index'] , index['docs.count'])
       if  response.status_code != 200:
           print (index['index'] , "index not deleted")
           print(response.content)   

我可以列出索引,但删除它们会出现 401 状态错误。

错误是:

b'{"error":{"root_cause":[{"type":"security_exception","reason":"操作 [indices:admin/delete] 需要身份验证","header":{"WWW-Authenticate" :["基本领域=\"security\" 字符集=\"UTF-8\"","承载领域=\"security\"","ApiKey"]}}],"type":"security_exception","原因":"操作 [索引:管理/删除] 需要身份验证","标头":{"WWW-Authenticate":["基本领域=\"安全\" 字符集=\"UTF-8\"","承载领域=\"安全\"","ApiKey"]}},"状态":401}'

我不完全理解这个错误的含义。根据我在 Google 上读到的内容,我没有提供足够的身份验证凭据来完成此删除请求。

有人可以帮助我解决我的困境吗?

authentication elasticsearch python-requests
1个回答
0
投票

您的 Elasticsearch 似乎已启用安全性,并且错误消息

action [indices:admin/delete] requires authentication
指出您需要为该请求提供用户名密码。

您只需要对删除请求使用

auth
参数,就像之前使用
get
那样。

requests.delete(delete_url, auth=(ELASTIC_SEARCH_USER, ELASTIC_SEARCH_PASSWORD))
© www.soinside.com 2019 - 2024. All rights reserved.