Netdevops入门之Telnetlib语法案例

news2025/4/22 3:06:57

1、Telnetlib模块:

支持telnet/ssh远程访问的模块很多,常见的有telnetlib、ciscolib、paramiko、netmiko、pexpect,其中telnetlib和ciscolib对应telnet协议,后面3个对应SSH协议。

①-通过ENSP环境搭建实验环境

②-基础语法-telnetlib案例1:

注意:python3中,telnetlib模块下所有的返回值都是字节流,而默认输入的都是普通字符串str,因此在python3中使用tlenetlib需要注意:

①在字符串的前面需要加上一个b; 转换成字节流

②在变量和tlentlib函数后面需要加上.encode('ascii')函数 进行解码

③在read_all()函数后面需要加上decode('ascii')函数

import telnetlib
import time

host = '192.168.2.11'
user = '111'
password = '111'
#执行telnet 并输入用户名和密码
tn = telnetlib.Telnet(host,port=23,timeout=1)  #tn实例化函数   telnet设备ip地址,(端口号,超时时间也可以不写,默认即可)
tn.read_until(b"Username",timeout=1)           #read函数  读取设备返回的Username字符串
tn.write(user.encode('ascii') + b'\n')         #将用户名转为ascii编码方式将字符串转换为bytes  \n回车
tn.read_until(b"Password:",timeout=1)
tn.write(password.encode('ascii') + b'\n')
print('已登录进设备'+ host)

tn.write(b"sys\n")  #写入命令
tn.write(b"int loopback 1\n")
tn.write(b"ip address 1.1.1.1 32\n")
tn.write(b"quit\n")
tn.write(b"quit\n")
tn.write(b"save\n")
tn.write(b"y\n")

time.sleep(2)   #时间模块,暂停2s  等待设备响应
output = (tn.read_very_eager().decode("ascii"))   #输出结果区域
print(output)
tn.close()

③-登录多台设备(for 循环)-telnetlib案例2:

通过列表添加设备ip,然后for循环调用执行

import telnetlib
import time

hosts =['192.168.2.11','192.168.2.12','192.168.2.13','192.168.2.14','192.168.2.15','192.168.2.16']
user = '111'
password = '111'

for ip in hosts:                    #循环执行hosts列表
    tn = telnetlib.Telnet(ip)      #tn实例化函数   telnet设备ip地址,(端口号,超时时间也可以不写,默认即可)
    tn.read_until(b"Username:")      #read函数  读取设备返回的Username字符串
    tn.write(user.encode('ascii') + b'\n')          #将用户名转为ascii编码方式将字符串转换为bytes  \n回车
    tn.read_until(b"Password:",timeout=1)
    tn.write(password.encode('ascii') + b'\n')
    print('已登录进设备'+ ip)

    tn.write(b"sys\n")  #写入命令
    tn.write(b"int loopback 1\n")
    tn.write(b"ip address 1.1.1.1 32\n")
    tn.write(b"quit\n")
    tn.write(b"quit\n")
    tn.write(b"save\n")
    tn.write(b"y\n")

    time.sleep(2)   #时间模块,暂停2s  等待设备响应
    output = (tn.read_very_eager().decode("ascii"))   #输出结果区域   转为ascii编码方式将字符串转换为bytes
    print(output)
    tn.close()

④-循环执行多条命令-telnetlib案例3:

定义主机ip列表

定义命令字符串列表

然后for循环执行以上列表

import telnetlib
import time

hosts =['192.168.2.11','192.168.2.12','192.168.2.13','192.168.2.14','192.168.2.15','192.168.2.16']  #s表示列表
user = '111'
password = '111'
commands = ['sys','int loopback 1','ip address 1.1.1.1 32','quit','quit','save','y']   #相当于把命令刷到文档里,s表示列表

for ip in hosts:
    tn = telnetlib.Telnet(ip)                #tn实例化函数   telnet设备ip地址,(端口号,超时时间也可以不写,默认即可)
    tn.read_until(b"Username:")              #read函数  读取设备返回的Username字符串
    tn.write(user.encode('ascii') + b'\n')   #将用户名转为ascii编码方式将字符串转换为bytes  \n回车
    tn.read_until(b"Password:",timeout=1)
    tn.write(password.encode('ascii') + b'\n')
    print('已登录进设备'+ ip)

    for command in commands:
        tn.write(command.encode('ascii')+b'\n')   #循环调用commands内的命令
    time.sleep(2)   #时间模块,暂停2s  等待设备响应
    output = (tn.read_very_eager().decode("ascii"))   #输出结果区域
    print(output)
    tn.close()

⑤-异常处理-telnetlib案例:

增加异常处理,防止某台交换机登录失败,导致程序中断

