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)
本文来自博客园,作者:HuTiger,转载请注明原文链接:https://www.cnblogs.com/huguodong/p/12333323.html,欢迎加入qq群927460240学习讨论