1. 实现目标

想要达到的指标是:当在浏览器向http://192.168.11.254:3090/au...这个地址发动GET申请后可能主动登入Grafana

2. 实现思路

须要额定开发一个API解决来自用户的登录申请,实现思路次要有2点:

  1. 通过代码登录grafana,失去cookie
  2. 携带这个cookie做重定向

须要留神的中央:为了缩小麻烦,这个API程序须要和grafana服务在同一台机器上跑起来,不然会有跨域的问题,跨域的话就不好携带这个cookie了,也不是不能实现,而是解决起来还是比拟麻烦。

3. 实现剖析

  1. 剖析cookie

应用非法的账号密码手动登录胜利后,服务端会向浏览器写入cookie,key是grafana_session,看下图:

  1. 剖析登录表单

给到后端的明码字段是user

给到后端的明码字段是password

解决认证的path是/login(其实在地址栏就能够看到,但为了进一步确认还是要剖析一下)

该晓得的都晓得了,上面开始写代码实现这个解决登录申请的API,分享用go和python的实现

4. go的实现

package mainimport ( "io/ioutil" "log" "net/http" "strings")const login_url = "http://192.168.11.254:3000/login"const home_url = "http://192.168.11.254:3000/"// 应用admin账号登陆获取cookie,我这里的明码是1qaz#EDCfunc GetSession(url string) string { method := "POST"     payload := strings.NewReader(`{` + " " + ` "user": "admin",` + " " + ` "password": "1qaz#EDC"` + " " + `}`) client := &http.Client{} req, err := http.NewRequest(method, url, payload) if err != nil {  log.Println(err) } req.Header.Add("Content-Type", "application/json") res, err := client.Do(req) if err != nil {  log.Println(err) } defer res.Body.Close() body, err := ioutil.ReadAll(res.Body) if err != nil {  log.Println(err) } log.Println(string(body)) cookie := res.Cookies()[0].Value return cookie}// 处理函数func AutoLogin(w http.ResponseWriter, r *http.Request) { session := GetSession(login_url) if r.Method == "GET" {        // 向浏览器写cookie  cookie := http.Cookie{   Name:  "grafana_session",   Value: session,  }  http.SetCookie(w, &cookie)        // 重定向  http.Redirect(w, r, home_url, http.StatusMovedPermanently) }}// 拉起http服务和做路由func Api() { http.HandleFunc("/auto_login", AutoLogin) err := http.ListenAndServe(":3080", nil) if err != nil {  log.Println("ListenAndserve:", err) }}func main() {    Api()}

5. python的实现

import jsonimport requestsfrom flask import Flask, request, redirect, make_responseapp = Flask(__name__)login_url = "http://192.168.11.254:3000/login"home_url = "http://192.168.11.254:3000/"def get_session():  payload = json.dumps({    "user": "admin",    "password": "1qaz#EDC"  })  headers = {    'Content-Type': 'application/json'  }  response = requests.request("POST", login_url, headers=headers, data=payload)  cookie = response.cookies.items()[0][1]  return cookie@app.route('/auto_login', methods=['GET'])def auto_login():  if request.method == 'GET':    cookie = get_session()    response = make_response(redirect(home_url))    response.set_cookie('grafana_session', cookie)    return responseif __name__ == "__main__":  app.run("0.0.0.0", 3080)

6. 测试成果

代码写完了,上面测试测试成果,go和python的实现,最终达到的目标是一样的,请别离自行测试哈。

在浏览器拜访:http://192.168.11.254:3090/au...

实现主动登录

写在最初:在go的实现中,第一次登入后且失常登记,再次通过API登录时,重定向到指标地址时向浏览器写入cookie会失败,导致间接去到登录页面,革除浏览器的历史记录和cookie(次要是清理掉cookie)啥的就能失常进入,这个问题我还在深刻排查。晓得怎么解决的盆友麻烦私聊我,感激不尽。

本文转载于(喜爱的盆友关注咱们哦):https://mp.weixin.qq.com/s/FN...