import telnetlib
import time

hosts =['192.168.2.11','192.168.2.12','192.168.2.13','192.168.2.14','192.168.2.15','192.168.2.16']  #s表示列表
user = '111'
password = '111'
commands = ['sys','int loopback 1','ip address 1.1.1.1 32','quit','quit','save','y']   #相当于把命令刷到文档里,s表示列表
Error= []                          #创建Error队列
for ip in hosts:                   #循环登录ip
    try:
        tn = telnetlib.Telnet(ip)       #tn实例化函数   telnet设备ip地址
        tn.read_until(b"Username:",timeout=1)     #read函数  读取设备返回的Username字符串
        tn.write(user.encode('ascii') + b'\n')    #将用户名转为ascii编码方式将字符串转换为bytes  \n回车
        tn.read_until(b"Password:",timeout=1)
        tn.write(password.encode('ascii') + b'\n')
        print('已登录进设备'+ ip)

        for command in commands:
            tn.write(command.encode('ascii')+b'\n')  #循环调用commands内的命令
        time.sleep(2)   #时间模块,暂停2s  等待设备响应
        output = (tn.read_very_eager().decode("ascii"))   #输出结果区域
        print(output)
        tn.close()
    
    except:    #只要登录错误都按如下打印
#   except TimeoutError:  # 只会处理timeoutError的错误
        print("登录失败,登录超时的设备IP:"+ip )
        Error.append(ip)       #append添加,附加,将失败的ip添加到Error的列表
print(Error)           #打印失败的设备ip

连接异常和密码错误异常 处理判断

⑥-通过文本读取IP和命令-telnetlib案例:

将ip地址或者命令放在txt文本文件中,通过脚本读取文本文件

import telnetlib
import time

hosts = open('hosts.txt','r')  #使用open函数  打开文本,并read 读取
user = '111'
password = '111'
commands = open('commands.txt','r')
ConnectionError= []    #连接失败的列表

for ip in hosts.readlines():                   #readline 逐行读取文本文件
    try:
        ip =ip.strip()       #strip函数可以去除文本中的回车和空格
        tn = telnetlib.Telnet(ip)       #tn实例化函数   telnet设备ip地址
        tn.read_until(b"Username:")     #read函数  读取设备返回的Username字符串
        tn.write(user.encode('ascii') + b'\n')    #将用户名转为ascii编码方式将字符串转换为bytes  \n回车
        tn.read_until(b"Password:")
        tn.write(password.encode('ascii') + b'\n')
        print('已登录进设备'+ ip)
        #print(f'已登录进设备:{ip}')

        commands.seek(0)           #光标每次读取完都会在最后,需要用seek函数将光标置于最前面
        for command in commands.readlines():
            tn.write(command.encode('ascii')+b'\n')       #循环调用commands内的命令
        time.sleep(2)
        output = (tn.read_very_eager()).decode("ascii")   #输出结果区域
        print(output)
        tn.close()
    except:                           #只要登录错误都按如下打印
        print("##########登录失败,登录超时的设备IP:"+ip+'##########' )
        ConnectionError.append(ip)    #append添加,附加,将失败的ip添加到ConnectionError的列表
print(ConnectionError)     

⑦-封装成函数解决问题-telnetlib案例:

将telnetlib封装成函数,方便小规模灵活应用,便于调用,同时增加input输入用户名和密码。允许部分交换机用户名和密码不同。

import telnetlib
import time

commands = open('commands.txt','r')
ConnectionError= []
AuthenFaill= []

def Telnet (host,username=input('请输入用户名:'),password=input('请输入密码:'),port=23):    #封装定义函数,定义host  username password
    try:
        tn = telnetlib.Telnet(host)       #tn实例化函数   telnet设备ip地址
        tn.read_until(b"Username:")     #read函数  读取设备返回的Username字符串
        tn.write(username.encode('ascii') + b'\n')    #将用户名转为ascii编码方式将字符串转换为bytes  \n回车
        tn.read_until(b"Password:")
        tn.write(password.encode('ascii') + b'\n')

        index,obj,oup=tn.expect([b'Info',b'Error'],timeout=1)
        if index ==0:
            print('已经成功登录设备'+host)
        elif index == 1:
            print('设备用户或密码错误'+host)
            AuthenFaill.append(host)

        commands.seek(0)           #光标每次读取完都会在最后,需要用seek函数将光标置于最前面
        for command in commands.readlines():
            tn.write(command.encode('ascii')+b'\n')       #循环调用commands内的命令
        time.sleep(2)
        output = (tn.read_very_eager()).decode("ascii")   #输出结果区域
        print(output)
        tn.close()
    except :
        print("连接异常失败IP:"+host)
        ConnectionError.append(host)    #append添加,附加,将失败的ip添加到ConnectionError的列表

