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)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM