Python Telnetlib模块连接网络设备

# -*- coding: UTF-8 -*-
import telnetlib
import time
import datetime
import os
import json


Username=
Password=
ip=
enable_passwd=
file='/opt/test.txt'

def connect(ip, username, password, enable_passwd):
    tn = telnetlib.Telnet(ip.encode('utf-8'))
    tn.read_until('Username: ')  # 用户名
    tn.write(username.encode('utf-8') + '\n')
    tn.read_until('Password: ')  # 密码
    tn.write(password.encode('utf-8') + '\n')
    tn.write('enable' + '\n')  
    tn.read_until('Password: ')   #enable 模式
    tn.write(enable_passwd.encode('utf-8') + '\n')
    if tn.read_until('#'):
        tn.write('terminal length 0' + '\n')
        print '登录成功'
        time.sleep(1)
        tn.write('configure terminal' + '\n')  # 进入设置模式
        time.sleep(1)
    return tn
    
    
def split_res(info):
    info = info.strip().split('\r\n')[1:-1]
    return '\n'.join(info)
    
    
def run_command(tn, command):
    print '开始执行命令: {}'.format(command)
    tn.write(command + '\n')
    time.sleep(3)
    strs =  split_res(tn.read_very_eager())
    return strs
    
def main(file):
    with open(file[0], 'r') as f:
        command_list = f.readlines()
    client = connect(ip, Username, Password, enable_passwd)
    for lien in command_list:
        print lien.split("\n")[0]
        res = run_command(client, lien.split("\n")[0])   # 执行配置下发
        print res
    print "执行完成"
    return True
    
    
if __name__ == '__main__':
    main(file)

 

posted @ 2020-07-16 14:17  QQmini  阅读(347)  评论(0编辑  收藏  举报