【Python实践】自定义操作服务器+ssh免密码登录

在企业里面,为了IDC机器的安全,通常不能直接登录IDC里面的机器,通过需要通过跳板机登录,在跳板机上面放置如下脚本,可以省去大量的登录工作。当然,也可以通过secureCRT的login script,但是每次输入跳板机的密码也是件麻烦事情。 
以下脚本存在不足的地方是需要明文保存密码,vi之后会出现点可视区域变小。实现来源来自互联网,只是稍加改动,增加了信任机器间直接登录的情况。需要安装pexpect,安装方式搜索pexpect+python即可。 

首先说一下如何实现免密码登录服务器

源代码访问网址https://github.com/buzheng1949/Athena/tree/master/FreeServer

查看服务器的时候,需要经过登录堡垒机,输入查看的服务器的IP地址,输入命令对服务器进行操作的流程,为此学习了Python之后,鼓捣了一个Python版本的免密码登录服务器的脚本。

一、需求分析

登录堡垒机

登录服务器

输入命令

二、方案选择

首先我们考虑的是Linux下是可以用expect进行ssh交互的,强大如Python当然也有这个能力,于是我们就自然想到了Python的pexpect库。

三、方案实现

得到服务器的回应后,对我进行了密码输入的请求

第三步,发送完密码之后,我们已经实现了登录堡垒机的功能,如下图所示:

接下来就是输入我们需要登录的服务器的IP地址,然后再次输入密码,只需要调用两次pexpect的sendline方法即可完成服务器的交互。

ret_watch_server = child.expect([watch_server_ip,pexpect.TIMEOUT]) if ret_watch_server != 0: print ('the password is correct,but the server ip maybe you have no perssion,please apply it') return else: child.sendline(watch_server_ip) child.expect('password') child.sendline(password)

第四步,但是即使进行免密码登录之后,我们还是很困扰,因为我们有两个问题还没解决,第一个问题是如何当我们想要登录查看的机器很多的时候,难道我每次都去改脚本的服务器的IP地址么?第二个问题是,难道我每次都需要去执行python xxx.py的方式去执行我们的脚本么?

第一个问题的解决方式:我们可以使用docopt库进行在命令行执行Python命令的同时带上你想登录的服务器的IP地址。如下所示:

这样我们就可以在执行Python命令的时候,按照usage的方式输入然后解析watch_server_ip字段的方式进行自定义查看服务器而无需改脚本的方式。如下图所示,在入口进行简单的判断:

第二个问题的解决方式:我们可以使用setuptools搞事情,代码如下所示:

从上面我们可以看到,我们定义了一个脚本,自定义了一个命令叫freeserver,然后调用freeserver脚本的时候,调用脚本的main方法。编写完以上代码之后,我们执行python3 setup.py install 方法,就可以完成自定义命令行的方式输入而无需执行Python xxx.py xxxx_ip的麻烦的方式了。第五步,让我们来看看效果吧,虽然都打了马赛克,但是红红绿绿的可以看到我们的脚本确实成功了。

果不其然的源代码分享

freeserver.py代码

"""免密码登录远端服务器Usage: freeserver <watch_server_ip>Examples: freeserver xxxxxxx"""import pexpectimport os import getpassfrom docopt import docopt# 实现免密码登录方法def login(fortresses_ip,user_name,password,watch_server_ip,command): child = pexpect.spawn('ssh -pxxx %s@%s'%(user_name,fortresses_ip)) ret_login = child.expect(['%s@%s's password:'%(user_name,fortresses_ip),pexpect.TIMEOUT]) if ret_login == 1: print ('login the remote server ip is timeout') return else: child.sendline(password) ret_password = child.expect(['This is a beta version. If you find bugs, please contact @Securit',pexpect.TIMEOUT]) if ret_password == 1: print ('the password is wrong,please check the password') return else: child.sendline('p') ret_watch_server = child.expect([watch_server_ip,pexpect.TIMEOUT]) if ret_watch_server != 0: print ('the password is correct,but the server ip maybe you have no perssion,please apply it') return else: child.sendline(watch_server_ip) child.expect('password') child.sendline(password) child.expect('Powered') if command is not None: child.sendline(command) child.sendline('tailf web.log') child.interact()def main(): arguments = docopt(__doc__) watch_server_ip = arguments.get('<watch_server_ip>') user_name = 'your user name' password = 'your password' fortresses_ip = 'fortresses_ip' command = 'your command when your want success enter the ip server' login(fortresses_ip,user_name,password,watch_server_ip,command)if __name__ == '__main__': main()

setup.py

from setuptools import setup setup( name='freeserver', py_modules=['__inti__', 'freeserver'], install_requires=['pexpect'], entry_points={ 'console_scripts': ['freeserver=freeserver:main'] } )

#!/usr/bin/python  
#coding=utf-8  
# 这是一个登录服务器的自动ssh脚本 ,需要安装pexpect module
#   
#  
# @created on 2012.3.7 5:56 am  
#  
import os  
import sys  
import pexpect  
import string  
  
Server_Ip={  
  
    "主机代号":["主机IP地址","登录账户","密码","服务器用途"]  
#   在此处添加主机列表      
}  
  
def auto_connect():  
    """ 
    自动登录实现,提供选择功能 
    """  
    while True:  
        print "\n\n###########################################################"  
        for server in Server_Ip.keys():  
            print "["+server+"]=>"+"["+Server_Ip[server][0]+"]"+" [服务器用途]=>"+"["+Server_Ip[server][3]+"]"  
        print "###########################################################\n"  
        destination=raw_input("[forest,which server do you want to connect?]=>")  
         
        if(Server_Ip.has_key(destination)):  
            print "\n正在连接服务器"+destination  
            break  
        else:  
            print "\n服务器没有添加到列表中"  
            return  
    URL="ssh %s@%s"%(Server_Ip[destination][1],Server_Ip[destination][0])  
#   print URL  
#   发起连接进程    
    try:  
        p=pexpect.spawn(URL)  
        if Server_Ip[destination][2] != "":
            p.expect("password:")
            p.sendline(Server_Ip[destination][2]+"\n")
        p.interact()  
    except:  
        print "关闭连接"  
auto_connect()  

用Python写个自动ssh登录远程服务器的小工具 - https://www.cnblogs.com/jiaoyu121/p/7027694.html

好啦本期讲完了,喜欢各位大大能给辛苦的小编点一个关注,谢谢!~(写的不好,高手勿喷!)

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值