proxy.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. #!/usr/bin/env python3
  2. import os
  3. import sys
  4. from subprocess import check_output, list2cmdline
  5. cwd = os.path.dirname(__file__)
  6. ssh_agent = os.path.join(cwd, "ssh-agent.py")
  7. user_proxy = os.environ.get("CONFIG_PROXY", os.path.expandvars("$HOME/.config/proxy"))
  8. def get_http_proxy():
  9. if "DEFAULT_PROXY" in os.environ:
  10. return os.environ["DEFAULT_PROXY"]
  11. if os.path.isfile(user_proxy):
  12. return check_output(user_proxy).decode("utf-8").strip()
  13. raise Exception("Not found, Proxy configuration")
  14. def make_proxies(url: str):
  15. proxies = {"%s_PROXY" % _: url for _ in ("HTTP", "HTTPS", "FTP", "RSYNC", "ALL")}
  16. proxies.update({name.lower(): value for (name, value) in proxies.items()})
  17. proxies["GIT_SSH"] = ssh_agent
  18. return proxies
  19. def merge(mapping: dict):
  20. return ("%s=%s" % _ for _ in mapping.items())
  21. class CommandSet:
  22. proxies = make_proxies(get_http_proxy())
  23. aliases = {
  24. _: "env __SSH_PROGRAM_NAME__=%s %s" % (_, ssh_agent)
  25. for _ in ("ssh", "sftp", "scp", "slogin", "ssh-copy-id")
  26. }
  27. def enable(self):
  28. cmdline("export", *merge(self.proxies))
  29. cmdline("alias", *merge(self.aliases))
  30. def disable(self):
  31. cmdline("unset", *self.proxies.keys())
  32. cmdline("unalias", *self.aliases.keys())
  33. def status(self):
  34. proxies = (
  35. "%11s = %s" % (name, os.environ[name])
  36. for name in self.proxies.keys()
  37. if name in os.environ
  38. )
  39. for _ in proxies:
  40. cmdline("echo", _)
  41. def usage(self):
  42. cmdline("echo", "usage: proxy {enable,disable,status}")
  43. self.status()
  44. def cmdline(*items):
  45. print(list2cmdline(items))
  46. def main():
  47. command = CommandSet()
  48. if len(sys.argv) == 1:
  49. command.usage()
  50. sys.exit(-1)
  51. getattr(command, sys.argv[1], command.usage)()
  52. if __name__ == "__main__":
  53. main()