Sample code for 30+ languages & platforms
PureBasic

Check Whether an SSH Channel is Open

See more SSH Examples

Demonstrates the Chilkat Ssh.ChannelIsOpen method, which reports whether a channel number identifies a channel Chilkat currently considers open for application I/O. The only argument is the channel number. This example checks the channel before and after sending CLOSE.

Background: Because one SSH connection can carry many channels with independent lifetimes, code that manages several needs a way to ask whether a given one is still usable. This returns false for invalid or nonexistent channel numbers, after a local Disconnect, once remote closure is processed, and immediately after ChannelSendClose — which marks the channel locally closed without waiting for the remote side.

Chilkat PureBasic Downloads

PureBasic
IncludeFile "CkSsh.pb"

Procedure ChilkatExample()

    success.i = 0

    ;  Demonstrates the Ssh.ChannelIsOpen method, which reports whether a channel number identifies
    ;  a channel Chilkat currently considers open for application I/O.  The only argument is the
    ;  channel number.

    ssh.i = CkSsh::ckCreate()
    If ssh.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    sshPort.i = 22
    success = CkSsh::ckConnect(ssh,"ssh.example.com",sshPort)
    If success = 0
        Debug CkSsh::ckLastErrorText(ssh)
        CkSsh::ckDispose(ssh)
        ProcedureReturn
    EndIf

    ;  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.
    password.s = "mySshPassword"

    success = CkSsh::ckAuthenticatePw(ssh,"mySshLogin",password)
    If success = 0
        Debug CkSsh::ckLastErrorText(ssh)
        CkSsh::ckDispose(ssh)
        ProcedureReturn
    EndIf

    ;  Open a session channel.  A negative return value indicates failure.
    channelNum.i = CkSsh::ckOpenSessionChannel(ssh)
    If channelNum < 0
        Debug CkSsh::ckLastErrorText(ssh)
        CkSsh::ckDispose(ssh)
        ProcedureReturn
    EndIf

    If CkSsh::ckChannelIsOpen(ssh,channelNum)
        Debug "The channel is open."
    Else
        Debug "The channel is not open."
    EndIf

    ;  Send CLOSE, which immediately marks the channel locally closed.
    success = CkSsh::ckChannelSendClose(ssh,channelNum)
    If success = 0
        Debug CkSsh::ckLastErrorText(ssh)
        CkSsh::ckDispose(ssh)
        ProcedureReturn
    EndIf

    If CkSsh::ckChannelIsOpen(ssh,channelNum)
        Debug "Still open."
    Else
        Debug "The channel is now closed."
    EndIf

    CkSsh::ckDisconnect(ssh)


    CkSsh::ckDispose(ssh)


    ProcedureReturn
EndProcedure