Implementing SSH command interaction by using the pipeline to split the Plink.exe
Set ch [tclplink::connect ssh 127.0.0.1 user Pass]
puts [Tclplink::sendcommand $ch ls]
puts [Tclplink::sendcommand $ch pwd]
; #by Enter
Namespace Eval Tclplink {
}
Proc Tclplink::openpipe {PIPESTR} {
Global ExePath
if {[Info exists exepath]==0}} {
Set ExePath "."
}
Set Currentpath [pwd]
CD $exePath
Set channel [open] |plink.exe $pipestr "r+"
CD $currentPath
Fconfigure $channel-block 0-buffering none-buffersize 1-encoding utf-8
fileevent $channel readable [list Tclplink::getecho $channel]
return $channel
}
Proc Tclplink::getecho {Channel} {
Variable ${channel}readable
If[catch {
set S [Read $channel]
#puts-nonewline $s; #输出到console
Append ${channel}read $s; #保存到内存
} ErrMsg] {
Puts stderr "Getecho error: = $errmsg"
}
}
Proc Tclplink::sendcommand {Channel str args} {
Variable ${channel}read
Puts-nonewline $channel $str
Puts-nonewline $channel "\ r"
Set ${channel}read ""
Set Readflush ""
Set Timeout 0
Tclplink::waittime 100
if {[Llength $args]>0} {
Set M "$args |#|>"
} else {
Set M "#|>"
}
While {1} {
if {[regexp] $args |#|> "[set ${channel}read]] > 0} {
Break
} elseif {$timeout >10000} {
if {[Expr $timeout%3000]==0} {; #发送时间超过10s, and 3s content does not change, exiting the loop
if{$readflush ==[set ${channel}read]} {
Puts "execute command: $str timeout"
Break
}
Set Readflush [Set ${channel}read]
}
}
Tclplink::waittime 100
INCR Timeout 100
}
#regsub-nocase-all "~#" [Set ${channel}read] "--" ${channel}read; #将 ~ #输出变成
Regsub-nocase-all {\e\[\?\d{1,4}h|\e\[\d{1,2} (; \d{1,2}) {0,2}m|\e\ (b\e\[m} [set ${channel}read] "" ${channel}read; Remove garbled colors from Linux display
regsub {. *?\n} [Set ${channel}read] "" ${channel}read; #去掉回显第一行
if {[Llength $args]<1 && [Regexp-all {(. *?) (\ n)} [Set ${channel}read]] >0} {; #去掉回显最后一行
Set I 1
Set C ""
Set a [split [set ${channel}read "\ n"]
foreach x $a {
If {$i <[llength $a]} {
INCR I
Append c $x "\ n"
}
}
Set ${channel}read [string trimright $c "\ n"]
}
# puts [set ${channel}read]; #打印命令回显
return [set ${channel}read]; #返回命令回显
}
Proc Tclplink::connect {protocol Remoteip username password} {
Set URL "-$protocol-l $username-pw password $remoteip"
Set channel [Openpipe $url]
Variable ${channel}read
Set ${channel}read ""
Set Timeout 0
While {1} {
if {[regexp "#|>" [set ${channel}read]]>0} {
Break
} elseif {$timeout > 12000} {
Puts stderr "Connect $url: Timeout"
Break
}
Tclplink::waittime 100
INCR Timeout 100
}
Regsub-nocase-all {\e\[\?\d{1,4}h|\e\[\d{1,2} (; \d{1,2}) {0,2}m|\e\ (b\e\[m} [set ${channel}read] ""
puts [set ${channel}read]
return $channel
}
Proc Tclplink::tclclose {Channel} {
Fileevent $channel Readable {}
if [catch]{
EXEC taskkill/f/im Plink.exe
#close $channel
} ErrMsg] {
Puts stderr "Close Plink error: $errmsg"
}
Return $errmsg
}
The SSH interactive of TCL automation