# !/usr//bin/python3
# -*- coding:UTF-8 -*- from telnetlib import Telnet
import time, os, datetime, json
import logging class TelnetClient(): def __init__(self):
self.tn = Telnet() def __login_host(self, ip, username, password, enable=None, verbose=True):
try:
self.tn.open(ip, port=23)
except:
logging.warning('%s网络连接失败' % ip)
return False
self.tn.read_until(b'Username:', timeout=1)
self.tn.write(b'\n')
self.tn.write(username.encode() + b'\n')
rely = self.tn.expect([], timeout=1)[2].decode().strip() # 读显
if verbose:
print(rely)
self.tn.read_until(b'Password:', timeout=1)
self.tn.write(password.encode() + b'\n')
rely = self.tn.expect([], timeout=1)[2].decode().strip()
if verbose:
print(rely)
if enable is not None:
self.tn.write(b'enable\n')
self.tn.write(enable.encode() + b'\n')
if verbose:
rely = self.tn.expect([], timeout=1)[2].decode().strip()
print(rely)
time.sleep(1)
time.sleep(2)
rely = self.tn.read_very_eager().decode()
if 'Login invalid' not in rely:
logging.warning('%s登陆成功' % ip)
return True
else:
logging.warning('%s登陆失败,用户名或密码错误' % ip)
return False def __do_cmd(self, cmd, location=None):
if location:
os.system('mkdir backup\\{}'.format(location))
with open('backup/{}/configuration_{}.txt'.format(location, datetime.date.today()), 'w') as f:
self.tn.write(cmd.encode().strip() + b'\n')
time.sleep(3)
rescmd = self.tn.read_very_eager().decode()
f.write(rescmd)
logging.warning('命令执行结果:\n %s' % rescmd)
return True
else:
os.system('mkdir backup')
with open('backup/configuration_{}.txt'.format(location, datetime.date.today()), 'w') as f:
self.tn.write(cmd.encode().strip() + b'\n')
time.sleep(3)
rescmd = self.tn.read_very_eager().decode()
f.write(rescmd)
logging.warning('命令执行结果:\n %s' % rescmd)
return True def telnet_login(self, ip, user, pwd, enable=None, cmd=None, location=None):
res1 = self.__login_host(ip, user, pwd, enable)
if res1:
for i in cmd.split(';'):
self.__do_cmd(i, location)
self.__logout_host()
return True
else:
self.__logout_host()
return False def __logout_host(self):
self.tn.close() if __name__ == '__main__':
username = 'cisco' # 用户名
password = 'cisco' # 密码
# 存放设备登陆信息和要执行的命令(多条命令用;隔开),示例:["ip", "username", "password", "enable_password", "terminal length 0;show run", "backup_path"]
lists = 'list.text'
with open('test.txt', 'rt', encoding='utf-8') as list_obj:
# textline = list_obj.readline()
# while textline != '':
# print(json.loads(textline))
# textline = list_obj.readline()
telnet_client = TelnetClient()
for line in list_obj:
hostmsg = json.loads(line)
telnet_client.telnet_login(hostmsg[0], hostmsg[1], hostmsg[2], hostmsg[3], hostmsg[4])

常见网络设备命令结果全部显示

<H3C> screen-length disable     # no screen-length disable (华三)
Cisco# terminal length 0 # terminal no length (思科)
MaiPu# more off # more on (迈普)
<HuaWei> screen-length 0 temporary # undo screen-length temporary (华为)
RuiJie# terminal length 0 # terminal no length (锐捷)
ZTE# terminal length 0 # no terminal length (中兴)

常见网络设备巡检命令
https://blog.csdn.net/qq_46417230/article/details/122336116

