Advertisement
Guest User

Untitled

a guest
Jan 31st, 2015
228
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.86 KB | None | 0 0
  1. from ansible.inventory.ini import InventoryParser
  2. import os
  3. from pycommand.command import Command, SubCommand
  4. #
  5.  
  6. _CHECK_SESSION = "tmux has-session -t {session} 2> /dev/null "
  7. _NEW_SESSION = "tmux new-session -d -s {session} '{ssh}'"
  8. _NEW_WINDOW = "tmux new-window -t {session} '{ssh}'"
  9. _ATTACH_SESSION = "tmux attach-session -t {session}"
  10.  
  11.  
  12. def tmux_format():
  13. yield " ".join(
  14. [_CHECK_SESSION, "&&", _NEW_WINDOW, '||', _NEW_SESSION, ])
  15. while True:
  16. yield _NEW_WINDOW
  17.  
  18.  
  19. def tmux_command(group='all', hosts=[], session=None, hostfile='hosts'):
  20. session = session or os.path.basename(os.path.abspath('.'))
  21.  
  22. tmux = tmux_format()
  23.  
  24. commands = []
  25. for host in InventoryParser(hostfile).groups['server'].hosts:
  26. if hosts and host.name not in hosts:
  27. continue
  28. key = host.vars.get('ansible_ssh_private_key_file', '')
  29. user = host.vars.get('ansible_ssh_user', '')
  30. ssh = 'ssh {key} {user}{host}'.format(
  31. key=key and '-i ' + key or '',
  32. user=user and user + '@' or '',
  33. host=host.name,
  34. )
  35. commands.append(tmux.next().format(
  36. session=session, ssh=ssh,))
  37.  
  38. if len(commands) > 0:
  39. commands.append(_ATTACH_SESSION.format(session=session))
  40. return commands
  41.  
  42.  
  43. class AnsibleCommand(Command):
  44.  
  45. class TmuxCommand(SubCommand):
  46. name = "tmux"
  47. description = "Open tmux windows with ssh connection"
  48. args = [
  49. (('hosts',), dict(nargs='*', help="Hosts")),
  50. (('--group',),
  51. dict(nargs=1, help="Host Group", default="all"),),
  52. (('--file',),
  53. dict(nargs=1, help="Host File", default="hosts"),),
  54. ]
  55.  
  56. def run(self, params, **options):
  57. print ";\n".join(
  58. tmux_command(params.group[0], params.hosts))
  59.  
  60.  
  61. if __name__ == '__main__':
  62. AnsibleCommand().run()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement