Python3 telnetlib library usage method

telnetlibModule provides a Telnetrealization of Telnetsuch agreements, those who achieved Telnetthe agreement provided can be used telnetlibto log on.

By telnetlibbasic functions packaged as class.

#!/usr/bin/env python3
# -*- coding: UTF-8 -*-

import time
import telnetlib


class TelnetLib(object):

    def __init__(self):
        self.tn = None
        self.EXIT = b'quit\n'
        self.LOGIN = b'Login'
        self.USERNAME = b'Username:'
        self.PASSWORD = b'Password:'

    @staticmethod
    def format(data):
        return data.encode('UTF-8') + b'\n'

    def link(self, host, port=23, timeout=3):
        # 连接设备
        self.tn = telnetlib.Telnet(host, port, timeout)

    def login(self, username, password):
        # 监听登录事件
        self.tn.read_until(self.LOGIN)
        # 监听输入账户事件
        self.tn.read_until(self.USERNAME)
        # 输入账户
        self.tn.write(self.format(username))
        # 监听输入密码事件
        self.tn.read_until(self.PASSWORD)
        # 输入密码
        self.tn.write(self.format(password))

    def shell(self, command):
        # 执行命令
        self.tn.write(self.format(command))
        # 延时0.5s
        time.sleep(1)
        # 在I/O不阻塞的情况下读取所有数据,否则返回空
        data = self.tn.read_very_eager()
        # 解码后返回数据
        return data.decode('UTF-8')

    def __del__(self):
        # 退出设备
        self.tn.write(self.EXIT)
        # 关闭连接
        self.tn.close()


if __name__ == '__main__':
    tl = TelnetLib()
    tl.link(host='127.0.0.1', port=23, timeout=3)
    tl.login(username='admin', password='***')
    return_value = tl.shell(command='display ip routing-table')
    print(return_value)

The Telnet instance has the following methods:

Return until the given string is read, or return after timeout. If no match is found, any available items are returned, which may be an empty string.

Telnet.read_until(expected[, timeout])

Read all data until EOF.

Telnet.read_all()

Read at least one byte of cooked data.

Telnet.read_some()

Read all cooked data.

Telnet.read_very_eager()

Read the available data at any time.

Telnet.read_eager()

Process and return the data already in the queue.

Telnet.read_lazy()

Return any data in the skilled queue.

Telnet.read_very_lazy()

Returns the data collected between the SB/SE pair.

Telnet.read_sb_data()

Guess you like

Origin blog.csdn.net/yilovexing/article/details/109856289