#!/usr/bin/env python #_*_coding:utf-8_*_ #Author:Tiger At ''' 1.此腳本使用python3編寫 2.此腳本用於通過linux堡壘機登錄網絡設備 3.僅供學習和參考 ''' #導入對應模塊 from netmiko import ConnectHandler from netmiko import redispatch import getpass from datetime import datetime import time #輸入堡壘機IP地址 jumpserver_ip = input('jumpserver_ip: ') #輸入堡壘機用戶名 jumpserver_username = input('jumpserver_username: ') #輸入堡壘機用戶密碼,注getpass模塊在pycharm上運行有問題 jumpserver_password = getpass.getpass('jumpserver_password: ') #定義堡壘機 jumpserver = { #定義堡壘機類型 'device_type': 'ovs_linux', #定義堡壘機IP 'ip': jumpserver_ip, #定義堡壘機用戶名 'username': jumpserver_username, #定義堡壘機密碼 'password': jumpserver_password, } #輸入要管理設備的用戶名/密碼信息 username = input('aaa_username: ') password = getpass.getpass('aaa_password: ') #從文件“ip_list.txt”讀取設備管理IP地址信息,默認在同級目錄下創建此文件即可 ip_file = list(open('ip_list.txt', 'r')) #從文件“command.txt”讀取操作命令信息,默認在同級目錄下創建此文件並添加對應要執行的命令即可 command_file = list(open('command.txt', 'r')) #打開錯誤文件“Error_list.txt”以便存放錯誤信息,默認在同級目錄下創建此文件即可 error_file = open('Error_list.txt', 'a') #創建連接堡壘機對象,連接堡壘機 net_connect = ConnectHandler(**jumpserver) for line in ip_file: #顯示堡壘機提示符 print(net_connect.find_prompt()) try: #獲取IP地址信息 ip = line.strip() #打印當前時間 print('===============================' + datetime.now().strftime( "%Y-%m-%d %H:%M:%S") + '===============================' + '\n') #進行telnet操作 net_connect.write_channel('telnet ' + ip + '\n') #等待2秒 time.sleep(2) #存儲登錄結果,后續用於判斷 result = net_connect.read_channel() #打印登錄結果 print(result) #根據返回結果判斷是否使用ssh登錄 if 'foreign host' in result or 'Connection refused' in result: #嘗試SSH登錄 net_connect.write_channel('ssh -l ' + username + ' ' + ip + '\n') time.sleep(1) #存儲SSH結果 result1 = net_connect.read_channel() #打印SSH結果 print(result1) #判斷是否提示存儲秘鑰 if '(yes/no)' in result1: net_connect.write_channel('yes' + '\n') time.sleep(1) #輸入密碼進行登錄 net_connect.write_channel(password + '\n') time.sleep(1) #判斷TELNET登錄提示符,用於TELNET登錄 if 'username' in result or 'Username' in result: #調用用戶名/密碼信息嘗試TELNET登錄 net_connect.write_channel(username + '\n' + password + '\n') time.sleep(1) #關聯設備類型,以便后續進行對應廠家命令操作 redispatch(net_connect, device_type='cisco_ios') #打印設備提示符 print(net_connect.find_prompt()) #獲取相應命令,進行相關命令輸入 for command in command_file: show_commands = command.strip() #保存命令輸入結果 output = net_connect.send_command(show_commands) #創建對應記錄保存文件 syslog = open(ip + '.txt', 'a+') #將結果寫入創建的日志文件 syslog.write(net_connect.find_prompt() + show_commands + '\n' + output + '\n') #退出設備 net_connect.send_command_timing('exit') 異常存儲及打印 except: print(ip + ' error') error_file.write(ip + ' error' + '\n')