zoukankan      html  css  js  c++  java
  • Python利用paramiko模块ssh防火墙执行命令

    一、前言

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

     

    二、代码

    #-*- coding: utf-8 -*-
    import time
    
    import paramiko
    
    def remote_login(**kwargs):
        try:
            ssh = paramiko.SSHClient()
            ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            ssh.connect(kwargs['host'], 22 ,kwargs['user'], kwargs['passwd'] ,timeout=2)
            return ssh
        except Exception as e:
            print(e)
            return None
    
    def get_info(**kwargs):
        #登录防火墙
        client = 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
    ')
            time.sleep(1)
            remote_conn.send('show configuration
    ')
            while True:#循环拿取返回内容,直到获取到End结束,跳出循环
                result += remote_conn.recv(1024)
                if result and "End" in result:
                    break
            print(result)
        except Exception as e:
            print(e)
        finally:
            client.close()
    
    if __name__ == '__main__':
        userinfo={'host':"192.168.1.1","user":"test","passwd":"test"}
        get_info(userinfo)

     

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

    import paramiko

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

    def get_info(**kwargs):
    #登录防火墙
    client = 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 ')
    time.sleep(1)
    remote_conn.send('show configuration ')
    while True:#循环拿取返回内容,直到获取到End结束,跳出循环
    result += remote_conn.recv(1024)
    if result and "End" in result:
    break
    print(result)
    except Exception as e:
    print(e)
    finally:
    client.close()

    if __name__ == '__main__':
    userinfo={'host':"192.168.1.1","user":"test","passwd":"test"}
    get_info(**userinfo)
  • 相关阅读:
    设置SSH编码为中文
    深入浅出REST架构 REST架构概述
    RESTful Web Services初探
    Linux 基础命令
    Linux 目录和文件操作
    Linux 压缩文件的命令行总结
    Linxu 监控命令总结
    Linux 下Tomcat的启动、关闭、杀死进程
    Linux日知录(常用问题笔记)
    linux 下远程连接mysql命令详解
  • 原文地址:https://www.cnblogs.com/huguodong/p/12333323.html
Copyright © 2011-2022 走看看