Please enable Javascript to view the contents

Curl操作Elasticsearch

 ·  ☕ 1 分钟 · 👀... 阅读
1
2
➜  ~ curl -X GET http://localhost:9200
curl: (52) Empty reply from server

返回这样的结果,有安全策略或版本大于7时默认开启,需要改用https协议

1
2
3
➜  ~ curl -X GET "https://localhost:9200"
curl: (60) SSL certificate problem: self signed certificate in certificate chain
More details here: https://curl.se/docs/sslcerts.html

提示需要证书,增加--insecure选项忽略,但不建议

1
2
➜  ~ curl --insecure -X GET "https://localhost:9200"
{"error":{"root_cause":[{"type":"security_exception","reason":"missing authentication credentials for REST request [/]","header":{"WWW-Authenticate":["Basic realm=\"security\" charset=\"UTF-8\"","Bearer realm=\"security\"","ApiKey"]}}],"type":"security_exception","reason":"missing authentication credentials for REST request [/]","header":{"WWW-Authenticate":["Basic realm=\"security\" charset=\"UTF-8\"","Bearer realm=\"security\"","ApiKey"]}},"status":401}

增加证书,证书在启动es后,默认会在config目录新增证书文件夹,使用--cacert选项增加证书

1
2
➜  elasticsearch-8.1.3 curl --cacert config/certs/http_ca.crt -X GET "https://localhost:9200"
{"error":{"root_cause":[{"type":"security_exception","reason":"missing authentication credentials for REST request [/]","header":{"WWW-Authenticate":["Basic realm=\"security\" charset=\"UTF-8\"","Bearer realm=\"security\"","ApiKey"]}}],"type":"security_exception","reason":"missing authentication credentials for REST request [/]","header":{"WWW-Authenticate":["Basic realm=\"security\" charset=\"UTF-8\"","Bearer realm=\"security\"","ApiKey"]}},"status":401}

Finnally 但提示需要凭证,添加凭证,用户名和密码

1
2
➜  elasticsearch-8.1.3 curl --cacert config/certs/http_ca.crt -u elastic -X GET "https://localhost:9200"
Enter host password for user 'elastic':

将密码直接同命令一起传入,不建议

1
➜  elasticsearch-8.1.3 curl --cacert config/certs/http_ca.crt -u elastic:xb_hOsOhy3sgTRGHwow4 -X GET "https://localhost:9200"

发送post请求(增加-d选项,跟上json字符串),提示协议头不支持

1
2
➜  elasticsearch-8.1.3 curl --cacert config/certs/http_ca.crt -u elastic:xb_hOsOhy3sgTRGHwow4 -X GET https://localhost:9200/products/_search -d '{"query":{"match_all":{}}}'
{"error":"Content-Type header [application/x-www-form-urlencoded] is not supported","status":406}

-H选项 增加协议头,使用json格式

1
➜  elasticsearch-8.1.3 curl --cacert config/certs/http_ca.crt -u elastic:xb_hOsOhy3sgTRGHwow4 -X GET -H "Content-type:application/json" https://localhost:9200/products/_search -d '{"query":{"match_all":{}}}'
分享
您的鼓励是我最大的动力
alipay QR Code
wechat QR Code

Jason Tan
作者
Jason Tan
Developer