Netdevops入门之Telnetlib语法案例

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 timehost = '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 timehosts =['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编码方式将字符串转换为bytesprint(output)tn.close()

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

定义主机ip列表

定义命令字符串列表

然后for循环执行以上列表

import telnetlib
import timehosts =['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 timehosts =['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:                   #循环登录iptry: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 timehosts = 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 timecommands = open('commands.txt','r')
ConnectionError= []
AuthenFaill= []def Telnet (host,username=input('请输入用户名:'),password=input('请输入密码:'),port=23):    #封装定义函数,定义host  username passwordtry: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.mzph.cn/pingmian/51310.shtml

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

相关文章

16现代循环神经网络—深度循环与双向循环

目录 1.深度循环神经网络回顾:循环神经网络总结简洁代码实现2.双向循环神经网络隐马尔可夫模型中的动态规划双向模型模型的计算代价及其应用总结代码实现1.深度循环神经网络 回顾:循环神经网络 如何将循环神经网络变深,以获得更多的非线性? 通过添加多个隐藏层的方式来实现…

解决git每次push代码到github都需要输入用户名以及密码

产生原因: 出现以上情况的主要原因在于采用的是 https 方式提交代码, 如果采用的是 ssh 方式只需要在版本库中添加用户的 sha 的key就可以实现提交时无需输入用户名和密码。 解决方法 在终端中使用以下命令删除原先已经建立的http的链接方式&#xff0c…

KCache-go本地缓存,支持本地缓存过期、缓存过期自维护机制。

GitHub - kocor01/kcache: go 本地缓存解决方案,支持本地缓存过期、缓存过期自维护机制。 最近系统并发很高,单接口10W的 QPS,对 redis 压力很大,大量的热KEY导致 redis 分片CPU资源经常告警。计划用 go 本地缓存缓解 redis 的压…

git实践汇总【配置+日常使用+问题解决】

**最初配置步骤:** git config --global user.name "yournemae" git config --global user.email "yourmail" git config -l ssh-keygen -t rsa -C “xxx.xxxx.EXTcccc.com” git config --global ssh.variant ssh $ git clone git仓库路径 git…

洗地机哪家好?四款洗地机好洗地机的品牌推荐

随着“懒人经济”的兴起,洗地机作为家居清洁领域的革新者,正逐步融入越来越多家庭的生活之中。面对市场上繁多的洗地机品牌与型号,消费者往往感到难以抉择:“洗地机哪个牌子最佳?”为了解答这一疑问,本文精…

KubeSphere介绍及一键安装k8s

KubeSphere介绍 官网地址:https://kubesphere.io/zh/ KubeSphere愿景是打造一个以 Kubernetes 为内核的云原生分布式操作系统,它的架构可以非常方便地使第三方应用与云原生生态组件进行即插即用(plug-and-play)的集成&#xff0…

C++ --> string类模拟实现(附源码)

欢迎来到我的Blog,点击关注哦💕 前言: C中STL扮演着极其重要的角色,学习C重中之重的就是学习STL,虽然string不作为containers的其中一员,但是也是值得学习的le类。下面就进行string的模拟实现 string的模拟…

C++ | Leetcode C++题解之第284题窥视迭代器

题目&#xff1a; 题解&#xff1a; template <class T> class PeekingIterator : public Iterator<T> { public:PeekingIterator(const vector<T>& nums) : Iterator<T>(nums) {flag Iterator<T>::hasNext();if (flag) {nextElement Ite…

docker 的常用命令随笔

sudo docker --help docker build -t demo:v1 systemctl start docker service docker start sudo docker ps -a sudo docker images sudo docker restart xx&#xff08;容器名&#xff09; sudo docker exec -it xxx (容器名) bash sudo docker run -it xxx:xx(镜…

【MyBatis】基础操作

准备工作 准备数据库表创建 springboot工程&#xff0c;选择引入对应的起步依赖&#xff08;mybatis、mysql驱动、lombok&#xff09;application.properties中引入数据库连接信息创建对应的实体类 Emp&#xff08;实体类属性采用驼峰命名&#xff09;准备Mapper接口 EmpMappe…

【C语言】队列的实现(数据结构)

前言&#xff1a; 相信大家在生活中经常排队买东西&#xff0c;今天学习的队列就跟排队买东西一样&#xff0c;先来买的人就买完先走&#xff0c;也就是先进先出。废话不多说&#xff0c;进入咱们今天的学习吧。 目录 前言&#xff1a; 队列的概念 队列的实现 队列的定义 …

【es】多个中文无法模糊查询

es 的 text类型字段会分词处理&#xff0c;模糊查询有单个中文能查&#xff0c;多个中文就不行了 改为keyword类型 ES模糊查询失效的坑以及解决方案_java_脚本之家

DDR等长,到底长度差多少叫等长?

DDR4看这一篇就够了 - 知乎 (zhihu.com) 【全网首发】DDR4 PCB设计规范&设计要点PCB资源PCB联盟网 - Powered by Discuz! (pcbbar.com) 终于看到较为权威的DDR4等长要求了: !!!! 依据这个要求&#xff0c;H616项目的等长线不合格&#xff1a;

C/S架构和B/C架构

C/S架构&#xff08;Client/Server Architecture&#xff09;和B/C架构&#xff08;Browser/Client Architecture&#xff09;是两种不同 的软件架构模型&#xff0c;它们各自有不同的特点和应用场景。 一、C/S架构&#xff08;Client/Server Architecture&#xff09; 1. 定…

Vue的指令语法、双向绑定、el和data的另一种写法、MVVM模型

目录 1. 指令语法1.1 双向绑定 2. el和data的另一种写法3. MVVM模型 1. 指令语法 用于解析标签&#xff08;包括&#xff1a;标签属性、标签体内容、绑定事件…&#xff09;。Vue中有很多的指令&#xff0c;且形式都是&#xff1a;v-xxxx&#xff0c;此处我们只是拿v-bind举个…

C++第二十八弹---进一步理解模板:特化和分离编译

✨个人主页&#xff1a; 熬夜学编程的小林 &#x1f497;系列专栏&#xff1a; 【C语言详解】 【数据结构详解】【C详解】 目录 1. 非类型模板参数 2. 模板的特化 2.1 概念 2.2 函数模板特化 2.3 类模板特化 2.3.1 全特化 2.3.2 偏特化 2.3.3 类模板特化应用示例 3. …

前端学习7——自学习梳理

​​​​​​jQuery 教程 | 菜鸟教程jQuery 教程 jQuery 是一个 JavaScript 库。 jQuery 极大地简化了 JavaScript 编程。 jQuery 很容易学习。 本章节的每一篇都包含了在线实例 通过本站的在线编辑器&#xff0c;你可以在线运行修改后的代码&#xff0c;并查看运行结果。 实例…

Redis的事务_乐观锁与悲观锁

目录 一 Redis事务-介绍 二 事务的基本操作 三 Redis事务-乐观锁与悲观锁 四 Redis事务-特性 一 Redis事务-介绍 Redis事务可以一次执行多个命令&#xff0c;本质是一组命令的集合&#xff0c;一个事务中的所有命令都会序列化&#xff0c;按顺序的串行化执行&#xff0c;而…

【开源库学习】libodb库学习(十二)

13 数据库架构演变 当我们添加新的持久类或更改现有的持久类时&#xff0c;例如&#xff0c;通过添加或删除数据成员&#xff0c;存储新对象模型所需的数据库模式也会发生变化。同时&#xff0c;我们可能有包含现有数据的现有数据库。如果应用程序的新版本不需要处理旧数据库&a…

使用 XRDP 远程linux主机

一、简介 XRDP是一个开源的远程桌面协议&#xff08;Remote Desktop Protocol,RDP&#xff09;服务器&#xff0c;采用的是标准的RDP。 官网地址&#xff1a;https://www.xrdp.org/ github地址&#xff1a; https://github.com/neutrinolabs/xrdp/releases XRDP也是C/S架构&…