怎么样用tcl和putty通过ssh或者telnet访问设备

本文介绍了一种基于Tcl编程语言的库TclPutty,用于通过Putty实现SSH和Telnet连接,提供API接口进行命令执行、数据读取和匹配,简化测试开发中的设备访问过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题由来

做测试开发,经常需要通过ssh或者telnet访问设备,来获取信息或者执行命令。目前tcl没有专门的api实现这个功能,以前windows版本的expect能做到。但是近期发现expect不能用了,于是就有开发一个相关api的打算。

解决方案

写代码,越简单越好,这里采用最简单的方案,不容易出错。该方案基于tcl调用putty来实现。核心代码是下面的两行。

set file_id [open "|$program -telnet -x  -t -sanitise-stderr -sanitise-stdout $ip" r+]
fconfigure $file_id -blocking 0 -buffering none

就是通过管道打开一个进程,然后通过这个管道跟进程通讯,记住必须配置 -blocking 0 -buffering none,否则会有卡死现象。

目前我已经在github上创建了一个lib,可以拿来就用。github的地址是:
https://github.com/smshi/TclPutty
也可以在我的百度网盘下载:
链接:https://pan.baidu.com/s/133yljc4ZH4Nds_NIrW18DA?pwd=oiqh
提取码:oiqh

下面是我在github创建的使用说明。

TclPutty

TclPutty is tcl lib to connect server by ssh or telnet via putty. It has tested on windows system. I think it could work on Linux too after replace the putty binary with Linux version.

Exmaple

Telnet

package require TclPutty

set DutIp       10.0.11.123
set DutUsername admin
set DutPassword admin123
set log_file_id [open log.txt w]

#Create object named telnet_obj using telnet protocol, the log is recorded into log.txt
TclPutty telnet_obj $DutIp $DutUsername $DutPassword telnet $log_file_id

#Connect to the server
telnet_obj login

#Input command in the connection
telnet_obj exec_cmd &
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值