Python實用工具,paramiko模組,Python實現簡易版SSH登入工具
阿新 • • 發佈:2021-08-03
開發工具
Python版本: 3.5.4
相關模組:
paramiko模組以及一些Python自帶的模組。
作業系統:Windows系列。
環境搭建
安裝Python並新增到環境變數,pip安裝需要的相關模組即可。
主要思路
目的:
製作命令列版的SSH登入工具。
需要實現的功能:
(1)新增/刪除連線伺服器需要的IP、埠、密碼;
(2)自動輸入密碼登入遠端伺服器。
相關程式碼
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 = os.path.dirname(os.path.abspath(sys.argv[0])) # 用於處理輸入的資料格式 def cmd_format(lable, rule): while True: 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......') f.close() return # 新增主機資訊 def add_host(): print('Add host information......') print('[HELP]: INPUT <#q> exit...') # IP地址 host_ip = cmd_format('Host IP:', '^(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])$') if host_ip == '#q': return True # 埠號 host_port = cmd_format('Host port(Default 22):', '[0-9]+') if host_port == '#q': return True # 使用者名稱 username = cmd_format('User Name:', '^[^ ]+$') if username == '#q': return True # 密碼 password = cmd_format('Password:', '.*') if password == '#q': return True # password = base64.encodestring(password) # 輸入別名 alias = cmd_format('Local Alias:', '^[^ ]+$') if alias == '#q': return True elif not alias: os.system('cls') print('[Warning]: Alias cannot be empty...') return False # 查重 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.close() # 儲存 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
# 功能: # 新增/刪除連線伺服器需要的IP、埠、密碼 # 自動輸入密碼登入遠端伺服器 # Python新手學習交流社群: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()
文章到這裡就結束了,感謝你的觀看,關注我每天分享Python小工具系列,下篇文章分享簡易的計時器
為了感謝讀者們,我想把我最近收藏的一些程式設計乾貨分享給大家,回饋每一個讀者,希望能幫到你們。
乾貨主要有:
① 2000多本Python電子書(主流和經典的書籍應該都有了)
② Python標準庫資料(最全中文版)
③ 專案原始碼(四五十個有趣且經典的練手專案及原始碼)
④ Python基礎入門、爬蟲、web開發、大資料分析方面的視訊(適合小白學習)
⑤ Python學習路線圖(告別不入流的學習)
⑥ 兩天的Python爬蟲訓練營直播許可權
All done~完整原始碼+乾貨詳見個人主頁簡介或者私信獲取