nacos-config.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. #!/usr/bin/env python3
  2. # -*- coding: UTF-8 -*-
  3. import http.client
  4. import sys
  5. import getopt as opts
  6. import urllib.parse
  7. import re
  8. def get_params() -> dict:
  9. params = {
  10. '-h': '127.0.0.1',
  11. '-p': '8848',
  12. '-t': '',
  13. '-g': 'SEATA_GROUP',
  14. '-u': '',
  15. '-w': ''
  16. }
  17. inputs, args = opts.getopt(sys.argv[1:], shortopts='h:p:t:g:u:w:')
  18. for k, v in inputs:
  19. params[k] = v
  20. print(params)
  21. return params
  22. def error_exit():
  23. print('python nacos-config.py [-h host] [-p port] [-t tenant] [-g group] [-u username] [-w password]')
  24. exit()
  25. def get_pair(line: str) -> tuple:
  26. res = re.match(r"([\.\w]+)=(.*)",line)
  27. return res.groups() if res is not None else ['','']
  28. headers = {
  29. 'content-type': "application/x-www-form-urlencoded"
  30. }
  31. hasError = False
  32. params = get_params()
  33. url_prefix = f"{params['-h']}:{params['-p']}"
  34. tenant = params['-t']
  35. username = params['-u']
  36. password = params['-w']
  37. group = params['-g']
  38. url_postfix_base = f'/nacos/v1/cs/configs?group={group}&tenant={tenant}'
  39. if username != '' and password != '':
  40. url_postfix_base += f'&username={username}&password={password}'
  41. if url_prefix == ':':
  42. error_exit()
  43. for line in open('../config.txt'):
  44. pair = get_pair(line.rstrip("\n"))
  45. if len(pair) < 2 or pair[0] == '' or pair[0].startswith("#") or pair[1] == '':
  46. continue
  47. url_postfix = url_postfix_base + f'&dataId={urllib.parse.quote(str(pair[0]))}&content={urllib.parse.quote(str(pair[1])).strip()}'
  48. conn = http.client.HTTPConnection(url_prefix)
  49. conn.request("POST", url_postfix, headers=headers)
  50. res = conn.getresponse()
  51. data = res.read().decode("utf-8")
  52. if data != "true":
  53. hasError = True
  54. print(f"{pair[0]}={pair[1]} {data if hasError else 'success'}")
  55. if hasError:
  56. print("init nacos config fail.")
  57. else:
  58. print("init nacos config finished, please start seata-server.")