proxy.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. default_proxy = os.environ.get("DEFAULT_PROXY")
  10. if default_proxy:
  11. return default_proxy
  12. if os.path.isfile(user_proxy):
  13. return check_output(user_proxy).decode("utf-8").strip()
  14. raise Exception("Not found, Proxy configuration")
  15. def make_proxies(url: str):
  16. proxies = {"%s_PROXY" % _: url for _ in ("HTTP", "HTTPS", "FTP", "RSYNC", "ALL")}
  17. proxies.update({name.lower(): value for (name, value) in proxies.items()})
  18. proxies["GIT_SSH"] = ssh_agent
  19. return proxies
  20. def merge(mapping: dict):
  21. return ("%s=%s" % _ for _ in mapping.items())
  22. class CommandSet:
  23. proxies = make_proxies(get_http_proxy())
  24. aliases = {
  25. _: "env __SSH_PROGRAM_NAME__=%s %s" % (_, ssh_agent)
  26. for _ in ("ssh", "sftp", "scp", "slogin", "ssh-copy-id")
  27. }
  28. def enable(self):
  29. cmdline("export", *merge(self.proxies))
  30. cmdline("alias", *merge(self.aliases))
  31. def disable(self):
  32. cmdline("unset", *self.proxies.keys())
  33. cmdline("unalias", *self.aliases.keys())
  34. def status(self):
  35. proxies = (
  36. "%11s = %s" % (name, os.environ[name])
  37. for name in self.proxies.keys()
  38. if name in os.environ
  39. )
  40. for _ in proxies:
  41. cmdline("echo", _)
  42. def usage(self):
  43. cmdline("echo", "usage: proxy {enable,disable,status}")
  44. self.status()
  45. def cmdline(*items):
  46. print(list2cmdline(items))
  47. def main():
  48. command = CommandSet()
  49. if len(sys.argv) == 1:
  50. command.usage()
  51. sys.exit(-1)
  52. getattr(command, sys.argv[1], command.usage)()
  53. if __name__ == "__main__":
  54. main()