PHP前端开发

如何使用python写个自动SSH登录远程服务器的小工具代码分享(推荐)

百变鹏仔 6小时前 #Python
文章标签 如何使用

下面小编就为大家带来一篇用python写个自动ssh登录远程服务器的小工具(实例)。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧

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

来个GIF动画示例下先:

概述

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

立即学习“Python免费学习笔记(深入)”;

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, syspath = os.path.dirname(os.path.abspath(sys.argv[0]))'''选项配置管理author = 'allen woo''''def add_host_main(): while 1:  if add_host():   break  print("Again:")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("")  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("{} {} {} {} {}".format(name.strip(""), host_ip.strip(""), host_port, password.strip(""), alias.strip(""))) of.close() print("Add the success:{} {}@{}:{}".format(alias.strip(""), name.strip(""), host_ip.strip(""), host_port, password.strip(""))) return 1def remove_host(): ''' 删除主机信息 :return:  ''' while 1:  # 打开数据文件  of = open("{}/data/information.d".format(path))  hosts = of.readlines()  of.close  l = len(hosts)  if l  l or c <p>2. 我们再添加一个函数在setting.py用于输出我们的信息,也就是about me。</p><p class="jb51code"><br></p><pre class="brush:py;">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, base64import pexpectpath = 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  l or c <p>好了,现在我们只需要启动文件了,也就是打开程序后的第一个菜单</p><p>3.再osnssh目录下建个osnssh.py 文件:</p><p class="jb51code"><br></p><pre class="brush:py;">#!/usr/bin/env python#-*-coding:utf-8-*-import os, syssys.path.append("../")from bin import setting, auto_sshpath = 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 host2.Add host3.Remove host4.About[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("")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