您的位置:首页>科学 >使用python写一个自动ssh登录远程服务器的小工具(示例)

使用python写一个自动ssh登录远程服务器的小工具(示例)

2023-10-02 03:04

很多时候我们喜欢从自己电脑的终端直接ssh到Linux服务器,而不是使用那些有UI界面的工具区连接到我们的服务器。但是在终端使用ssh时,我们每次都需要输入账号和密码,这也是一个麻烦,所以我们可以简单创建一个运行在Linux/Mac上的通过ssh自动登录远程服务器的小工具操作系统。

这是 GIF 动画的示例:

概述

我们先来梳理一下我们需要什么功能:

1。添加/删除连接服务器所需的 IP、端口和密码

2。自动输入密码登录远程服务器

是的,我们只是做这么一个简单的功能

开始写代码

代码比较长,所以我也放到了Github和码云上。地址在文章底部:

1。我们先创建一个模块目录osnssh(开源noob ssh),然后在下面创建两个目录,一个是主程序,名为bin,一个是保存登录数据(IP、端口、密码)的目录,名为data。

-osnssh
-bin
-数据

1。设置程序:添加/删除IP、端口、密码。创建py文件bin/www.webguidecorpuschristi.com:

#!/usr/bin/env python
#-*-编码:utf-8-*-
导入 re、base64、os、sys
路径 = os.path.dirname(os.path.abspath(sys.argv[0]))
'''

选项配置管理

__author__ = '吴艾伦'
'''
def add_host_main():
 而1:
  如果添加主机():
   休息
  打印(“再次:”)

def add_host():
 '''
 添加主机信息
 :返回:
 '''print("================添加======================")
 print("[帮助]输入'#q'退出")
 # 输入IP
 host_ip = str_format("主机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])$")
 如果 host_ip == "#q":
  返回1
 #输入端口
 host_port = str_format("主机端口(默认22):", "[0-9]+")
 如果主机端口==“#q”:
  返回1
 # 输入密码
 密码 = str_format("密码:", ".*")
 如果密码==“#q”:
  返回1
 # 密码加密
 密码 = base64.encodestring(密码)
 # 输入你的用户名
 name = str_format("用户名:", "^[^ ]+$")
 如果名称==“#q”:
  返回1
 elif 不是名字:
  os.system("清除")
  print("[警告]:用户名不能为空g")
  返回0

 #塞利亚斯
 # 输入别名
 alias = str_format("本地别名:", "^[^ ]+$")
 如果别名==“#q”:
  返回1
 elif 不是别名:
  os.system("清除")
  print("[警告]:别名不能为空g")
  返回0#打开数据保存文件
 of = open("{}/data/information.d".format(path))
 主机 = of.readlines()
 # 遍历文件数据,查找是否存在IP、端口、别名
 对于主机中的 l:
  l = l.strip("n")
  如果不是我:
   继续
  l_list = l.split(" ")
  如果 host_ip == l_list[1] 且 host_port == l_list[2]:
   os.system("清除")
   print("[警告]{}:{} 现有".format(host_ip, host_port))
   返回0
  如果别名 == l_list[4]:
   os.system("清除")
   print("[警告]别名'{}'已存在".format(alias))
   返回0
 of.close()
 #节省
 # 保存数据到数据文件
 of = open("{}/data/information.d".format(path), "a")
 of.write("n{} {} {} {} {}".format(name.strip("n"), host_ip.strip("n"), host_port, 密码.strip("n"), 别名.strip("n")))
 of.close()
 print("添加成功:{} {}@{}:{}".format(alias.strip("n"), name.strip("n"), host_ip.strip("n"), host_port,密码.strip("n")))
 返回1

