Tcl
Tcl
Collect Completed SSH Commands with QuickCmdCheck
See more SSH Examples
Demonstrates the Chilkat Ssh.QuickCmdCheck method, which waits for any command started by QuickCmdSend to complete. The only argument is the poll timeout in milliseconds; 0 performs a nonblocking check. It returns the channel number of a completed command, -1 when commands are still pending but none finished before the timeout, or -2 when no quick commands remain or an error occurred.
Background: This is the collection half of the concurrent pattern. Each completed channel is reported only once, so looping until
-2 drains every outstanding command exactly once. Distinguish the two negative values carefully: -1 simply means "still working, ask again," while -2 means there is nothing left to wait for — or that the connection failed, so check LastErrorText when the distinction matters. Manually opened exec channels are not reported here.Chilkat Tcl Downloads
load ./chilkat.dll
set success 0
# Demonstrates the Ssh.QuickCmdCheck method, which waits for any command started by
# QuickCmdSend to complete. The only argument is the poll timeout in milliseconds; 0 performs
# a nonblocking check.
set ssh [new_CkSsh]
set sshPort 22
set success [CkSsh_Connect $ssh "ssh.example.com" $sshPort]
if {$success == 0} then {
puts [CkSsh_lastErrorText $ssh]
delete_CkSsh $ssh
exit
}
# Normally you would not hard-code the password in source. You should instead obtain it
# from an interactive prompt, environment variable, or a secrets vault.
set password "mySshPassword"
set success [CkSsh_AuthenticatePw $ssh "mySshLogin" $password]
if {$success == 0} then {
puts [CkSsh_lastErrorText $ssh]
delete_CkSsh $ssh
exit
}
# Start two commands that will finish at different times.
set channel1 [CkSsh_QuickCmdSend $ssh "sleep 2; echo first done"]
if {$channel1 < 0} then {
puts [CkSsh_lastErrorText $ssh]
delete_CkSsh $ssh
exit
}
set channel2 [CkSsh_QuickCmdSend $ssh "echo second done"]
if {$channel2 < 0} then {
puts [CkSsh_lastErrorText $ssh]
delete_CkSsh $ssh
exit
}
# Collect the results as they complete. The return value is the channel number of a completed
# command, -1 if commands are still pending but none finished before the timeout, or -2 when
# no quick commands remain (or an error occurred).
set pollTimeoutMs 5000
set completedChannel [CkSsh_QuickCmdCheck $ssh $pollTimeoutMs]
while {$completedChannel != -2} {
if {$completedChannel >= 0} then {
set output [CkSsh_getReceivedText $ssh $completedChannel "utf-8"]
if {[CkSsh_get_LastMethodSuccess $ssh] == 0} then {
puts [CkSsh_lastErrorText $ssh]
delete_CkSsh $ssh
exit
}
puts "Channel $completedChannel finished: $output"
}
if {$completedChannel == -1} then {
puts "Still waiting for a command to finish..."
}
set completedChannel [CkSsh_QuickCmdCheck $ssh $pollTimeoutMs]
}
puts "All quick commands have been collected."
CkSsh_Disconnect $ssh
delete_CkSsh $ssh