shortcuts.py 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. # -*- coding: utf-8 -*-
  2. # Licensed under the Apache License, Version 2.0 (the "License");
  3. # you may not use this file except in compliance with the License.
  4. # You may obtain a copy of the License at
  5. #
  6. # http://www.apache.org/licenses/LICENSE-2.0
  7. #
  8. # Unless required by applicable law or agreed to in writing, software
  9. # distributed under the License is distributed on an "AS IS" BASIS,
  10. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
  11. # implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import grp
  15. import os
  16. import pwd
  17. def host_iter(config):
  18. for key, value in config.iteritems():
  19. if key.endswith("_HOST"):
  20. host = value.split('/')[0]
  21. if host:
  22. yield key, host
  23. if key.endswith("_HOSTS"):
  24. for i in value.split(","):
  25. host = i.strip().split('/')[0]
  26. if host:
  27. yield key, host
  28. def hosts(config):
  29. result = set()
  30. for key, host in host_iter(config):
  31. result.add(host)
  32. return result
  33. def get_current_user():
  34. try:
  35. user = pwd.getpwnam(os.getlogin())
  36. uid, gid = user.pw_uid, user.pw_gid
  37. except OSError:
  38. # in case program is run by a script
  39. uid, gid = os.getuid(), os.getgid()
  40. return uid, gid
  41. def get_current_username():
  42. uid, gid = get_current_user()
  43. user = pwd.getpwuid(uid).pw_name
  44. group = grp.getgrgid(gid).gr_name
  45. return user, group
  46. def split_hosts(hosts_string):
  47. hosts = set()
  48. for host in hosts_string.split(','):
  49. shost = host.strip()
  50. if shost:
  51. hosts.add(shost)
  52. return hosts