用Python写个自动ssh登录远程服务器的小工具
很多时候我们喜欢在自己电脑的终端直接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":"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
具体的演示,就是我在文章开头放了张GIF动画图片源码加群
学习过程中遇到什么问题或者想获取学习资源的话,欢迎加入学习交流群
626062078,我们一起学Python!
用Python写个自动ssh登录远程服务器的小工具的更多相关文章
- mac 终端下ssh 登录远程服务器不发输入中文
转:https://segmentfault.com/q/1010000000150673 用Mac的iterm2 ssh连上去,终端显示中文乱码,也不能输入中文,然而本地终端可以显示和输入. 解决方 ...
- 配置本地无密码 SSH登录远程服务器
下面这幅图简单来说就是你本地有一把钥匙,服务器也有一把钥匙,当登录的时候本地的钥匙与服务器的进行对比,通过算法的判定,监测是否具有权限的用户 第一步,在本地配置这把钥匙生成私钥与公钥: 打开.ssh目 ...
- Linux上SSH登录远程服务器免密码
在本地的客户端SSH到远程服务端时,每次都要输入用户名和密码,如果不想每次都输入密码则可以使用以下操作. 首先在本地的客户端输入 ssh-keygen [keysystem@localhost ~]$ ...
- 终端利用ssh登录远程服务器
第一步: 安装ssh:yum install ssh 第二步: 启动ssh服务:service sshd start 第三步: 连接远程服务器: ssh -p 端口号 用户名@ip地址 然 ...
- 使用秘钥ssh登录远程服务器
一.使用公钥远程登录ssh服务器方式 1.1 在客户端使用ssh-keygen 生成密匙 steven:~ admin$ ssh-keygen //客户端生成秘钥 Generating public ...
- ssh 登录远程服务器--config配置
一.config 配置案列 Host master HostName: 39.105.61.1 Port 22 User root IdentityFile <id_rsa> 二.配置讲解 ...
- ssh登录远程服务器
在终端输入ssh 用户名@IP地址, 比如输入用户名和密码,进入目录,即可查看修改文件,启动服务. 这和安装xshell和filelizza,终端有什么区别? useradd guangbo pas ...
- Mac下ssh连接远程服务器时自动断开问题
在mac下使用securecrt通过ssh连接远程服务器时,总会一段时间没有动作后,ssh被自动断开.在windows下用xmanager貌似没有遇到过这个问题. 在网上找了解决方法如下: 客户端配置 ...
- 最新JetBrainsPyCharm自动部署Python(Django,tornado等)项目至远程服务器
每次开发Python项目时,对于所有Python开发人员来说,最枯燥的不是修改代码,而是实时将自己的代码上传至远程服务器,进行测试或者部署,本人最初开发也是这样,通过使用Xshell 5,WinSCP ...
随机推荐
- 算法语言Scheme修订6报告 R6RS简体中文翻译
算法语言Scheme修订6报告 R6RS简体中文翻译 来源 https://r6rs.mrliu.org/ MICHAEL SPERBERR. KENT DYBVIG, MATTHEW FLATT ...
- RESTful Webservice
1,REST和RESTFUL是什么? REST ( REpresentational State Transfer ),State Transfer 为 "状态传输" 或 &quo ...
- CentOS 配置无线网络,开启wifi
背景:一台老笔记本安装CentOS7.x,最小安装模式,安装后无法开启wifi 1.先用NetworkManager包的nmcli命令检查网卡,发现无线网卡wlo1信息里有个错误plugin miss ...
- bzoj 1103: [POI2007]大都市meg (dfs序)
dfs序,加个bit维护前缀和就行了 type arr=record toward,next:longint; end; const maxn=; var edge:..maxn]of arr; bi ...
- BZOJ3930:[CQOI2015]选数——题解
http://www.lydsy.com/JudgeOnline/problem.php?id=3930 https://www.luogu.org/problemnew/show/P3172#sub ...
- pandas模块(数据分析)------dataframe
DataFrame DataFrame是一个表格型的数据结构,含有一组有序的列,是一个二维结构. DataFrame可以被看做是由Series组成的字典,并且共用一个索引. 一.生成方式 import ...
- Sqlserver中如何创建链接服务器
链接服务器在跨数据库/跨服务器查询时非常有用(比如分布式数据库系统中),我将以图文方式详细说明如何利用SQL Server Management Studio在图形界面下创建链接服务器 方法/步骤 ...
- SpringMVC+MyBatis 返回时间格式转换的解决方案
Spring MVC 4.X ResponseBody 日期类型Json 处理 摘自http://tramp-zzy.iteye.com/blog/2090330 2014-07-10 方法一:全局 ...
- Linux 中使用 dd 测试磁盘性能
翻译自 : Linux I/O Performance Tests using dd 基本说明 dd 可以用来做简单的低级别复制文件. 这样做, 一般都是可一直直接访问设备文件. 需要说明的是, 错误 ...
- UIActivityIndicatorView---iOS-Apple苹果官方文档翻译
本系列所有开发文档翻译链接地址: iOS7开发-Apple苹果iPhone开发Xcode官方文档翻译PDF下载地址 UIActivityIndicatorViewactivityIndicatorVi ...