python3+telnetlib实现telnet客户端

Telnet对象

1. Telnet.read_until(expected, timeout=None)

# 读取连接服务器后显示的内容,直到遇到同expected相同的字节串,或者等待时间大于timeout时直接向下运行

2. Telnet.read_very_eager()

# 读取从上次IO阻断到现在所有的内容,返回的是字节串,需要进行decode()编码.如果连接关闭或者没有可用数据时会抛出EOFError,如果没有其他可用的数据,返回的是b"",除非在IAC中间,否则不会阻碍

3. Telnet.open(host, port=23[, timeout])

# 连接到主机,端口号为第二个可选参数,默认为标准的Telnet端口(23),可选的timeout参数指定连接的超时时间,如果未指定,将使用全局默认超时设置
# 不要尝试去重新打开一个已经连接的实例对象

4. Telnet.close()

# 关闭连接

5. Telnet.write(buffer)

# 将一个字节串(byte string)写进socket, 如果连接被阻塞,这也会被阻塞,如果连接关闭,会抛出OSError

6. Telnet.interact()

# telnet的交互功能,我下面用了一个死循环保证用户能够一直输入命令进行某些操作,也可以使用Telnet.interact()这个方法来使所连接终端持久化,不过官网说 (emulates a very dumb Telnet client)直译是一个非常愚蠢的客户端,不过我也不太明白为什么这么说,哈哈,有明白的欢迎指教

示例代码

class TelnetClient():
	"""此代码在Ubuntu18.04以及centos上测试通过,使用windows可能会出现登录返回值不同的问题,有问题的小伙伴自行修改"""
    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)
        except:
            print('%s网络连接失败'%host_ip)
            return False
        # 等待login出现后输入用户名,最多等待10秒
        self.tn.read_until(b'login: ',timeout=10)
        self.tn.write(username.encode('ascii') + b'
')
        # 等待Password出现后输入用户名,最多等待10秒
        self.tn.read_until(b'Password: ',timeout=10)
        self.tn.write(password.encode('ascii') + b'
')
        # 延时两秒再收取返回结果,给服务端足够响应时间
        time.sleep(2)
        # 获取登录结果
        # read_very_eager()获取到的是的是上次获取之后本次获取之前的所有输出
        command_result = self.tn.read_very_eager().decode('utf-8')
        if 'Login incorrect' not in command_result:
            print('%s登录成功'%host_ip)
            return True
        else:
            print('%s登录失败,用户名或密码错误'%host_ip)
            return False

    # 此函数实现执行传过来的命令,并输出其执行结果
    def execute_some_command(self):
        # 执行命令
        while True:
            command = input("请输入要执行的命令: ")
            if command == "exit":
                break
            self.tn.write(command.encode()+b'
')
            time.sleep(1)
            # 获取命令结果
            command_result = self.tn.read_very_eager().decode('utf-8')
            print('命令执行结果:%s' % command_result)

    # 退出telnet
    def logout_host(self):
        self.tn.write(b"exit
")


if __name__ == '__main__':
    host_ip = '要连接的ip'
    username = '用户名'
    password = '密码'
    telnet_client = TelnetClient()
    # 如果登录结果返加True,则执行命令,然后退出
    if telnet_client.login_host(host_ip,username,password):
        telnet_client.execute_some_command()
        telnet_client.logout_host()

  更多内容请查阅官网: https://docs.python.org/3/library/telnetlib.html

本文来源:

https://blog.csdn.net/study_in/article/details/89338016

原文地址:https://www.cnblogs.com/moonbaby/p/13690982.html