The development tools

The Paramiko module and some of the modules that come with Python. Operating system: Windows series.

Environment set up

Install Python and add it to the environment variable, and the PIP will install the appropriate module.

The main idea

Purpose: To create a command line version of the SSH login tool. (1) Add/delete IP, port and password needed to connect to the server; (2) Automatically enter the password to log in the remote server.

The relevant code

auto_ssh.py

# import OS import base64 import sys import paramiko path = os.path.dirname(os.path.abspath(sys.argv[0])) def ssh_connect(host_ip, host_port, username, password): ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) try: ssh.connect(host_ip, host_port, username, password, allow_agent=False, look_for_keys=False) print('[INFO]:Connect Successfully... ') except: print('[INFO]:Fail to Connect... ') while True: command = input('Enter the command(<#q> exit):') if command.strip() == '#q': ssh.close() return stdin, stdout, stderr = ssh.exec_command(command) out_content = stdout.readlines() if len(out_content) < 1: print('Error:') print(stderr.readlines()) else: print('Result:') for o in out_content: print(o) def choose_host(): f = open("{}/data/info.d".format(path)) hosts = f.readlines() hosts_temp = [] for h in hosts: if h.strip(): hosts_temp.append(h) hosts = hosts_temp[:] hosts_len = len(hosts) if hosts_len <= 0: os.system('cls') print('[Warning]:No info saved before... ') return while True: print('SSH...... ') print('FORMAT:\nAlias UserName@IP: PORT') for i in range(0, hosts_len): line_list = hosts[i].strip().split(' ') print("<{}>: {} |{}@{}: {}|".format(i+1, line_list[4], line_list[2], line_list[0], line_list[1])) choice = input('[SSH]:Choose the number or alias(<#q> exit):') is_alias = False is_num = False try: choice = int(choice) if choice < 1 or choice > hosts_len: os.system('cls') print('[Warning]:Number inexistence... ') continue line_list = hosts[choice-1].split(' ') username = line_list[2] password = line_list[3] host_ip = line_list[0] host_port = line_list[1] is_num = True except: is_alias = True if is_alias: if choice.strip() == '#q': os.system('clear') return for h in hosts: if choice.strip() == h.split(' ')[4].strip(): line_list = h.split(' ') username = line_list[2] password = line_list[3] host_ip = line_list[0] host_port = line_list[1]  is_num = True if not is_num: os.system('cls') print('[Warning]:Alias inexistence... ') continue # password = base64.decodestring(password) print('Start to connect {}@{}... '.format(username, host_ip)) ssh_connect(host_ip, host_port, username, password)

settings.py

