Python 远程登陆 telnet

参考:https://blog.csdn.net/qq_41629756/article/details/102784236
https://www.cnblogs.com/mrlayfolk/p/15154813.html
https://blog.csdn.net/ever_peng/article/details/93073862
https://blog.csdn.net/qq_49442278/article/details/116301836

教程:https://www.w3schools.cn/python_network_programming/python_telnet.html

一、Python - telnetlib 模块提供一个实现Telnet协议的类 Telnet

telnetlib.Telnet 类的各种方法

Telnet.read_until - 一直读取,直到遇到预期的给定字符串或直到超时秒数过去。

Telnet.write - 将字符串写入套接字,将任何 IAC 字符加倍。 如果连接被阻塞,这可能会阻塞。 如果连接关闭,可能会引发 socket.error。

Telnet.read_all() - 读取所有数据直到 EOF; 阻塞直到连接关闭。

代码

import telnetlib
import time
 

HOST = "10.26.0.1"
user = 'root'
password = 'root'

tn = telnetlib.Telnet(HOST)
time.sleep(0.1)

tn.read_until(b"login: ")
time.sleep(0.1)

tn.write(user.encode('ascii') + b'\n')
if password:
    tn.read_until(b"Password: ")
    tn.write(password.encode('ascii') + b'\n')

tn.write('fpga_spi r 0x0'.encode('ascii') + b'\n')
time.sleep(0.1)
command_result = tn.read_very_eager().decode('ascii')  # 获取回显并解码(decode())
print(command_result)


tn.write(b"exit\n")  # 退出telnet连接
 
import telnetlib
import time

# 创建连接对象,链接IP地址
# 方式1
# tn = telnetlib.Telnet()
# tn.open('10.26.0.1', port=23)
# 方式2
tn = telnetlib.Telnet('10.26.0.1')

# 等待期望的字符出现
login_main  = tn.read_until(b'login: ', timeout=0.1)
tn.write('root'.encode('utf-8') + b'\n')  # 发送命令
Password_main = tn.read_until(b'Password: ', timeout=0.1)
tn.write('root'.encode('utf-8') + b'\n')


tn.write('fpga_spi r 0x0'.encode('ascii') + b'\n')
time.sleep(0.1)
command_result = tn.read_very_eager().decode('ascii')  # 获取回显并解码(decode())
print(command_result)

你可能感兴趣的:(telnet,python,开发语言)