cosmo/terminal/tools/bind_code.py

45 lines
1.5 KiB
Python
Executable File
Raw Permalink Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

#!/usr/bin/env python3
"""用命令行完成网页端那一步:登录账号 -> 输入屏幕上的 6 位码 -> 绑定终端。
用法:
python3 terminal/tools/bind_code.py <6位码> [用户名] [密码] [--api URL]
默认账号 pepperdog/cosmo,默认后端 http://127.0.0.1:8000/api
"""
import argparse
import json
import sys
import urllib.error
import urllib.request
def post(url, payload, token=None):
data = json.dumps(payload).encode()
req = urllib.request.Request(url, data=data, headers={"Content-Type": "application/json"})
if token:
req.add_header("Authorization", "Bearer " + token)
with urllib.request.urlopen(req, timeout=15) as r:
body = r.read().decode()
return r.status, (json.loads(body) if body else {})
def main():
ap = argparse.ArgumentParser()
ap.add_argument("code")
ap.add_argument("username", nargs="?", default="pepperdog")
ap.add_argument("password", nargs="?", default="cosmo")
ap.add_argument("--api", default="http://127.0.0.1:8000/api")
a = ap.parse_args()
st, login = post(a.api + "/auth/login", {"username": a.username, "password": a.password})
token = login.get("access_token") or login.get("token")
if not token:
sys.exit("login failed: %s %s" % (st, login))
st, dev = post(a.api + "/devices/bind", {"code": a.code}, token)
print("HTTP %s -> %s" % (st, json.dumps(dev, ensure_ascii=False)))
return 0 if st < 400 else 1
if __name__ == "__main__":
sys.exit(main())