Telnet登陆网络设备执行命令脚本的更多相关文章

  1. expect实现远程主机自动执行命令脚本

    2014年第一个脚本,哈哈!!! expect实现远程主机自动执行命令脚本: #!/usr/bin/expect -- if { [llength $argv] < 4 } { puts &qu ...

  2. Python-SSH批量登陆并执行命令

    Python-SSH批量登陆并执行命令 #!/usr/bin/env python #-*- coding:utf-8 -*- import paramiko from time import cti ...

  3. Shell下通过echo+telnet在远端执行命令

    创建脚本cmd.sh,用于输入telnet的用户与密码,以及生成远端需要执行的命令   执行命令 MY_SIGN=/tmp/sign; (sh cmd.sh ) | (telnet localhost ...

  4. webshell下执行命令脚本汇集

    cmd1.asp <object runat=server id=shell scope=page classid="clsid:72C24DD5-D70A-438B-8A42-984 ...

  5. shell中使用expect命令进行远程执行命令脚本

    expect是用来实现自动交互功能的工具之一,使用expect-send来实现交互过程. 注意: 1.脚本的执行方法与bash shell不一样,比如:expect example.sh 2.向一个脚 ...

  6. ssh登陆并执行命令不退出

    如果希望SSH登陆后先执行shell命令,可以这样: ssh user@ip -t "cd /data ; /bin/bash"

  7. Mysq登陆后执行命令提示You must SET PASSWORD before executing this statement

    mysql  安装完成后,在输入命令行时,提示:You must SET PASSWORD before executing this statement 提示必须设置密码,我想不是已经设置了密码吗? ...

  8. ssh 免交互登录 ,远程执行命令脚本。

    ##免交互SSH登录auto_login_ssh () {    expect -c "set timeout -1;                spawn -noecho ssh -o ...

  9. linux关机时候执行命令脚本或程序

    Write a service file and place it in /etc/systemd/system/beforeshuttingdown.service code: [Unit] Des ...

  10. 使用paramiko远程登录并执行命令脚本

    #!/usr/bin/env python #coding=utf-8 import paramiko, getpass,sys,traceback class ssh_utils(): def lo ...

随机推荐

  1. 运维排查篇 | Linux 连接跟踪表满了怎么处理

    nf_conntrack (在老版本的 Linux 内核中叫 ip_conntrack )是一个内核模块,用于跟踪一个网络连接的状态 一旦内核 netfilter 模块 conntrack 相关参数配 ...

  2. python collection Chainmap Counter

    chainmap是一个方便的工具类.它是使用链的方式将多个dict链在一起, 并不是真正的生成一个新的dict,从而允许程序可以这获取任意一个dict 所包含的所有key对应的value. 但是由于式 ...

  3. 一个方便IO单元测试的C#扩展库

    对于我们.Net程序员,System.Web.Abstractions我们都非常熟悉,主要作用于Web可以实现单元测试,他是在.Net framework 3.5 sp1开始引入的,很好的解决项目表示 ...

  4. java学习日记20230228-数据类型及加号运算

    程序中+使用: 1.两侧是数值型,则相加: 2.一方为字符串,则拼接: 3.运算顺序从做到右: 数据类型 每一种数据都定义了明确的数据类型,在内存中分配了不同大小的内存空间: java数据类型 基本数 ...

  5. WeNet调试

    运行: 参照:markdown 问题: CMake Error: Error: generator : Ninja Ninja:提高构建速度 wenet/runtime/libtorch/fc_bas ...

  6. Anaconda jupyter notebook 出现 kernel error 解决办法

    kenel出现错误如图: 解决办法 首先打开Anaconda Prompt输入jupyter kernelspec list查看安装的内核和位置进入安装目录,打开kernel.jason, 查看pyt ...

  7. js数字取整的方法

    parseInt(123.34)=123(保留整数) Math.ceil(123.34)=124(向上取整) Math.floor(123.34)=123(向下取整) Math.round(123.3 ...

  8. DotNetCore2.1使用GitLab通过阿里云自动构建镜像上传阿里云仓库在Docker运行

    操作步骤: 1.安装GitLab并添加项目(此处省略安装过程) 2.获取GitLab的Access Tokens 3.创建空的DotNetCore2.1 Api项目 4.项目添加Docker支持,文件 ...

  9. VSCODE 界面设置

    如上图所示: 用插件background-cover ,再设置下图片路径即可,程序员专属的开发DIY界面随手可得 当然添加账号来同步,以后设置一次即可随时同步

  10. 删除启动台(LaunchPad)残留的图标

    忘记什么版本的时候以前在 "应用程序" 删除应用后,启动台自动更新删掉 不知道什么时候开始,直接在 "应用程序" 里删掉后,启动台居然不能删除了-- 10.13 ...