oscp 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  1. #!/usr/bin/env python
  2. # vim: expandtab:tabstop=4:shiftwidth=4
  3. import argparse
  4. import ansibleutil
  5. import traceback
  6. import sys
  7. import os
  8. import re
  9. class Oscp(object):
  10. def __init__(self):
  11. self.file_path = os.path.join(os.path.dirname(os.path.realpath(__file__)))
  12. self.parse_cli_args()
  13. # parse host and user
  14. self.process_host()
  15. print self.args
  16. print self.host
  17. print self.user
  18. print self.path
  19. sys.exit(0)
  20. self.ansible = ansibleutil.AnsibleUtil()
  21. # get a dict of host inventory
  22. if self.args.list:
  23. self.get_hosts()
  24. else:
  25. self.get_hosts(True)
  26. if not self.args.list and not self.env:
  27. print "Please specify an environment."
  28. return
  29. if self.args.host == '' and not self.args.list:
  30. self.parser.print_help()
  31. return
  32. if self.args.debug:
  33. print self.args
  34. # perform the scp
  35. if self.args.list:
  36. self.list_hosts()
  37. else:
  38. self.scp()
  39. def parse_cli_args(self):
  40. parser = argparse.ArgumentParser(description='Openshift Online SSH Tool.')
  41. parser.add_argument('-d', '--debug', default=False,
  42. action="store_true", help="debug mode")
  43. parser.add_argument('-v', '--verbose', default=False,
  44. action="store_true", help="Verbose?")
  45. parser.add_argument('--list', default=False,
  46. action="store_true", help="list out hosts")
  47. parser.add_argument('-r', action='store_true', default=False,
  48. help='Recusrively copy files to or from destination.')
  49. parser.add_argument('-o', '--ssh_opts', action='store',
  50. help='options to pass to SSH.\n \
  51. "-oPort=22,TCPKeepAlive=yes"')
  52. parser.add_argument('src', default='')
  53. parser.add_argument('dest',default='')
  54. self.args = parser.parse_args()
  55. self.parser = parser
  56. def process_host(self):
  57. '''Determine host name and user name for SSH.
  58. '''
  59. self.user = None
  60. self.path = ''
  61. self.host = ''
  62. if '@' in self.args.src:
  63. self.host = self.args.src
  64. else:
  65. self.host = self.args.dest
  66. re_host = re.compile("(.*)@(.*)(:.*$)")
  67. search = re_host.search(self.host)
  68. if search:
  69. # take the first?
  70. self.user = search.groups()[0]
  71. self.host = search.groups()[1]
  72. self.path = search.groups()[2]
  73. else:
  74. print "Could not determine user and hostname."
  75. return
  76. def get_hosts(self, cache_only=False):
  77. '''Query our host inventory and return a dict where the format
  78. equals:
  79. dict['environment'] = [{'servername' : {}}, ]
  80. '''
  81. if cache_only:
  82. self.host_inventory = self.ansible.build_host_dict(['--cache-only'])
  83. else:
  84. self.host_inventory = self.ansible.build_host_dict()
  85. def select_host(self, regex=False):
  86. '''select host attempts to match the host specified
  87. on the command line with a list of hosts.
  88. if regex is specified then we will attempt to match
  89. all *{host_string}* equivalents.
  90. '''
  91. re_host = re.compile(self.host)
  92. results = []
  93. for hostname, server_info in self.host_inventory[self.env].items():
  94. if hostname.split(':')[0] == self.host:
  95. # an exact match, return it!
  96. return [(hostname, server_info)]
  97. elif re_host.search(hostname):
  98. results.append((hostname, server_info))
  99. if results:
  100. return results
  101. else:
  102. print "Could not find specified host: %s in %s" % (self.host, self.env)
  103. # default - no results found.
  104. return None
  105. def list_hosts(self, limit=None):
  106. '''Function to print out the host inventory.
  107. Takes a single parameter to limit the number of hosts printed.
  108. '''
  109. if self.env:
  110. results = self.select_host(True)
  111. if len(results) == 1:
  112. hostname, server_info = results[0]
  113. sorted_keys = server_info.keys()
  114. sorted_keys.sort()
  115. for key in sorted_keys:
  116. print '{0:<35} {1}'.format(key, server_info[key])
  117. else:
  118. for host_id, server_info in results[:limit]:
  119. name = server_info['ec2_tag_Name']
  120. ec2_id = server_info['ec2_id']
  121. ip = server_info['ec2_ip_address']
  122. print '{ec2_tag_Name:<35} {ec2_tag_environment:<8} {ec2_id:<15} {ec2_ip_address}'.format(**server_info)
  123. if limit:
  124. print
  125. print 'Showing only the first %d results...' % limit
  126. print
  127. else:
  128. for env, host_ids in self.host_inventory.items():
  129. for host_id, server_info in host_ids.items():
  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:<5} {ec2_id:<15} {ec2_ip_address}'.format(**server_info)
  134. def scp(self):
  135. '''scp files to or from a specified host
  136. '''
  137. try:
  138. # shell args start with the program name in position 1
  139. scp_args = ['/usr/bin/scp']
  140. if self.args.verbose:
  141. scp_args.append('-v')
  142. if self.args.ssh_opts:
  143. for arg in self.args.ssh_opts.split(","):
  144. scp_args.append("-o%s" % arg)
  145. result = self.select_host()
  146. if not result:
  147. return # early exit, no results
  148. if len(result) > 1:
  149. self.list_hosts(10)
  150. return # early exit, too many results
  151. # Assume we have one and only one.
  152. hostname, server_info = result[0]
  153. dns = server_info['ec2_public_dns_name']
  154. scp_args.append(dns)
  155. #last argument
  156. if self.args.command:
  157. scp_args.append("%s" % self.args.command)
  158. print "Running: %s\n" % ' '.join(scp_args)
  159. os.execve('/usr/bin/scp', scp_args, os.environ)
  160. except:
  161. print traceback.print_exc()
  162. print sys.exc_info()
  163. if __name__ == '__main__':
  164. oscp = Oscp()