ossh 7.3 KB

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