Python how to use telnet network equipment

0. Introduction

The Telnet protocol is TCP / IP protocol suite in one, for those of us who network siege lion, too familiar, often used for remote login to the network device to operate, but its flaws are too obvious, is unsafe , clear text transmission, very easy to be attacked to steal information, not recommended, but I start with it in this section to start Ha.

1. Test environment and explain the key code

1.1 Simple test environment

  1. Use python3 environment
  2. Use the built-in module telnetlib
  3. Simple experimental environment
    Here Insert Picture Description
    Here Insert Picture Description
说明:
cmd.txt文件里面命令如下:
  terminal length 0
  show clock
  show ip interface brief
list.txt文件里面的IP如下:
  192.168.1.101
  192.168.1.102
  192.168.1.103

1.2 Key Code

import xx: import module
class xx: define a class
def xx: Defined Function
try-except: handling exceptions may arise
tn.read_until (expected, timeout = None) : Expected Wait Wait Timeout string or
tn.write (buffer): Write the character string (meaning to a command sent to the device)
tn.expect (List, timeout = None): read significantly, list using regular expressions (meaning the execution shown)
tn.read_very_eager (): read significant (meaning the execution shown)
tn.open (host, Port = 0 [, timeout]): connecting a host
tn.close (): close the connection

Tips : information delivery terminal and the network device is a byte, it is put on the string encoding encode terminal to a byte object significant byte of information back to the network device to decode decoded.

2. The complete code

'''
欢迎关注微信公众号:'diandijishu'
  此平台是网路工程师个人日常技术、项目案例经验分享,
  为巩固及提升技术能力乃至共享所学所知技术
  也欢迎各位工程师一起分享、一起成长。
'''

#!/usr/bin/env python
#coding:utf-8

'导入模块'
from telnetlib import Telnet
import time
import logging

'定义类'
class TelnetClient():
    '初始化属性'
    def __init__(self):
        self.tn = Telnet()
    '定义login_host函数,用于登陆设备'
    def login_host(self,ip,username,password,enable=None,verbose=True):
        '连接设备,try-except结构'
        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)

        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

    '定义do_cmd函数,用于执行命令'
    def do_cmd(self,cmds):
        '读取文件,for语句循环执行命令'
        with open(cmds) as cmd_obj:
            for cmd in cmd_obj:
                self.tn.write(cmd.encode().strip()   b'\n')
                time.sleep(2)
                rely = self.tn.read_very_eager().decode()
                logging.warning('命令执行结果:\n %s' %rely)
    '定义logout_host函数,关闭程序'
    def logout_host(self):
        self.tn.close()

if __name__ == '__main__':
    username = 'cisco'  #用户名
    password = 'cisco' #密码
    enable = 'cisco'    #特权密码
    lists = 'list.txt'  #存放IP地址文件,相对路径
    cmds = 'cmd.txt'    #存放执行命令文件,相对路径
    telnet_client = TelnetClient()
    '读取文件,for语句循环登陆IP'
    with open(lists,'rt') as list_obj:
        for ip in list_obj:
            '如果登录结果为True,则执行命令,然后退出'
            if telnet_client.login_host(ip.strip(),username,password,enable):
                telnet_client.do_cmd(cmds)
                telnet_client.logout_host()
                time.sleep(2)

3. operating results

Here Insert Picture Description

Note: This effect I just run the store 192.168.1.101 the IP, streamlined look, for effect.

4. Effect given

4.1 Remote connections are not

Here Insert Picture Description

4.2 user name and password error

Here Insert Picture Description

The broken pieces of language

These are just some simple code to be optimized still a lot of places, give small partners to learn about, telnet protocol is insecure, basic network environment is rarely used, ssh is a common protocol, secure and easy to use, the next article I tell you how to use ssh python modules Kazakhstan.
I Code kung fu is not deep, such as defective hope the exhibitions, thank you.


If you like my articles, I welcome the attention of the public number: drip technique, scan code concerned, from time to time to share

Bit technology

Guess you like

Origin www.cnblogs.com/singvis/p/11568607.html