ossh 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  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. self.user = None
  69. re_env = re.compile('\.(int|stg|prod|ops)')
  70. search = re_env.search(self.args.host)
  71. if self.args.env:
  72. self.env = self.args.env
  73. elif search:
  74. # take the first?
  75. self.env = search.groups()[0]
  76. # remove env from hostname command line arg if found
  77. if search:
  78. self.args.host = re_env.split(self.args.host)[0]
  79. # parse username if passed
  80. if '@' in self.args.host:
  81. self.user, self.host = self.args.host.split('@')
  82. else:
  83. self.host = self.args.host
  84. if self.args.login_name:
  85. self.user = self.args.login_name
  86. def get_hosts(self):
  87. '''Query our host inventory and return a dict where the format
  88. equals:
  89. dict['servername'] = dns_name
  90. '''
  91. # TODO: perform a numerical sort on these hosts
  92. # and display them
  93. self.host_inventory = self.ansible.build_host_dict()
  94. def select_host(self, regex=False):
  95. '''select host attempts to match the host specified
  96. on the command line with a list of hosts.
  97. if regex is specified then we will attempt to match
  98. all *{host_string}* equivalents.
  99. '''
  100. # list environment stuff as well
  101. # 3 states:
  102. # - an exact match; return result
  103. # - a partial match; return all regex results
  104. # - no match; None
  105. re_host = re.compile(self.host)
  106. exact = []
  107. results = []
  108. for hostname, server_info in self.host_inventory[self.env].items():
  109. if hostname.split(':')[0] == self.host:
  110. exact.append((hostname, server_info))
  111. break
  112. elif re_host.search(hostname):
  113. results.append((hostname, server_info))
  114. if exact:
  115. return exact
  116. elif results:
  117. return results
  118. else:
  119. print "Could not find specified host: %s in %s" % (self.host, self.env)
  120. # default - no results found.
  121. return None
  122. def list_hosts(self, limit=None):
  123. '''Function to print out the host inventory.
  124. Takes a single parameter to limit the number of hosts printed.
  125. '''
  126. if self.env:
  127. results = self.select_host(True)
  128. if len(results) == 1:
  129. hostname, server_info = results[0]
  130. sorted_keys = server_info.keys()
  131. sorted_keys.sort()
  132. for key in sorted_keys:
  133. print '{0:<35} {1}'.format(key, server_info[key])
  134. else:
  135. for host_id, server_info in results[:limit]:
  136. name = server_info['ec2_tag_Name']
  137. ec2_id = server_info['ec2_id']
  138. ip = server_info['ec2_ip_address']
  139. print '{ec2_tag_Name:<35} {ec2_tag_environment:<8} {ec2_id:<15} {ec2_ip_address}'.format(**server_info)
  140. if limit:
  141. print
  142. print 'Showing only the first %d results...' % limit
  143. print
  144. else:
  145. for env, host_ids in self.host_inventory.items():
  146. for host_id, server_info in host_ids.items():
  147. name = server_info['ec2_tag_Name']
  148. ec2_id = server_info['ec2_id']
  149. ip = server_info['ec2_ip_address']
  150. print '{ec2_tag_Name:<35} {ec2_tag_environment:<5} {ec2_id:<15} {ec2_ip_address}'.format(**server_info)
  151. def ssh(self):
  152. '''SSH to a specified host
  153. '''
  154. try:
  155. cmd = '/usr/bin/ssh'
  156. # shell args start with the program name in position 1
  157. ssh_args = [cmd, ]
  158. if self.user:
  159. ssh_args.append('-l%s' % self.user)
  160. if self.args.verbose:
  161. ssh_args.append('-vvv')
  162. if self.args.ssh_opts:
  163. ssh_args.append("-o%s" % self.args.ssh_opts)
  164. result = self.select_host()
  165. if not result:
  166. return # early exit, no results
  167. if len(result) > 1:
  168. self.list_hosts(10)
  169. return # early exit, too many results
  170. # Assume we have one and only one.
  171. hostname, server_info = result[0]
  172. dns = server_info['ec2_public_dns_name']
  173. ssh_args.append(dns)
  174. #last argument
  175. if self.args.command:
  176. ssh_args.append("%s" % self.args.command)
  177. if self.args.debug:
  178. print "SSH to %s in %s as %s" % (hostname, self.env, self.user)
  179. print "Running: %s\n" % ' '.join(ssh_args)
  180. os.execve('/usr/bin/ssh', ssh_args, os.environ)
  181. except:
  182. print traceback.print_exc()
  183. print sys.exc_info()
  184. def main():
  185. ossh = Ossh()
  186. if __name__ == '__main__':
  187. main()