Import base64 import OS import sys import re import getpass path = Def cmd_format(lable, rule): while True: def cmd_format(lable, rule): print('{} (<#q> exit):'.format(lable)) if lable.strip().strip(':').upper() == 'PASSWORD': temp = getpass.getpass() else: temp = input().strip() content = re.match(r'{}'.format(rule), temp) if content: break elif 'port' in lable: temp = 22 break elif temp.strip() == '#q': os.system('cls') break os.system('cls') print('[Warning]: Invalid format... ') return temp def about(): f = open('{}/info/about.bat'.format(path)) content = f.read() try: info = eval(content) os.system('cls') print('About SSH...... ') for k, v in info.items(): print('{}: {}'.format(k, v)) except: print('No Info...... Print ('Add host information...... ') f.lose () return # Add host(): print('Add host information...... ') print('[HELP]: INPUT <#q> exit... ') # IP addresses host_ip = cmd_format (' Host IP: ', '^ (25 [0 to 5] | 2 [0 to 4] [0-9] [0-9] | 1 | [0-9] [1-9]? [0-9]) \. (25 [0 to 5] | 2 [0 to 4] [0-9] | 1 [0-9] [0-9] | [1-9]? [0-9]) \. (25 [0 to 5] | 2 [0 to 4] [0-9] | 1 [0-9] [0-9] | [1-9]? [0-9]) \. (25 [0 to 5] | 2 [0 to 4] [0-9] | 1 [0-9] [0-9] | [1-9]? [0-9])$') if host_ip == '#q': Return True # format = cmd_format('Host port(Default 22):', '[0-9]+') if host_port == '#q': Return True # username = cmd_format('User Name:', '^[^]+$') if username == '#q': Return True # cmd_format(' password :', '.*') if password == '#q': Return True # password = cmd_format('Local alias :') '^[^ ]+$') if alias == '#q': return True elif not alias: os.system('cls') print('[Warning]: Alias cannot be empty... F = open('{}/data/info.d'. Format (path)) hosts = f.readlines() for line in hosts: temp = line.strip('\n') if not temp: continue line_list = line.split(' ') if host_ip == line_list[0] and host_port == line_list[1]: os.system('cls') print('[Warning]: {}: {} existing... '.format(host_ip, host_port)) return False if alias == line_list[4]: os.system('cls') print('[Warning]: Alias <{}> existing... '.format(alias)) return False f.lose () # f = open('{}/data/info.d'. Format (path), 'a') f.write('\n{} {} {} {} {}'.format(host_ip.strip('\n'), host_port, username.strip('\n'), password.strip('\n'), alias.strip('\n'))) f.close() print('[INFO]:{} {}@{}:{} Add Successfully... '.format(alias.strip('\n'), username.strip('\n'), host_ip.strip('\n'), password.strip('\n'))) return True def add_hosts(): while True: if add_host(): Break print('\n\nTry Again:') # def remove_host(): while True: f = open('{}/data/info.d'.format(path)) hosts = f.readlines() f.close() hosts_len = len(hosts) if hosts_len < 1: os.system('cls') print('[Warning]: No host info... ') return print('Remove host information...... ') print('%' * 40) print('FORMAT:\nAlias UserName@IP: PORT') print('%' * 40) hosts_temp = [] n = 1 for i in range(0, hosts_len): if not hosts[i].strip(): continue line_list = hosts[i].strip().split(' ') print("<{}>: {} |{}@{}: {}|".format(n, line_list[4], line_list[2], line_list[0], line_list[1])) n += 1 hosts_temp.append(hosts[I]) hosts = hosts_temp[:] choice = input('[Remove]: Choose the Number or Alias(<#q> to exit):') is_alias = False is_num = False try: choice = int(choice) if choice < 1 or choice > hosts_len: os.system('cls') print('[Warning]:Number inexistence... ') continue del hosts[choice-1] is_num = True except: is_alias = True if is_alias: if choice.strip() == '#q': os.system('cls') break n = 0 for h in hosts: if choice.strip() == h.split(' ')[4].strip(): del hosts[n] is_num = True n += 1 if not is_num: os.system('cls') print('[Warning]:Alias inexistence... ') continue else: choice = input('Remove? [y/n]:') if choice.strip().upper() == 'Y': f = open("{}/data/info.d".format(path), "w") for h in hosts: f.write(h) print('Remove Successfully... ') f.close()

SSH.py

Add/remove IP, port, password required to connect to the server. 594356095 import os import sys import settings import auto_ssh path = os.path.dirname(os.path.abspath(sys.argv[0])) def main(): while True: print('='*15 + 'SSH[Menu]' + '='*15) print('<1> Connect a host\n<2> Add host\n<3> Remove host\n<4> About\n[Help]: <q>:quit <clear>: clear screen') print('='*40) choice = input('Please select depend on tips:') if choice == 1 or choice == '1': auto_ssh.choose_host() elif choice == 2 or choice == '2': settings.add_hosts() elif choice == 3 or choice == '3': settings.remove_host() elif choice == 4 or choice == '4': settings.about() elif choice == 'q' or choice == 'Q' or choice == 'quit' or choice == 'exit': print('Bye... ') sys.exit() elif choice == 'clear' or 'cls': os.system('cls') else: print('No use input... ') if __name__ == '__main__': try: f = open('{}/data/info.d'.format(path)) except: f = open('{}/data/info.d'.format(path), 'w') f.close() main()

That’s it for now. Thank you for watching. Follow me for my daily series on Python gadgets

To thank you readers, I’d like to share with you some of my recent collection of dry programming goodies and give something back to every reader in the hope of helping you out.

Dry goods mainly include:

① More than 2000 Python e-books (mainstream and classic books are available)

(2) The Python Standard Library (Chinese version)

③ project source code (40 or 50 interesting and classic hands-on project and source code)

④Python basic introduction, crawler, web development, big data analysis video (suitable for small white learning)

⑤Python Learning Roadmap (Goodbye to Slow Learning)

⑥ Two days of Python crawler training camp live access

All done~ complete source code + dry goods see personal profile or private message to obtain the relevant files.