def remove_host():
 '''
 删除主机信息
 :返回:
 '''
 而1:
  #打开数据文件
  of = open("{}/data/information.d".format(path))主机 = of.readlines()
  of.close
  l = len(主机)
  如果 l <= 0:
   os.system("清除")
   print("[警告]没有主机")
   返回

  print("================删除================")
  print("+{}+".format("-"*40))
  print("| 别名用户名@IP:端口")
  主机温度 = []
  n = 0
  # 遍历输出所以信息(除了密码)供选择
  对于范围 (0, l) 内的 i:
   如果不是hosts[i].strip():
    继续
   v_list = 主机[i].strip().split(" ")
   print("+{}+".format("-"*40))
   print("| {} | {} {}@{}:{}".format(n+1, v_list[4], v_list[0], v_list[1], v_list[2]))
   n+=1
   主机临时.append(主机[i])
  主机 = 主机临时[:]
  print("+{}+".format("-"*40))
  c = raw_input("[删除]选择号码或别名('#q'退出):")
  is_alias = False
  is_y = 假
  尝试:
   c = int(c)
   如果 c > l 或 c < 1:
    os.system("清除")
    print("[警告]:没有")
    继续
   删除主机[c-1]
   is_y = True

  除了:
   is_alias = True
  如果是_别名:
   如果 c.strip() == "#q":os.system("清除")
    休息
   n = 0
   对于主机中的 l:
    if c.strip() == l.split(" ")[4].strip():
     删除主机[n]
     is_y = True
    n+=1
  如果不是 is_y:
   os.system("清除")
   print("[警告]:没有")
   继续
  别的:
   #节省
   # 再次确认是否删除
   c = raw_input("删除?[y/n]:")
   如果 c.strip().upper() == "Y":
    of = open("{}/data/information.d".format(path), "w")
    对于主机中的 l:
     of.write(l)
    print("删除成功!")
    of.close()

def str_format(标签,规则):
 '''
 用于验证输入的数据格式
 :参数标签:
 :参数规则:
 :返回:
 '''
 而1:
  print("{} ('#q' 退出)".format(lable))
  temp = raw_input().strip()
  m = re.match(r"{}".format(rule), temp)
  如果米:
   休息
  标签中的 elif“端口”:
   温度=22
   休息
  elif temp.strip() == "#q":
   os.system("清除")
   休息
  os.system("清除")
  print("[警告]:格式无效")

 返回温度

2。我们在www.webguidecorpuschristi.com中添加另一个函数来输出我们的信息,这是关于我的。

定义关于():
 '''
 输出有关该程序的信息
 :返回:
 '''
 of = open("{}/bin/about.dat".format(path))
 rf = www.webguidecorpuschristi.com()
 尝试:
  信息 = 评估(rf)
  os.system("清除")
  print("================关于osnssh================")
  对于 info.items() 中的 k,v:
   print("{}: {}".format(k, v))
 除了:
  print("失败。")
 返回

然后在bin目录下创建一个about.dat文件,写入我们的一些信息,如:

{
 "auther":"吴艾伦",
 "简介":"在Linux或MAC下使用SSH,不需要多次输入IP和密码",
 “主页”:””,
 "下载地址":"https://www.webguidecorpuschristi.com/osnoob/osnssh",
 “版本”:“1.1.0”,
 "邮箱":"support@www.webguidecorpuschristi.com"
}

现在是设置过程:

2。自动登录远程服务器程序:在bin中创建一个名为auto_www.webguidecorpuschristi.com的py文件:

注意:这里我们需要先安装一个名为:pexpect的包,它可以让用户终端交互捕获交互信息并自动输入密码。

安装预期:

pip install pexpect

然后开始写代码:

