1. 程式人生 > 實用技巧 >用Python寫個自動ssh登入遠端伺服器的小工具

用Python寫個自動ssh登入遠端伺服器的小工具

國慶假期已經結束了,放假幾天出行,這些天沒分享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{} {} {} {} {}".format(name.strip("\n"), host_ip.strip("\n"), host_port, password.strip("\n"), alias.strip("\n")))
    of.close()
    print("Add the success:{} {}@{}:{}".format(alias.strip("\n"), name.strip("\n"), host_ip.strip("\n"), host_port, password.strip("\n")))
    return 1
   
def remove_host():
    '''
    刪除主機資訊
    :return: 
    '''
    while 1:
        # 開啟資料檔案
        of = open("{}/data/information.d".format(path))
        hosts = of.readlines()
        of.close
        l = len(hosts)
        if l <= 0:
            os.system("clear")
            print("[Warning]There is no host")
            return
            
        print("================Remove================")
        print("+{}+".format("-"*40))
        print("|     Alias   UserName@IP:PORT")
        hosts_temp = []
        n = 0
        # 遍歷輸出所以資訊(除了密碼)供選擇
        for i in range(0, l):
            if not hosts[i].strip():
                continue
            v_list = hosts[i].strip().split(" ")
            print("+{}+".format("-"*40))
            print("| {} | {}   {}@{}:{}".format(n+1, v_list[4], v_list[0], v_list[1], v_list[2]))
            n += 1
            hosts_temp.append(hosts[i])
        hosts = hosts_temp[:]
        print("+{}+".format("-"*40))
        c = raw_input("[Remove]Choose the Number or Alias('#q' to exit):")
        is_alias = False
        is_y = False
        try:
            c = int(c)
            if c > l or c < 1:
                os.system("clear")
                print("[Warning]:There is no")
                continue
            del hosts[c-1]
            is_y = True
            
        except:
            is_alias = True
        if is_alias:
            if c.strip() == "#q":
                os.system(
"clear") break n = 0 for l in hosts: if c.strip() == l.split(" ")[4].strip(): del hosts[n] is_y = True n += 1 if not is_y: os.system("clear") print("[Warning]:There is no"
) continue else: # save # 再次確認是否刪除 c = raw_input("Remove?[y/n]:") if c.strip().upper() == "Y": of = open("{}/data/information.d".format(path), "w") for l in hosts: of.write(l) print("Remove the success!") of.close() def str_format(lable, rule): ''' 用於驗證輸入的資料格式 :param lable: :param rule: :return: ''' while 1: print("{} ('#q' exit)".format(lable)) temp = raw_input().strip() m = re.match(r"{}".format(rule), temp) if m: break elif "port" in lable: temp = 22 break elif temp.strip() == "#q": os.system("clear") break os.system("clear") print("[Warning]:Invalid format") return temp

2. 我們再新增一個函式在setting.py用於輸出我們的資訊,也就是about me。

def about():
    '''
    輸出關於這個程式的資訊
    :return: 
    '''
    of = open("{}/bin/about.dat".format(path))
    rf = of.read()
    try:
        info = eval(rf)
        os.system("clear")
        print("================About osnssh================")
        for k,v in info.items():
            print("{}: {}".format(k, v))
    except:
        print("For failure.")
    return

然後在bin目錄下面建立個檔案about.dat寫入我們的一些資訊,比如:

{
    "auther":"Allen Woo",
    "Introduction":"In Linux or MAC using SSH, do not need to enter the IP and password for many times",
    "Home page":"",
    "Download address":"https://github.com/osnoob/osnssh",
    "version":"1.1.0",
    "email":"[email protected]"
}

好了設定程式就這樣了:

2. 自動登入遠端伺服器程式:在bin建個py檔案叫auto_ssh.py:
注意:這裡我們需要先安裝個包叫:pexpect, 使用者終端互動,捕捉互動資訊實現自動輸入密碼。
安裝pexpect:

pip install pexpect

然後開始寫程式碼:

#!/usr/bin/env python
#-*-coding:utf-8-*-
import os, sys, base64
import pexpect
path = os.path.dirname(os.path.abspath(sys.argv[0]))

