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.

183 lines
5.5 KiB

  1. """
  2. Jake Zaia
  3. 2018-10-12
  4. Manages SSH config files, and supports a more user-friendly terminal based way of creating them
  5. """
  6. import os
  7. #This is the location of where the SSH
  8. SSH_CONFIG_FILE_LOC = os.path.expanduser('~/.ssh/config')
  9. bar = '================================\n'
  10. def config_exists():
  11. """
  12. Checks if an SSH config file exists at the desired path
  13. """
  14. return os.path.isfile(SSH_CONFIG_FILE_LOC)
  15. def get_config():
  16. """
  17. Returns the contents of the SSH config file as a string
  18. """
  19. if not config_exists():
  20. return ''
  21. f = open(SSH_CONFIG_FILE_LOC, 'r')
  22. ret = f.read()
  23. f.close()
  24. return ret
  25. def get_entries():
  26. """
  27. Creates a list of dictionaries where each dictionary contains all the information about a Host in the SSH config.
  28. """
  29. ret = []
  30. config = get_config().split('\n')
  31. #Operate on each line in the config
  32. for i in range(len(config)):
  33. #Add a new host entry
  34. if config[i][0:4] == 'Host':
  35. ret.append({})
  36. ret[-1]['Host'] = config[i][5:]
  37. #Add information to the current host
  38. if "\t" in config[i]:
  39. config[i] = config[i].strip()
  40. key = config[i][0: config[i].find(' ')]
  41. value = config[i][1 + config[i].find(' '):]
  42. ret[-1][key] = value
  43. return ret
  44. def print_entry_info(entry):
  45. """
  46. Conveniently displays the information for one entry in the SSH Config
  47. Takes a dictionary as input.
  48. """
  49. print("Host: {0}".format(entry['Host']))
  50. print("HostName: {0}".format(entry['HostName']))
  51. print("User: {0}".format(entry['User']))
  52. #Optional
  53. if 'Port' in entry:
  54. print("Port: {0}".format(entry['Port']))
  55. if 'IdentityFile' in entry:
  56. print("IdentityFile: {0}".format(entry['IdentityFile']))
  57. def modify_entry():
  58. """
  59. Gets all current entries and allows the user to modify the current values.
  60. """
  61. entries = get_entries()
  62. print("Which entry would you like to modify?")
  63. for i in range(len(entries)):
  64. print("{0}: {1}".format(i, entries[i]['Host']))
  65. i = int(input())
  66. #Print to ensure the correct property is specified
  67. print_entry_info(entries[i]);
  68. prop = input("Which property would you like to edit? (case sensitive) ")
  69. value = input("What should the new value be? ")
  70. entries[i][prop] = value
  71. #Update actual file
  72. push_config(entries)
  73. print("Successfully updated the entry.")
  74. def remove_entry():
  75. """
  76. Facilitates removing a singular entry from the SSH Config file
  77. """
  78. entries = get_entries()
  79. print("Which entry would you like to remove?")
  80. for i in range(len(entries)):
  81. print("{0}: {1}".format(i, entries[i]['Host']))
  82. i = int(input())
  83. print(bar)
  84. #For safety
  85. print_entry_info(entries[i]);
  86. resp = input("Really delete this entry? [y/N] ")
  87. if (resp=='y' or resp=='Y' or resp.lower() == 'yes'):
  88. entries.pop(i)
  89. print("Successfully deleted.")
  90. push_config(entries)
  91. def push_config(config):
  92. """
  93. Overwrites current config with an input list of dictionaries. Used as a helper to modify values in the SSH Config.
  94. """
  95. f = open(SSH_CONFIG_FILE_LOC, 'w')
  96. for each in config:
  97. f.write("Host {0}\n".format(each['Host']))
  98. f.write("\tHostName {0}\n".format(each['HostName']))
  99. f.write("\tUser {0}\n".format(each['User']))
  100. if 'Port' in each:
  101. f.write("\tPort {0}\n".format(each['Port']))
  102. if 'IdentityFile' in each:
  103. f.write("\tIdentityFile {0}\n".format(each['IdentityFile']))
  104. f.close()
  105. def create_entry():
  106. """
  107. Creates an SSH config file with information taken from a user
  108. """
  109. print("Please input the relevent information for generating your config file.")
  110. host = input("Nickname for Host: ")
  111. hostname = input("Hostname: ")
  112. user = input("Username: ")
  113. #Port is optional
  114. port = input("Would you like to specify a port?(y/N)")
  115. if (port == 'y' or port == 'Y' or port.lower() =='yes'):
  116. port = input("Port number: ")
  117. else:
  118. port = None
  119. #SSH public key location is optional
  120. identityfile = input("Would you like to specify an ssh public key location?(y/N)")
  121. if (identityfile == 'y' or identityfile == 'Y' or identityfile.lower() =='yes'):
  122. identityfile = input("SSH Public key file location: ")
  123. #Write info to config file
  124. if config_exists():
  125. f = open(SSH_CONFIG_FILE_LOC, 'a')
  126. else:
  127. f = open(SSH_CONFIG_FILE_LOC, 'w')
  128. f.write("Host {0}\n".format(host))
  129. f.write("\tHostName {0}\n".format(hostname))
  130. f.write("\tUser {0}\n".format(user))
  131. if port:
  132. f.write("\tPort {0}\n".format(port))
  133. if identityfile:
  134. f.write("\tIdentityFile {0}\n".format(identityfile))
  135. f.close()
  136. print("Successfully created the entry.")
  137. if __name__ == '__main__':
  138. cont = True
  139. while(cont):
  140. print("Modify your SSH Config file. Please Select an option:")
  141. print("0: Add a new entry")
  142. print("1: List all information")
  143. print("2: Modify an existing entry")
  144. print("3: Remove an entry")
  145. print("Any other number: exit")
  146. resp = input()
  147. print(bar)
  148. if resp == '0':
  149. create_entry()
  150. elif resp == '1':
  151. for each in get_entries():
  152. print()
  153. print_entry_info(each)
  154. elif resp == '2':
  155. modify_entry()
  156. elif resp == '3':
  157. remove_entry()
  158. else:
  159. cont = False
  160. print(bar)