Python scripts I use to manage my ssh connections, drive mounts, and other bash related things.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

317 lines
8.6 KiB

6 years ago
7 years ago
6 years ago
7 years ago
  1. """
  2. Jeffery Russell
  3. 9-26-17
  4. """
  5. import subprocess
  6. import collections
  7. from utils import module
  8. import configuration
  9. import mount_ssh_drive
  10. import os
  11. INPUT_FILE = configuration.get_config()["servers"]
  12. FORWARD_FILE = configuration.get_config()["forwards"]
  13. Computer = collections.namedtuple("Computer", ('host', 'menu_id'))
  14. WELCOME_MESSAGE = "**************************************"
  15. def main():
  16. """
  17. This function inputs all the available hosts from a text file and
  18. prompts the user to connect to them
  19. :return:
  20. """
  21. file = module.input_file(INPUT_FILE)
  22. cmp = []
  23. count = 1
  24. for line in file:
  25. cmp.append(Computer(line, count))
  26. count += 1
  27. menu = []
  28. for c in cmp:
  29. menu.append(str(c.menu_id) + ") " + c.host)
  30. menu.append("A) Exit")
  31. menu.append("B) Manager tools")
  32. menu.append("C) Socks Tunnel")
  33. menu.append("D) SSH Drive Manager")
  34. menu.append("E) Local Port Forwarding")
  35. module.print_menu("SSH manager V 1.0", menu)
  36. i = input("Enter Option:")
  37. if i == '' or i == 'A' or i == 'a':
  38. exit_program()
  39. elif i == 'b' or i == 'B':
  40. sub_menu()
  41. elif "c" == str.lower(i):
  42. socks_ssh_tunnel()
  43. elif "d" == str.lower(i):
  44. mount_ssh_drive.main()
  45. elif "e" == str.lower(i):
  46. port_forwarding_sub_menu()
  47. else:
  48. for c in cmp:
  49. if int(i) == c.menu_id:
  50. subprocess.call(["ssh", c.host])
  51. exit_program()
  52. def socks_ssh_tunnel():
  53. """
  54. prints user a menu to select a host to start a socks proxy with
  55. :return: None
  56. """
  57. file = module.input_file(INPUT_FILE)
  58. cmp = []
  59. count = 1
  60. for line in file:
  61. cmp.append(Computer(line, count))
  62. count += 1
  63. menu = []
  64. for c in cmp:
  65. menu.append(str(c.menu_id) + ") " + c.host)
  66. menu.append("A) Exit")
  67. menu.append("B) Main")
  68. module.print_menu("Socks Tunnel", menu)
  69. i = input("Enter option:")
  70. if i == '' or 'a' == str.lower(i):
  71. exit_program()
  72. elif 'b' == str.lower(i):
  73. main()
  74. else:
  75. for c in cmp:
  76. if int(i) == c.menu_id:
  77. print_red("Starting socks proxy on " + c.host + ":8123")
  78. subprocess.call(["ssh", "-D", "8123", "-C", "-q", "-N", c.host])
  79. exit_program()
  80. def print_sub_menu():
  81. """
  82. prints out a sub help menu for other options
  83. :return: None
  84. """
  85. module.print_menu("Options", ["1) Add Host",
  86. "2) Copy SSH key to server",
  87. "3) Remove host name",
  88. "4) Return to ssh manager",
  89. "5) Manage Configuration and Bash",
  90. "6) Exit"])
  91. def print_red(prt): return "\033[91m {}\033[00m" .format(prt)
  92. def sub_menu():
  93. """
  94. calls printSubMenu and then gets input from user to
  95. make appropriate function calls
  96. :return: None
  97. """
  98. print_sub_menu()
  99. i = input("Enter selection:")
  100. if i != '' and int(i) in {1, 2, 3, 4, 5, 6}:
  101. options = {1: add_host,
  102. 2: copy_ssh_key,
  103. 3: remove_host,
  104. 4: main,
  105. 5: configuration.main,
  106. 6: exit_program
  107. }
  108. options[int(i)]()
  109. else:
  110. print("Invalid selection!")
  111. sub_menu()
  112. def exit_program():
  113. """
  114. Exits the program and clears the screen
  115. :return: None
  116. """
  117. subprocess.call(["clear"])
  118. exit()
  119. def add_host():
  120. """
  121. appends an inputted host name to servers.txt
  122. :return: None
  123. """
  124. host = input("Enter 'user@host' or -1 to exit:")
  125. if host != '-1':
  126. module.append_file(INPUT_FILE, host)
  127. def copy_ssh_key():
  128. """
  129. calls systems ssh-copy-id with host name
  130. :return: None
  131. """
  132. file = module.input_file(INPUT_FILE)
  133. cmp = []
  134. count = 1
  135. for line in file:
  136. cmp.append(Computer(line, count))
  137. count += 1
  138. menu = []
  139. for c in cmp:
  140. menu.append(str(c.menu_id) + ") " + c.host)
  141. menu.append("A) Exit")
  142. module.print_menu("Copy SSH Key", menu)
  143. host_id = input("Enter number of host to copy ssh key to:")
  144. if not (host_id == '-1' or host_id.lower() == 'a'):
  145. for c in cmp:
  146. if c.menu_id == int(host_id):
  147. subprocess.call(["ssh-copy-id", c.host])
  148. def remove_host():
  149. """
  150. Removes a host name from servers.txt
  151. :return: None
  152. """
  153. file = module.input_file(INPUT_FILE)
  154. cmp = []
  155. count = 1
  156. print(print_red("*" * len(WELCOME_MESSAGE)))
  157. for line in file:
  158. cmp.append(Computer(line, count))
  159. count += 1
  160. for c in cmp:
  161. space = " " * (len(WELCOME_MESSAGE) - 3 -
  162. len(str(c.menu_id) + ") " + c.host))
  163. print(print_red("*") + str(c.menu_id) + ") " +
  164. c.host + space + print_red("*"))
  165. print(print_red("*" * len(WELCOME_MESSAGE)))
  166. host = input("Enter number of host -1 to exit:")
  167. if host != '-1':
  168. for c in cmp:
  169. if c.menu_id == int(host):
  170. module.remove_line_from_file(INPUT_FILE, c.host)
  171. def add_forward_config():
  172. """
  173. appends new local forward configurations to forwards.txt
  174. :return: None
  175. """
  176. forwardingConfig = input("Enter forwarding config to add or -1 to exit:")
  177. if forwardingConfig != '-1':
  178. module.append_file(FORWARD_FILE, forwardingConfig)
  179. def del_forward_config():
  180. """
  181. removes a local forward configurations from forwards.txt
  182. :return: None
  183. """
  184. # check if file is empty before trying to open to read file
  185. if (os.stat(FORWARD_FILE).st_size == 0):
  186. print(print_red("*" * len(WELCOME_MESSAGE)))
  187. print("No forward configurations are available for removal.")
  188. print(print_red("*" * len(WELCOME_MESSAGE)))
  189. else:
  190. f = open(FORWARD_FILE, "r")
  191. i = 1
  192. savedConfigs = []
  193. print(print_red("*" * len(WELCOME_MESSAGE)))
  194. print("Current saved local port forwarding configurations:")
  195. for line in f:
  196. print(print_red("*") + "%s) %s" % (i, line) + print_red("*"))
  197. savedConfigs.append(line.strip())
  198. i += 1
  199. print(print_red("*" * len(WELCOME_MESSAGE)))
  200. selection = input("Select a configuration to delete: ")
  201. module.remove_line_from_file(FORWARD_FILE, savedConfigs[int(selection)-1])
  202. def select_forward_config():
  203. """
  204. Select a local forwarding configuration from forwards.txt
  205. to execute using SSH
  206. :return: None
  207. """
  208. # check if file is empty before trying to open to read file
  209. if (os.stat(FORWARD_FILE).st_size == 0):
  210. print(print_red("*" * len(WELCOME_MESSAGE)))
  211. print("No forward configurations are available to run.")
  212. print(print_red("*" * len(WELCOME_MESSAGE)))
  213. else:
  214. f = open(FORWARD_FILE, "r")
  215. i = 1
  216. savedConfigs = []
  217. print(print_red("*" * len(WELCOME_MESSAGE)))
  218. print("Current saved local port forwarding configurations:")
  219. for line in f:
  220. print(print_red("*") + "%s) %s" % (i, line) + print_red("*"))
  221. savedConfigs.append(line.strip())
  222. i += 1
  223. print(print_red("*" * len(WELCOME_MESSAGE)))
  224. selection = input("Select a configuration to execute: ")
  225. #Split the selected entry based on a space so we can feed each
  226. #element into the subprocess call
  227. forwardConfig = savedConfigs[int(selection)-1].split(" ")
  228. subprocess.call(["ssh", "-tt", "-L", forwardConfig[0], forwardConfig[1]])
  229. exit_program()
  230. def print_forwarding_sub_menu():
  231. """
  232. prints out a sub help menu for other forwarding options
  233. :return: None
  234. """
  235. module.print_menu("Options", ["1) Add local forward configuration",
  236. "2) Remove local forward configuration",
  237. "3) Select local forward configuration",
  238. "4) Exit"])
  239. def port_forwarding_sub_menu():
  240. """
  241. print out a sub menu related to port forwarding
  242. options
  243. :return: None
  244. """
  245. print_forwarding_sub_menu()
  246. i = input("Enter selection:")
  247. if i != "" and (int(i) in {1, 2, 3, 4}):
  248. options = {1: add_forward_config,
  249. 2: del_forward_config,
  250. 3: select_forward_config,
  251. 4: exit_program
  252. }
  253. options[int(i)]()
  254. else:
  255. print("Invalid selection!")
  256. port_forwarding_sub_menu()
  257. """
  258. Makes sure that other programs don't execute the main
  259. """
  260. if __name__ == '__main__':
  261. try:
  262. main()
  263. except KeyboardInterrupt:
  264. exit_program()