Heim  >  Artikel  >  Backend-Entwicklung  >  So schreiben Sie mit Python einen kleinen Toolcode für die automatische SSH-Anmeldung bei einem Remote-Server (empfohlen)

So schreiben Sie mit Python einen kleinen Toolcode für die automatische SSH-Anmeldung bei einem Remote-Server (empfohlen)

黄舟
黄舟Original
2017-06-18 11:13:411562Durchsuche

Der folgende Editor stellt Ihnen ein kleines Tool (Beispiel) zur Verfügung, mit dem Sie mithilfe von Python eine automatische SSH-Anmeldung bei einem Remote-Server schreiben können. Der Herausgeber findet es ziemlich gut, deshalb werde ich es jetzt mit Ihnen teilen und es allen als Referenz geben. Folgen wir dem Editor und werfen wir einen Blick darauf.

Oftmals verbinden wir uns lieber über SSH direkt vom Terminal unseres Computers aus mit dem Linux-Server, anstatt den Tool-Bereich mit der UI-Schnittstelle zu verwenden, um eine Verbindung zu unserem Server herzustellen. Wenn wir jedoch SSH im Terminal verwenden, müssen wir jedes Mal die Kontonummer und das Passwort eingeben, was ebenfalls ein Problem darstellt. Daher können wir einfach ein kleines Tool erstellen, das unter Linux/Mac OS ausgeführt wird, um sich automatisch beim Remote-Server anzumelden über ssh.

Geben wir ein Beispiel für eine GIF-Animation:

Übersicht

Lassen Sie uns zunächst herausfinden, welche Funktionen wir benötigen:

1. Fügen Sie die für die Verbindung erforderliche IP, den Port und das Passwort hinzu bzw. löschen Sie sie zum Server

2. Geben Sie automatisch das Passwort ein, um sich beim Remote-Server anzumelden

Ja, das werden wir Führen Sie eine so einfache Funktion aus

Beginnen Sie mit dem Schreiben von Code

Der Code ist relativ lang, daher habe ich ihn auch auf Github und Code Cloud abgelegt. Die Adresse befindet sich unten der Artikel:

1. Lassen Sie uns ein Modulverzeichnis osnssh (Open Source noob ssh) erstellen und dann unten zwei weitere Verzeichnisse erstellen, eines dient zum Speichern des Hauptprogramms und heißt bin, das andere wird verwendet dient der Speicherung von Anmeldedaten (IP, Port, Passwort) und wird als Daten bezeichnet.

-osnssh
-bin
-data

1. Einstellungsprogramm: py-Datei hinzufügen/löschen 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(&#39;#q&#39; 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):
 &#39;&#39;&#39;
 用于验证输入的数据格式
 :param lable: 
 :param rule: 
 :return: 
 &#39;&#39;&#39;
 while 1:
  print("{} (&#39;#q&#39; 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. Wir fügen in Setting.py eine weitere Funktion hinzu, um unsere Informationen auszugeben, die sich auf mich beziehen.


def about():
 &#39;&#39;&#39;
 输出关于这个程序的信息
 :return: 
 &#39;&#39;&#39;
 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

Erstellen Sie dann eine Datei about.dat im Bin-Verzeichnis und schreiben Sie einige unserer Informationen, wie zum Beispiel:


{
 "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"
}

Nach dem Einrichten des Programms ist es so:

2. Melden Sie sich automatisch beim Remote-Server-Programm an: Erstellen Sie eine Py-Datei im Bin mit dem Namen auto_ssh.py:

Hinweis: Hier müssen wir zunächst ein Paket namens pexpect installieren, das es der Benutzerterminalinteraktion ermöglicht, Interaktionsinformationen zu erfassen und automatisch Passwörter einzugeben.

Installieren Sie pexpect:

pip install pexpect

Dann beginnen Sie mit dem Schreiben des Codes:


#!/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(&#39;#q&#39; 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):
 &#39;&#39;&#39;
 连接远程服务器
 :param cmd: 
 :param pwd: 
 :return: 
 &#39;&#39;&#39;
 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")

Okay, jetzt müssen wir nur noch die Datei starten, die das erste Menü nach dem Öffnen des Programms ist

3. Erstellen Sie eine osnssh.py-Datei im osnssh-Verzeichnis:


#!/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]))
&#39;&#39;&#39;
方便在LINUX终端使用ssh,保存使用的IP:PORT , PASSWORD
自动登录
author = &#39;allen woo&#39;
&#39;&#39;&#39;
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 == &#39;main&#39;:
 try:
  of = open("{}/data/information.d".format(path))
 except:
  of = open("{}/data/information.d".format(path), "w")
 of.close()
 main()

Endlich fertig, wir können es versuchen:

$python osnssh.py

Das obige ist der detaillierte Inhalt vonSo schreiben Sie mit Python einen kleinen Toolcode für die automatische SSH-Anmeldung bei einem Remote-Server (empfohlen). Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn