跨堡垒机连接二级服务器执行命令——python实现代码

来源:互联网 发布:网红开的淘宝店的货源 编辑:程序博客网 时间:2024/06/05 16:42

在linux下实现,需要使用paramiko和re模块

过程:

1.用paramiko连接堡垒机

2.构造数据包并发送(包内为用户命令)

3.接收数据包,用正则表达式提取出所需信息

#!/usr/bin/python# encoding:utf-8import paramikoimport reclass SecConnect:    def __init__(self):        self.ssh = paramiko.SSHClient()        self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())        bip = '堡垒机的ip地址'        buser = '堡垒机用户名'        bpasswd = '堡垒机密码'        sip = '目标主机ip'        suser = '目标主机用户名'        spasswd = '目标主机密码'        port = 22        passinfo = "\'s password: "  # 返回要求输入密码的提示字串                # 连接堡垒机        self.ssh.connect(bip, 22, buser, bpasswd)        self.channel = self.ssh.invoke_shell()        self.channel.settimeout(10)                self.repeat = 0  # 要区分是否为第一次调用命令,第一次与后续调用格式不同        buff = ''        resp = ''        # 连接目标主机        self.channel.send("ssh " + suser + '@' + sip + '\n')        while not buff.endswith(passinfo):            try:                resp = self.channel.recv(9999)            except Exception, e:                print e            buff += resp            if not buff.find('yes/no') == -1:                print "ok"                self.channel.send('yes\n')                buff = ''        self.channel.send(spasswd + '\n')            # 若需要,输入sudo的权限及密码,缺省为用户权限       def do_commend(self, commend, permission='user', passwd=''):        """执行命令,返回显示结果"""        # 以数据包的形式接受目标主机返回的信息        if permission == 'sudo':            commend = 'sudo ' + commend + '\n'            self.channel.send(commend)            buff = ''            try:                while buff.find('# ') == -1:                    resp = self.channel.recv(9999)                    buff += resp            except Exception, e:                print e            # print buff            self.channel.send(passwd + '\n')        else:            commend += '\n'            self.channel.send(commend)        buff = ''        recall = ''        try:            while buff.find('# ') == -1:                resp = self.channel.recv(9999)                buff += resp        except Exception, e:            print e        # print buff                # 正则表达式提取出需要的回执信息        start = 0        finish = 0        if self.repeat == 0:    # 第一次调用命令            # print "fir"            flag1 = 0            flag2 = 0            for i in range(len(buff)):                if buff[i] == '$':                    flag1 += 1                    continue                elif flag1 == 1 and flag2 == 0:                    if buff[i] == '\n':                        start = i + 1                        flag2 = 1                        continue                elif flag1 == 1 and flag2 == 1:                    if buff[i] == '\n':                        finish = i - 1                        self.repeat = 1        elif self.repeat == 1:            lines = 1            flag = 0            for i in range(len(buff)):                if buff[i] == '\n' and lines > 0:                    lines -= 1                    start = i+1                elif lines == 0:                    flag = 1                if flag == 1 and buff[i] == '\n':                    finish = i-1        # print start, finish        tip = start        for i in range(finish - start + 1):            recall += buff[tip]            tip += 1        # print recall        return recall    def close(self):        """关闭全部连接(堡垒机和二级主机)"""        self.channel.close()        self.ssh.close()


0 0
原创粉丝点击