Telnet('192.168.2.11')
Telnet('192.168.2.12')
Telnet('192.168.2.13',username='root',password='roo111')    #如果此台主机密码不同于其他,可以直接赋予正确的密码
Telnet('192.168.2.14')
Telnet('192.168.2.15')
Telnet('192.168.2.16')

print('-'*100)
print('认证失败的设备如下:')
print(AuthenFaill)
print('-'*100)
print('连接异常的设备如下:')
print(ConnectionError)

⑧-ping案例:

可以使用os.system或者subprocess模块实现ping检测 


import os
ip ='192.168.1.1'
response =os.system('ping -n 1 '+ip)   #发1包

if response ==0:
    print(ip,'is up!')
else:
    print(ip,'is down!')

或者

import os
host = ['192.168.1.1']
for ip in host:
    try:
        ping_result = os.system(f"ping -n 1 {ip}")
        if ping_result == 0:
            print(f"{ip} 连通性正常")
        else:
            print(f"{ip} 连通性异常")
    except Exception as e:
        print("检查 {ip} 连通性时出现异常:{e}")

或者

import subprocess   #subprocess模块执行ping命令(只返回结果不返回打印)
host = ['192.168.1.1']
for ip in host:
    try:
        command = ['ping', '-n', str(1), ip]
        result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
       #朱提部分subprocess.run执行命令,捕获输出但不打印
        if result.returncode == 0:  #检查是否执行成功
            print('ok')
        else:
            print('pok')
            #print('pok',result.stderr) 如果需要可以打印错误信息
    except Exception as e:
        print("检查 {ip} 连通性时出现异常:{e}")

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1969331.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

最优控制、轨迹优化相关笔记、感悟

写在前面 上学期和最近无聊在看一些最优控制、轨迹优化相关的内容,涉及到MIT Russ Tedrake教授的Underactuated Robotics,以及CMU Zachary Manchester教授的Optimal Control(两套课程其实挺像的),加起来估计也看了十多…

机器学习算法(二)线性模型

一、线性回归 假设自变量X矩阵有3个特征,因变量是Y矩阵,w是系数矩阵 Y X * w 损失函数:误差平方和函数(Y - label)** 2 二、逻辑回归 线性回归得到的是一个实数值 z ,用sigmoid函数可以将其映射到 0 …

【SQL Server 】SQL Server 网络配置

目录 ​编辑 第3章:SQL Server 网络配置 SQL Server 网络监听器 SQL Server 网络协议 配置 SQL Server 网络协议 示例:配置 SQL Server 使用自定义端口 安全注意事项 第3章:SQL Server 网络配置 SQL Server 网络监听器 SQL Server 通…

php时间 cookie session 文件上传基础

时间和日期 PHP Date() 函数 格式// date(format,timestamp) format Required. Specifies the format of the timestamp timestamp Optional. Specifies a timestamp. Default is the current date and time d - 表示每月的某一天(01…

反序列化漏洞靶机实战-serial

一.安装靶机 下载地址为https://download.vulnhub.com/serial/serial.zip,安装好后开启靶机,这里并不需要我们去登录,直接扫描虚拟机nat模式下c网段的ip,看看哪个的80端口开放,然后直接去访问 二.查找cookie 访问靶…

Java Try学习

一. 介绍 io.vavr.control.Try 是 Vavr 库的一个类,用于处理可能抛出异常的方法调用;它提供了一种优雅的方式来处理成功和失败的情况,而无需显示地使用 try-catch 块; 简而言之,它可以优雅的实现 try-catch&#xff…

链表【4】

目录 链表删除指定值元素 反转链表&#xff08;静态链表型&#xff09; 链表删除指定值元素 错误1&#xff1a;两个if间没有用else&#xff0c;导致两个都执行了 #include<stdio.h> const int N1005; int n,first,firstid; using namespace std; struct node {int da…

【Vue3】作用域插槽

【Vue3】作用域插槽 背景简介开发环境开发步骤及源码 背景 随着年龄的增长&#xff0c;很多曾经烂熟于心的技术原理已被岁月摩擦得愈发模糊起来&#xff0c;技术出身的人总是很难放下一些执念&#xff0c;遂将这些知识整理成文&#xff0c;以纪念曾经努力学习奋斗的日子。本文…

UI界面自动化测试-Selenium

Selenium工作原理 SeleniumAPI 定位元素 Selenium操作对象 **send_keys 在对象上模拟按键输入 ** clear 清除对象输入的文本内容 ** click 点击对象(无限制) submit 提交(用于form表单) ** getText() 用于获取元素的文本信息 getAttribute() 用于获取属性的值 quit 关闭…