def choose():
    # 開啟我們的資料檔案
    of = open("{}/data/information.d".format(path))
    hosts = of.readlines()
    hosts_temp = []
    for h in hosts:
        if h.strip():
            hosts_temp.append(h)
    hosts = hosts_temp[:]
    l = len(hosts)
    if l <= 0:
        os.system("clear")
        print("[Warning]Please add the host server")
        return
    while 1:
        
        print("=================SSH===================")
        print("+{}+".format("-"*40))
        print("|     Alias   UserName@IP:PORT")
        for i in range(0, l):
            v_list = hosts[i].strip().split(" ")
            print("+{}+".format("-"*40))
            print("| {} | {}   {}@{}:{}".format(i+1, v_list[4], v_list[0], v_list[1], v_list[2]))
        print("+{}+".format("-"*40))
        c = raw_input("[SSH]Choose the number or alias('#q' exit):")
        is_alias = False
        is_y = False
        try:
            c = int(c)
            if c > l or c < 1:
                os.system("clear")
                print("[Warning]:There is no")
                continue
            l_list = hosts[c-1].split(" ")
            name = l_list[0]
            host = l_list[1]
            port = l_list[2]
            password = l_list[3]
            is_y = True
            
        except:
            is_alias = True
        if is_alias:
            if c.strip() == "#q":
                os.system("clear")
                return
            for h in hosts:
                if c.strip() == h.split(" ")[4].strip():
                    l_list = h.split(" ")
                    name = l_list[0]
                    host = l_list[1]
                    port = l_list[2]
                    password = l_list[3]
                    is_y = True
        if not is_y:
            continue
        # ssh
        # 將加密儲存的密碼解密
        password = base64.decodestring(password)
        print("In the connection...")
        # 準備遠端連線,拼接ip:port
        print("{}@{}".format(name, host))
        if port == "22":
            connection("ssh {}@{}".format(name, host), password)
           
        else:
            connection("ssh {}@{}:{}".format(name, host, port), password)
  
def connection(cmd, pwd):
    '''
    連線遠端伺服器
    :param cmd: 
    :param pwd: 
    :return: 
    '''
    child = pexpect.spawn(cmd)
    i = child.expect([".*password.*", ".*continue.*?", pexpect.EOF, pexpect.TIMEOUT])
    if( i == 0 ):
        # 如果互動中出現.*password.*,就是叫我們輸入密碼
        # 我們就把密碼自動填入下去
        child.sendline("{}\n".format(pwd))
        child.interact()
    elif( i == 1):
        # 如果互動提示是否繼續,一般第一次連線時會出現
        # 這個時候我們傳送"yes",然後再自動輸入密碼
        child.sendline("yes\n")
        child.sendline("{}\n".format(pwd))
        
        #child.interact()    
    else:
        # 連線失敗
        print("[Error]The connection fails")

好了,現在我們只需要啟動檔案了,也就是開啟程式後的第一個選單
3.再osnssh目錄下建個osnssh.py 檔案:

#!/usr/bin/env python
#-*-coding:utf-8-*-
import os, sys
sys.path.append("../")
from bin import setting, auto_ssh
path = os.path.dirname(os.path.abspath(sys.argv[0]))
'''
方便在LINUX終端使用ssh,儲存使用的IP:PORT , PASSWORD
自動登入
__author__ = 'allen woo'
'''
def main():
    while 1:
        
        print("==============OSNSSH [Menu]=============")
        print("1.Connection between a host\n2.Add host\n3.Remove host\n4.About\n[Help]: q:quit   clear:clear screen")
        print("="*40)
        c = raw_input("Please select a:")
        if c == 1 or c == "1":
            auto_ssh.choose()
        if c == 2 or c == "2":
            setting.add_host_main()
        if c == 3 or c == "3":
            setting.remove_host()
        if c == 4 or c == "4":
            setting.about()
        elif c == "clear":
            os.system("clear")
        elif c == "q" or c == "Q" or c == "quit":
            print("Bye")
            sys.exit()
        else:
            print("\n")
       
if __name__ == '__main__':
    try:
        of = open("{}/data/information.d".format(path))
    except:
        of = open("{}/data/information.d".format(path), "w")
    of.close()
    main()

終於寫完了,我們可以試一試了:

$python osnssh.py

具體的演示,就是我在文章開頭放了張GIF動畫圖片,謝謝關注!