标签:
通过使用管道方式分装plink.exe实现ssh命令交互
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,且3s内容无变化,退出循环
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 ;#去除linux显示的颜色乱码
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
}
标签:
原文地址:http://www.cnblogs.com/hua198/p/5693665.html