【奥顺苹果CMS二开泛目录4.X版】PHP站群程序新增首页堆砌关键词新增四套seo模板

演示站&#xff08;赠送四套模板&#xff09;&#xff1a; https://macfan.qdwantong.com https://macfan2.qdwantong.com https://macfan3.qdwantong.com https://macfan4.qdwantong.com 4.X版程序特色功能&#xff1a; 后台除了可以设置干扰码、转码、插入符号和拼音这…

[Bugku] web-CTF-矛盾

1.开启环境 2.根据内容得知&#xff0c;get一个num&#xff0c;若num不是数字&#xff0c;出一次num的值&#xff0c;后若num1出flag&#xff1b;若num为数字则不进行任何操作所以要输出flag&#xff0c;首先要num不是数字&#xff0c;然后又要num1这显然是矛盾的&#xff0c;对…

transform详解

参考&#xff1a;https://zhuanlan.zhihu.com/p/690055241 https://zhuanlan.zhihu.com/p/685724799 https://zhuanlan.zhihu.com/p/609523552 cnn是通过卷积核的方式实现权重偏置的计算&#xff0c;ywkb&#xff0c;激活&#xff0c;前馈神经网络&#xff0c;反向传播。 trans…

P31结构体初阶

结构体的声明 结构体的基础知识 结构是一些值的集合&#xff0c;这些值成为成员变量。结构的每个成员可以是不同类型的变量。 结构体的声明 结构成员的类型 结构的成员可以是标量、数组、指针&#xff0c;甚至是其他结构体 结构体变量的定义和初始化 结构体成员的访问 结构…

AI技能提升学习-免费24年最新甲骨文(OCI)开卷AI证书(有答案)+代码调用OCI生成式AI服务教程

之前好多小伙伴和我反馈错过了24年甲骨文的AI专家级证书免费考试&#xff0c;这次小李哥就给大家带来了24年最新的OCI另外一门AI基础级考试&#xff0c;主要目的是帮助大家提升AI/ML的基础知识和技能&#xff0c;给大家带来免费的学习福利&#xff0c;赶紧关注小李哥不要再错过…

大数据技术原理-spark编程与应用

摘要 本实验总结了在"大数据技术原理"课程中进行的Spark编程实验。实验环境基于Apache Spark&#xff0c;旨在通过实践加深对Spark数据处理能力的理解。实验的主要内容包括开启Spark shell、导入必要的包、读入数据集、数据预处理、聚类模型训练、确定数据模型的中心…

STM32内部Flash存贮数据的应用(STM32F446)

目录 概述 1 STM32内部Flash介绍 1.1 MCU简介 1.2 存储空间 1.3 主要特性 1.4 嵌入式闪存 2 库函数介绍 2.1 编程接口函数 2.2 锁和解锁函数 3 功能实现 3.1 写数据函数&#xff1a;FlashDrv_Write 3.2 读数据函数&#xff1a; FlashDrv_read 3.3 源代码 4 测试…

carla unreal engine源码:如何自定义开发传感器

文章目录 前言一、目标二、代码内容三、工程搭建1、更改点总览2、工程修改1&#xff09;代码文件拷贝至目标路径2&#xff09;SafeDistanceSensor.cpp 修改3&#xff09;SafeDistanceSerializer.h 修改4&#xff09;SafeDistanceEvent.h 修改5&#xff09;Sensor.h 修改6&#…

大数据技术原理-NoSQL数据库的应用

摘要 本实验报告聚焦于"大数据技术原理"课程中的NoSQL数据库实验。实验环境包括MySQL、Redis、MongoDB、Java以及Hadoop。实验内容涉及Redis和MongoDB的安装、配置和基本操作&#xff0c;包括数据的插入、删除和查询。此外&#xff0c;实验还包括使用Java API对Mong…

【统计全为 1 的正方形子矩阵】python刷题记录

R3-分治篇 class Solution:def countSquares(self, matrix: List[List[int]]) -> int:rowlen(matrix)collen(matrix[0])dp[[0]*(col1) for _ in range(row1)]ret0for i in range(row):for j in range(col):if matrix[i][j]1:dp[i1][j1]min(dp[i][j1],dp[i1][j],dp[i][j])1re…

umi-request全局响应拦截器

文章目录 介绍思路实现方法1.直接修改 umi-request方法2.自定义 request 实例&#xff0c;通过 umi-request 库进行配置 介绍 后端设计统一返回比如BaseResponse对象&#xff0c;前端也需要接收这个对象&#xff0c;从data取出想要的返回值。 前端请求比如之前返回的是numbe…