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\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:
        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\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:
client.close()

if __name__ == '__main__':
userinfo={'host':"192.168.1.1","user":"test","passwd":"test"}
get_info(**userinfo)
posted @ 2020-02-19 21:32  HuTiger  阅读(1381)  评论(1编辑  收藏  举报