#!/usr/bin/env python
#-*-编码:utf-8-*-
导入操作系统、系统、base64
导入预期
路径 = os.path.dirname(os.path.abspath(sys.argv[0]))def select():
 #打开我们的数据文件
 of = open("{}/data/information.d".format(path))
 主机 = of.readlines()
 主机温度 = []
 对于主机中的 h:
  如果 h.strip():
   主机临时.append(h)
 主机 = 主机临时[:]
 l = len(主机)
 如果 l <= 0:
  os.system("清除")
  print("[警告]请添加主机服务器")
  返回
 而1:

  打印(“==================SSH====================”)
  print("+{}+".format("-"*40))
  print("| 别名用户名@IP:端口")
  对于范围 (0, l) 内的 i:
   v_list = 主机[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]选择号码或别名('#q' exit):")
  is_alias = False
  is_y = 假
  尝试:
   c = int(c)
   如果 c > l 或 c < 1:
    os.system("清除")
    print("[警告]:没有")
    继续
   l_list = 主机[c-1].split(" ")
   名称 = l_list[0]
   主机 = l_list[1]
   端口 = l_list[2]密码 = l_list[3]
   is_y = True

  除了:
   is_alias = True
  如果是_别名:
   如果 c.strip() == "#q":
    os.system("清除")
    返回
   对于主机中的 h:
    if c.strip() == h.split(" ")[4].strip():
     l_list = h.split(" ")
     名称 = l_list[0]
     主机 = l_list[1]
     端口 = l_list[2]
     密码 = l_list[3]
     is_y = True
  如果不是 is_y:
   继续
  #ssh
  # 解密加密密码
  密码 = base64.decodestring(密码)
  print("在连接中...")
  # 准备远程连接,拼接ip:port
  print("{}@{}".format(名称, 主机))
  如果端口==“22”:
   连接(“ssh {}@{}”。格式(名称,主机),密码)

  别的:
   连接("ssh {}@{}:{}".format(名称、主机、端口)、密码)

def 连接(cmd, pwd):
 '''
 连接到远程服务器
 :参数命令:
 :参数密码:
 :返回:
 '''
 孩子 = pexpect.spawn(cmd)
 i = child.expect([".*密码.*", ".*继续.*?", pexpect.EOF, pexpect.TIMEOUT])
 如果(我==0):
  # 如果交互中出现.*password.*,则要求我们输入密码。
  # 我们会自动填写密码child.sendline("{}n".format(pwd))
  child.interact()
 elif(我==1):
  # 如果交互提示是否继续,一般会在第一次连接时出现。
  # 这时候我们发送“yes”然后自动输入密码
  child.sendline("是的")
  child.sendline("{}n".format(pwd))

  #child.interact()
 别的:
  # 连接失败
  print("[错误]连接失败")

好了,现在我们只需要启动文件即可,也就是打开程序后的第一个菜单

3。在osnssh目录下创建www.webguidecorpuschristi.com文件:

#!/usr/bin/env python
#-*-编码:utf-8-*-
导入操作系统、系统
sys.path.append("../")
从 bin 导入设置,auto_ssh
路径 = os.path.dirname(os.path.abspath(sys.argv[0]))
'''
方便在LINUX终端使用ssh,保存使用过的IP:PORT、PASSWORD
自动登录
__author__ = '吴艾伦'
'''
def main():
 而1:

  print("==============OSNSSH [菜单]===============")
  print("1.主机n2之间的连接.添加主机n3.删除主机n4.Aboutn[帮助]: q:quit clear:清屏")
  打印(“=”*40)
  c = raw_input("请选择一个:")
  如果 c == 1 或 c == "1":
   auto_ssh.choose()
  如果 c == 2 或 c == "2":
   设置.add_host_main()
  如果 c == 3 或 c == "3":设置.remove_host()
  如果 c == 4 或 c == "4":
   设置.about()
  elif c ==“清除”:
   os.system("清除")
  elif c == "q" 或 c == "Q" 或 c == "quit":
   打印(“再见”)
   sys.exit()
  别的:
   打印(“n”)

如果 __name__ == '__main__':
 尝试:
  of = open("{}/data/information.d".format(path))
 除了:
  of = open("{}/data/information.d".format(path), "w")
 of.close()
 主要的()

终于完成了,我们可以尝试一下:

$python www.webguidecorpuschristi.com

上面这篇使用python写一个自动SSH登录远程服务器的小工具(例子)就是小编分享的全部内容。希望能给您一个参考,也希望您支持来客网。