用Python寫個自動ssh登入遠端伺服器的小工具
阿新 • • 發佈:2020-10-08
國慶假期已經結束了,放假幾天出行,這些天沒分享Python。今天來給大家分享一下~
很多時候我們喜歡在自己電腦的終端直接ssh連線Linux伺服器,而不喜歡使用那些有UI介面的工具區連線我們的伺服器。可是在終端使用ssh我們每次都需要輸入賬號和密碼,這也是一個煩惱,所以我們可以簡單的打造一個在Linux/Mac os執行的自動ssh登入遠端伺服器的小工具.
來個GIF動畫示例下先:
概述###
我們先理一下我們需要些什麼功能:
1. 新增/刪除連線伺服器需要的IP,埠,密碼
2. 自動輸入密碼登入遠端伺服器
對,我們就做這麼簡單的功能
開始寫程式碼
程式碼比較長,所以我也放在在Github和碼雲,地址在文章最底部:
1.我們建個模組目錄osnssh(Open source noob ssh),然後在下面再建兩個目錄,一個用來放主程式取名叫bin吧,一個用來儲存登入資料(IP, 埠,密碼)叫data吧。
-osnssh
-bin
-data
1.設定程式:新增/刪除IP,埠,密碼. 建立py檔案bin/setting.py:
#!/usr/bin/env python
#-*-coding:utf-8-*-
import re, base64, os, sys
path = os.path.dirname(os.path.abspath(sys.argv[0]))
'''
選項配置管理
__author__ = 'allen woo'
'''
def add_host_main():
while 1:
if add_host():
break
print("\n\nAgain:")
def add_host():
'''
新增主機資訊
:return:
'''
print("================Add=====================")
print("[Help]Input '#q' exit")
# 輸入IP
host_ip = str_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 1
# 輸入埠
host_port = str_format("Host port(Default 22):", "[0-9]+")
if host_port == "#q":
return 1
# 輸入密碼
password = str_format("Password:", ".*")
if password == "#q":
return 1
# 密碼加密
password = base64.encodestring(password)
# 輸入使用者名稱
name = str_format("User Name:", "^[^ ]+$")
if name == "#q":
return 1
elif not name:
os.system("clear")
print("[Warning]:User name cannot be emptyg")
return 0
# The alias
# 輸入別名
alias = str_format("Local Alias:", "^[^ ]+$")
if alias == "#q":
return 1
elif not alias:
os.system("clear")
print("[Warning]:Alias cannot be emptyg")
return 0
# 開啟資料儲存檔案
of = open("{}/data/information.d".format(path))
hosts = of.readlines()
# 遍歷檔案資料,查詢是否有存在的Ip,埠,還有別名
for l in hosts:
l = l.strip("\n")
if not l:
continue
l_list = l.split(" ")
if host_ip == l_list[1] and host_port == l_list[2]:
os.system("clear")
print("[Warning]{}:{} existing".format(host_ip, host_port))
return 0
if alias == l_list[4]:
os.system("clear")
print("[Warning]Alias '{}' existing".format(alias))
return 0
of.close()
# save
# 儲存資料到資料檔案
of = open("{}/data/information.d".format(path), "a")
of.write("\n{} {} {} {} {}"