admin.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. from setux.core.action import Actions, Action
  2. from setux.actions.user import User_
  3. from setux.actions.transfer import Sender
  4. class Sudoer(Action):
  5. '''Add User to sudoers
  6. context:
  7. user : user name
  8. '''
  9. @property
  10. def label(self):
  11. return f'Sudoer {self.user}'
  12. def check(self):
  13. grp = self.target.groups.fetch(self.user)
  14. ok = 'wheel' in grp.get()
  15. ret, out, err = self.target.run(f'sudo -l -U {self.user}')
  16. ok = ok and '(ALL) NOPASSWD: ALL' in (line.strip() for line in out)
  17. return ok
  18. def deploy(self):
  19. grp = self.target.groups.fetch(self.user)
  20. grp.add('wheel')
  21. ok = self.target.write(
  22. f'/etc/sudoers.d/{self.user}',
  23. f'{self.user} ALL=(ALL) NOPASSWD: ALL',
  24. )
  25. return ok
  26. class CopyId(Action):
  27. '''Send Public Key to Target
  28. context:
  29. user : User name
  30. pub : Public key
  31. '''
  32. @property
  33. def label(self):
  34. return f'Copy ID {self.user}'
  35. def check(self):
  36. if not getattr(self, 'pub', None): return True
  37. user = self.target.user.fetch(self.user)
  38. if user.check() is not True: return False
  39. path = f'/home/{self.user}/.ssh/authorized_keys'
  40. pub = self.target.file.fetch(
  41. path, mode='600', user=self.user, group=user.group.name
  42. )
  43. ok = pub.check() is True
  44. if ok:
  45. ok = pub.hash == self.local.file(self.pub, verbose=False).hash
  46. return ok
  47. def deploy(self):
  48. user = self.target.user.fetch(self.user)
  49. path = f'/home/{self.user}/.ssh'
  50. ssh = self.target.dir(
  51. path, mode='700', user=self.user, group=user.group.name
  52. )
  53. if ssh.check() is not True: return False
  54. full = f'{path}/authorized_keys'
  55. self.target.run('rm -f {full}', sudo='root')
  56. sent = Sender(self.target, src=self.pub, dst=full, **self.context)()
  57. if sent is not True: return False
  58. key = self.target.file(
  59. full, mode='600', user=self.user, group=user.group.name
  60. )
  61. return key.check() is True
  62. class Admin(Actions):
  63. '''Set User as sudoer
  64. context:
  65. user : User name
  66. pub : Public key
  67. - Create User if not present
  68. - Add User to sudoers
  69. - Send User's public key
  70. '''
  71. @property
  72. def label(self):
  73. return f'Admin {self.user}'
  74. @property
  75. def actions(self):
  76. return [
  77. User_,
  78. Sudoer,
  79. CopyId,
  80. ]