1
0

config.py 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142
  1. import os
  2. import getopt
  3. import sys
  4. import logging
  5. # 定义配置文件目录
  6. # linux
  7. config_path = '/etc/dnspod/ddnsrc'
  8. # windows
  9. if os.name == 'nt':
  10. config_path = 'ddnspod.cfg'
  11. # 配置属性,及其默认参数
  12. cfg = {}
  13. # dnspod 登录配置
  14. cfg["login_token"] = '' # 默认空参数,要求用户必填 格式 'token_id,token' # 登录token
  15. # ddns 基本配置
  16. cfg["sub_domain"] = '' # 默认空参数,要求用户必填 #格式 'www' # 子域名
  17. cfg["domain"] = '' # 默认空参数,要求用户必填 #格式 'domain.com' # 域名
  18. cfg["interval"] = '5' # 最小更新间隔
  19. cfg["record_id"] = '{auto}' # 记录id,程序自动生成
  20. cfg["current_ip"] = '{auto}' # 当前ip,程序自动生成
  21. cfg["email"] = '' # 默认空参数,要求用户必填 #格式 '[email protected]'
  22. # ip 池
  23. cfg["ip_count"] = '1' # 此域名拥有的ip数量,默认为 1 , OpenWrt 玩家可能会有多个IP
  24. cfg["ip_pool"] = '{auto}' # ip 池 ..,程序自动生成
  25. cfg["last_update_time"] = '{auto}' # 上次更新成功时间戳,程序自动生成
  26. def read_config():
  27. # 后面读出的数据会覆盖前面的
  28. read_config_from_file()
  29. read_config_from_env()
  30. read_config_from_argv()
  31. def print_help():
  32. max_key_len = max([len(key) for key in cfg.keys()])
  33. print("ddns.py [-h|...]")
  34. print("命令行方式调用,可用的参数如下:")
  35. for name in cfg.keys():
  36. print(' --%-' + str(max_key_len) + 's <value>' % name)
  37. print("配置优先级: 命令行 > 环境变量 > 配置文件")
  38. print("当前配置文件目录为:%s" % config_path)
  39. def read_config_from_file():
  40. try:
  41. with open(config_path, 'rU') as fp:
  42. for line in fp:
  43. pair = [x.strip() for x in line.split('=')]
  44. if pair[0] and pair[1]:
  45. cfg[pair[0].lower()] = pair[1]
  46. except:
  47. pass
  48. def read_config_from_env():
  49. for key in cfg:
  50. if os.getenv(key) is not None:
  51. cfg[key] = os.getenv(key)
  52. # 从命令行读取参数
  53. def read_config_from_argv():
  54. available_args = [x + "=" for x in cfg.keys()]
  55. try:
  56. opts, _ = getopt.getopt(sys.argv[1:], "h", available_args)
  57. for opt, arg in opts:
  58. if opt == '-h':
  59. print_help()
  60. sys.exit()
  61. if opt.startswith('--'):
  62. pair = [opt[2:], arg]
  63. if pair[0] and pair[1]:
  64. cfg[pair[0].lower()] = pair[1]
  65. except getopt.GetoptError:
  66. print_help()
  67. sys.exit(1)
  68. def save_config():
  69. try:
  70. save_config_to_env()
  71. save_config_to_file()
  72. except NotImplementedError as err:
  73. logging.error("FAILED to save config:" + str(err))
  74. # 不太清楚这个函数能干啥用 = = 写着玩。。。
  75. def save_config_to_env():
  76. for key in cfg:
  77. os.environ[key] = cfg[key]
  78. # 保存配置到文件… 这个函数现在会把配置文件里的注释也删掉……
  79. def save_config_to_file():
  80. max_key_len = max([len(key) for key in cfg.keys()])
  81. try:
  82. with open(config_path, "w+") as f:
  83. f.writelines([
  84. ('%-'+str(max_key_len)+'s=%s\n') % (key, cfg[key])
  85. for key in cfg.keys()
  86. ])
  87. except IOError as err:
  88. logging.error("FAILED to save config to file: " + str(err))
  89. # 检查配置是否齐全
  90. def check_config():
  91. if not (
  92. cfg['login_token'] and
  93. cfg['domain'] and
  94. cfg['sub_domain']):
  95. logging.fatal('config error: need login info')
  96. exit()
  97. try:
  98. if not(int(cfg["interval"])):
  99. logging.fatal('interval error')
  100. exit()
  101. if not(int(cfg["ip_count"])):
  102. logging.fatal('ip_count error')
  103. exit()
  104. except:
  105. logging.fatal('config error')
  106. exit()
  107. logging.info('config checked')
  108. if __name__ == '__main__':
  109. logging.basicConfig(level=logging.INFO,
  110. format='%(levelname)-8s: %(message)s')
  111. # 测试配置文件
  112. logging.info("init cfg: %s" % cfg)
  113. read_config()
  114. logging.info("read cfg: %s" % cfg)
  115. check_config()