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)
  • 6
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值