欧美三区_成人在线免费观看视频_欧美极品少妇xxxxⅹ免费视频_a级毛片免费播放_鲁一鲁中文字幕久久_亚洲一级特黄

用python寫個自動SSH登錄遠程服務器的小工具(實例)

系統 1865 0

很多時候我們喜歡在自己電腦的終端直接ssh連接Linux服務器,而不喜歡使用那些有UI界面的工具區連接我們的服務器??墒窃诮K端使用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":"xiaopingwoo@163.com"
}

          

好了設置程序就這樣了:

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

以上這篇用python寫個自動SSH登錄遠程服務器的小工具(實例)就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持腳本之家。


更多文章、技術交流、商務合作、聯系博主

微信掃碼或搜索:z360901061

微信掃一掃加我為好友

QQ號聯系: 360901061

您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。

【本文對您有幫助就好】

您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描上面二維碼支持博主2元、5元、10元、自定義金額等您想捐的金額吧,站長會非常 感謝您的哦!!!

發表我的評論
最新評論 總共0條評論
主站蜘蛛池模板: 久久国产精品精品国产 | 成人毛片观看 | 久久中文字幕一区 | 达达兔午夜起神影院在线观看麻烦 | 女猛烈无遮挡性视频免费 | 51国产视频 | 国产亚洲精品久久精品录音 | 免费观看一区二区三区毛片 | 日韩欧美视频免费观看 | 91视频在线观看免费 | 国产高清在线精品免费 | 国产精品嫩草影视在线观看 | 伊人亚洲 | 黄色精品| 91视频h | 91精品国产91久久久久久 | 天天拍天天干天天操 | 欧美另类亚洲 | 亚洲午夜精品视频 | 国产精品毛片久久久久久久 | 国产成人久久蜜一区二区 | 欧美性高清视频免费看www | 99久久精品国产免看国产一区 | 欧美一级毛片免费播放器 | 欧美顶级毛片在线播放 | 成人黄色免费在线观看 | 成人网页 | 欧美高清视频一区 | 日韩中文视频 | 国产不卡视频在线播放 | 欧美黄色一区 | 亚洲欧美激情另类 | 日韩美女一区二区三区 | 一区二区三区欧美在线观看 | 四虎1515hhhcom| 亚洲三级网 | 97色免费视频 | 欧美一区二区三区久久精品 | 久久精品国产一区 | 色播久久| 欧美精品一区二区三区久久 |