Demo entry 6799631

py

   

Submitted by jxp on May 21, 2019 at 08:43
Language: Python. Code size: 2.0 kB.

#!/usr/bin/python
# -*- coding:utf-8 -*-
import logging
import telnetlib
import time
import sys
yes = 1
no = 0
class TelnetClient():
    def __init__(self,):
        self.tn = telnetlib.Telnet()

    # 此函数实现telnet登录主机
    def login_host(self,host_ip,username,password):
        try:
            # self.tn = telnetlib.Telnet(host_ip,port=23)
            self.tn.open(host_ip,port=23)
        except:
            # logging.warning('%s网络连接失败'%host_ip)
            return False
        # 等待login出现后输入用户名,最多等待10秒
        self.tn.read_until(b'Username: ',timeout=0.1)
        self.tn.write(username.encode('ascii') + b'\n')
        # 等待Password出现后输入用户名,最多等待10秒
        self.tn.read_until(b'Password: ',timeout=0.1)
        self.tn.write(password.encode('ascii') + b'\n')

        # 延时1秒再收取返回结果,给服务端足够响应时间

        time.sleep(0.1)
        # 获取登录结果
        # read_very_eager()获取到的是的是上次获取之后本次获取之前的所有输出
        command_result = self.tn.read_very_eager().decode('ascii')
        if 'Login incorrect' not in command_result:
            # logging.warning('%s登录成功'%host_ip)
            return True
        else:
            # logging.warning('%s登录失败,用户名或密码错误'%host_ip)
            return False

    # 此函数实现执行传过来的命令,并输出其执行结果
    def execute_some_command(self,command):
        # 执行命令
        self.tn.write(command.encode('ascii')+b'\n')
        time.sleep(1)
        # 获取命令结果
        command_result = self.tn.read_very_eager().decode('ascii')
        # print('命令执行结果:\n%s',command_result)
        # 诊断输出
        if command_result.find('Fault') != -1:
            print(no)
        else:
            print(yes)
    # 退出telnet
    def logout_host(self):
        self.tn.write(b"exit\n")

if __name__ == '__main__':    # 程序入口
    host_ip = sys.argv[1]
    username = 'test'
    password = '123456'
    command = 'display fan'
    telnet_client = TelnetClient()
    # 如果登录结果返加True,则执行命令,然后退出
    if telnet_client.login_host(host_ip,username,password):
        telnet_client.execute_some_command(command)
        telnet_client.logout_host()

This snippet took 0.01 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).