Sample code for 30+ languages & platforms
Tcl

Enumerate Active SSH Channel Numbers

See more SSH Examples

Demonstrates the Chilkat Ssh.GetChannelNumber method, which returns the channel number at a zero-based enumeration index in the active channel collection. The only argument is the index — an enumeration position, not itself a channel number. Valid indexes run from 0 through NumOpenChannels - 1, and out-of-range indexes return -1.

Background: One SSH connection can carry many simultaneous channels, and this method lets you walk the live set rather than tracking every channel number yourself. The index-versus-channel-number distinction is the key point: index 0 is simply the first channel in the collection and may well be channel number 3. As channels open and close the enumeration shifts, so treat an index as valid only for the moment you read it.

Chilkat Tcl Downloads

Tcl

load ./chilkat.dll

set success 0

#  Demonstrates the Ssh.GetChannelNumber method, which returns the channel number at a
#  zero-based enumeration index in the active channel collection.  The only argument is the
#  index, which is an enumeration position and not itself a channel number.

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
}

#  Open a couple of channels so the collection has more than one entry.
set channelA [CkSsh_OpenSessionChannel $ssh]
if {$channelA < 0} then {
    puts [CkSsh_lastErrorText $ssh]
    delete_CkSsh $ssh
    exit
}

set channelB [CkSsh_OpenSessionChannel $ssh]
if {$channelB < 0} then {
    puts [CkSsh_lastErrorText $ssh]
    delete_CkSsh $ssh
    exit
}

#  Enumerate the active channels.  Valid indexes are 0 through NumOpenChannels - 1.
set n [CkSsh_get_NumOpenChannels $ssh]
puts "Open channels: $n"

for {set i 0} {$i <= [expr $n - 1]} {incr i} {
    set chNum [CkSsh_GetChannelNumber $ssh $i]
    puts "Index $i is channel number $chNum"
}

CkSsh_Disconnect $ssh

delete_CkSsh $ssh