使用Python在Elasticsearch查询中进行用户身份验证

huus2vyu  于 2023-10-17  发布在  ElasticSearch
关注(0)|答案(7)|浏览(262)

我使用Python的Elastisearch。我的代码看起来有点像这样:

from elasticsearch import Elasticsearch

if __name__ == '__main__': 
    index="IndexPosition"
    es=Elasticsearch(['https://localhost:8080'])
    res = es.search(index='{0}'.format(index), doc_type="log",size=1000, from_=0, body={ "query": {
    "match": {
      
        ...Match condition
      }
    }
  }})

现在,由于架构的变化,在elasticsearch中添加了用户身份验证。让我们假设username-user和password-pass。我如何在查询中传递用户名和密码..?

r9f1avp5

r9f1avp51#

您需要将用户名和密码传递给Elasticsearch对象,如下所示:
es = Elasticsearch(['http://localhost:8080'], http_auth=('user', 'pass'))

z3yyvxxp

z3yyvxxp2#

您可以在url中输入用户名和密码:
例如:
用户名:弹性
密码:changeme

es = Elasticsearch(hosts="http://elastic:changeme@localhost:9200/")

使用CURL

curl -X GET "elastic:changeme@localhost:9200/"
lvmkulzt

lvmkulzt3#

在Elasticsearch 8.x中,http_auth参数被弃用,请分别使用basic_authbearer_auth
Elasticsearch >= 8.x基本认证示例:

es = Elasticsearch(['https://localhost:8080'], basic_auth=('user', 'pass'))

Elasticseach < 8.x基本认证示例:

es = Elasticsearch(['http://localhost:8080'], http_auth=('user', 'pass'))
m1m5dgzv

m1m5dgzv4#

es = Elasticsearch([{'host': 'localhost', 'port': '8080'}], http_auth=('user', 'pass'))
11dmarpk

11dmarpk5#

是,使用es = Elasticsearch(hosts="http://username:password@es-endpoint:es-port/")
在es版本7.7.1中测试成功

k5hmc34c

k5hmc34c6#

你可以用下面的主机url配置连接elasticsearch

es = Elasticsearch(hosts="http://user:pass@localhost:9200/")
oxiaedzo

oxiaedzo7#

我在Docker上运行ElasticSearch。ElasticSearch v8.10自动启用额外的安全性(例如,使用证书)。可以通过运行以下命令将证书复制到本地计算机:
docker cp elasticsearch:/usr/share/elasticsearch/config/certs/http_ca.crt .
如果不是Docker:
cp /usr/share/elasticsearch/config/certs/http_ca.crt .
参见:Verifying HTTPS with CA certificates & Run Elasticsearch in Docker - Start a single-node cluster (7-8)

from elasticsearch import Elasticsearch

# Password for the 'elastic' user generated by Elasticsearch
ELASTIC_PASSWORD = "<elastic_password>"

es = Elasticsearch(
    "https://localhost:9200",
    ca_certs="/path/to/http_ca.crt",
    basic_auth=("elastic", ELASTIC_PASSWORD)
)

# Successful response!
es.info()

相关问题