ossh.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  1. #!/usr/bin/env python
  2. import pdb
  3. import argparse
  4. import ansibleutil
  5. import traceback
  6. import sys
  7. import os
  8. import re
  9. # use dynamic inventory
  10. # list instances
  11. # symlinked to ~/bin
  12. # list instances that match pattern
  13. # python!
  14. # list environment stuff as well
  15. # 3 states:
  16. # - an exact match; return result
  17. # - a partial match; return all regex results
  18. # - no match; None
  19. class Ossh(object):
  20. def __init__(self):
  21. self.file_path = os.path.join(os.path.dirname(os.path.realpath(__file__)))
  22. self.parse_cli_args()
  23. self.ansible = ansibleutil.AnsibleUtil()
  24. self.host_inventory = self.get_hosts()
  25. if self.args.debug:
  26. print self.args
  27. # get a dict of host inventory
  28. self.get_hosts()
  29. # parse host and user
  30. self.process_host()
  31. # perform the SSH
  32. if self.args.list:
  33. self.list_hosts()
  34. else:
  35. self.ssh()
  36. def parse_cli_args(self):
  37. parser = argparse.ArgumentParser(description='Openshift Online SSH Tool.')
  38. parser.add_argument('-r', '--random', action="store",
  39. help="Choose a random host")
  40. parser.add_argument('-e', '--env', action="store",
  41. help="Which environment to search for the host ")
  42. parser.add_argument('-d', '--debug', default=False,
  43. action="store_true", help="debug mode")
  44. parser.add_argument('-v', '--verbose', default=False,
  45. action="store_true", help="Verbose?")
  46. parser.add_argument('--list', default=False,
  47. action="store_true", help="list out hosts")
  48. parser.add_argument('host')
  49. parser.add_argument('-c', '--command', action='store',
  50. help='Command to run on remote host')
  51. parser.add_argument('-l', '--login_name', action='store',
  52. help='User in which to ssh as')
  53. parser.add_argument('-o', '--ssh_opts', action='store',
  54. help='options to pass to SSH.\n \
  55. "-o ForwardX11 yes"')
  56. self.args = parser.parse_args()
  57. def process_host(self):
  58. '''Determine host name and user name for SSH.
  59. '''
  60. self.env = None
  61. re_env = re.compile('\.(int|stg|prod|ops)')
  62. search = re_env.search(self.args.host)
  63. if self.args.env:
  64. self.env = self.args.env
  65. elif search:
  66. # take the first?
  67. self.env = search.groups()[0]
  68. # remove env from hostname command line arg if found
  69. if search:
  70. self.args.host = re_env.split(self.args.host)[0]
  71. # parse username if passed
  72. if '@' in self.args.host:
  73. self.user, self.host = self.args.host.split('@')
  74. else:
  75. self.host = self.args.host
  76. if self.args.login_name:
  77. self.user = self.args.login_name
  78. else:
  79. self.user = os.environ['USER']
  80. def get_hosts(self):
  81. '''Query our host inventory and return a dict where the format
  82. equals:
  83. dict['servername'] = dns_name
  84. '''
  85. # TODO: perform a numerical sort on these hosts
  86. # and display them
  87. self.host_inventory = self.ansible.build_host_dict()
  88. def select_host(self, regex=False):
  89. '''select host attempts to match the host specified
  90. on the command line with a list of hosts.
  91. if regex is specified then we will attempt to match
  92. all *{host_string}* equivalents.
  93. '''
  94. # list environment stuff as well
  95. # 3 states:
  96. # - an exact match; return result
  97. # - a partial match; return all regex results
  98. # - no match; None
  99. re_host = re.compile(self.host)
  100. exact = []
  101. results = []
  102. for hostname, server_info in self.host_inventory[self.env].items():
  103. if hostname.split(':')[0] == self.host:
  104. exact.append((hostname, server_info))
  105. break
  106. elif re_host.search(hostname):
  107. results.append((hostname, server_info))
  108. if exact:
  109. return exact
  110. elif results:
  111. return results
  112. else:
  113. print "Could not find specified host: %s in %s" % (self.host, self.env)
  114. # default - no results found.
  115. return None
  116. def list_hosts(self, limit=None):
  117. '''Function to print out the host inventory.
  118. Takes a single parameter to limit the number of hosts printed.
  119. '''
  120. if self.env:
  121. results = self.select_host(True)
  122. if len(results) == 1:
  123. hostname, server_info = results[0]
  124. sorted_keys = server_info.keys()
  125. sorted_keys.sort()
  126. for key in sorted_keys:
  127. print '{0:<35} {1}'.format(key, server_info[key])
  128. else:
  129. for host_id, server_info in results[:limit]:
  130. name = server_info['ec2_tag_Name']
  131. ec2_id = server_info['ec2_id']
  132. ip = server_info['ec2_ip_address']
  133. print '{ec2_tag_Name:<35} {ec2_tag_environment:<8} {ec2_id:<15} {ec2_ip_address}'.format(**server_info)
  134. if limit:
  135. print
  136. print 'Showing only the first %d results...' % limit
  137. print
  138. else:
  139. for env, host_ids in self.host_inventory.items():
  140. for host_id, server_info in host_ids.items():
  141. name = server_info['ec2_tag_Name']
  142. ec2_id = server_info['ec2_id']
  143. ip = server_info['ec2_ip_address']
  144. print '{ec2_tag_Name:<35} {ec2_tag_environment:<5} {ec2_id:<15} {ec2_ip_address}'.format(**server_info)
  145. def ssh(self):
  146. '''SSH to a specified host
  147. '''
  148. try:
  149. cmd = '/usr/bin/ssh'
  150. ssh_args = [cmd, '-l%s' % self.user]
  151. #ssh_args = [cmd, ]
  152. if self.args.verbose:
  153. ssh_args.append('-vvv')
  154. if self.args.ssh_opts:
  155. ssh_args.append("-o%s" % self.args.ssh_opts)
  156. result = self.select_host()
  157. if not result:
  158. return # early exit, no results
  159. if len(result) > 1:
  160. self.list_hosts(10)
  161. return # early exit, too many results
  162. # Assume we have one and only one.
  163. hostname, server_info = result[0]
  164. ip = server_info['ec2_ip_address']
  165. ssh_args.append(ip)
  166. #last argument
  167. if self.args.command:
  168. ssh_args.append("%s" % self.args.command)
  169. if self.args.debug:
  170. print "SSH to %s in %s as %s" % (hostname, self.env, self.user)
  171. print "Running: %s\n" % ' '.join(ssh_args)
  172. os.execve('/usr/bin/ssh', ssh_args, os.environ)
  173. except:
  174. print traceback.print_exc()
  175. print sys.exc_info()
  176. def main():
  177. ossh = Ossh()
  178. if __name__ == '__main__':
  179. main()