Python利用paramiko模块ssh防火墙执行命令

一、前言

  在日常运维的过程中,需要登录防火墙执行命令,该脚本可以通过paramiko模块远程登录执行命令,并返回结果。

 

二、代码

#-*- coding: utf-8 -*-
import time

import paramiko

def remote_login(self, **kwargs):
    try:
        self.ssh = paramiko.SSHClient()
        self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        self.ssh.connect(kwargs['host'], 22 ,kwargs['user'], kwargs['passwd'] ,timeout=2)
        return self.ssh
    except Exception as e:
        print(e)
        return None

def get_info(**kwargs):
    #登录防火墙
    client = self.remote_login(**kwargs)
    if client is None:
        # self.logger.error(u'登录失败,跳过')
        return None
    # 获取防火墙规则
    result = ""
    try:
        remote_conn = client.invoke_shell()
        time.sleep(4)
        remote_conn.send('terminal length 0\n')
        time.sleep(1)
        remote_conn.send('show configuration\n')
        while True:#循环拿取返回内容,直到获取到End结束,跳出循环
            result += remote_conn.recv(1024)
            if result and "End" in result:
                break
        print(result)
    except Exception as e:
        print(e)
    finally:
        self.ssh.close()

if __name__ == '__main__':
    userinfo={'host':"192.168.1.1","user":"test","passwd":"test"}
    get_info(userinfo)

 

猜你喜欢

转载自www.cnblogs.com/huguodong/p/12333323.html
今日推荐