问题由来
做测试开发,经常需要通过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 &