Java
Chilkat2 Java
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 Java Downloads
import com.chilkatsoft.chilkat2.ChilkatException;
import com.chilkatsoft.chilkat2.Ssh;
public class ChilkatExample {
public static void main(String[] args) {
// 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 ssh = new Ssh();
int sshPort = 22;
try {
ssh.connect("ssh.example.com", sshPort);
} catch (ChilkatException e) {
System.out.println(e.getLastErrorText());
return;
}
// 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.
String password = "mySshPassword";
try {
ssh.authenticatePw("mySshLogin", password);
} catch (ChilkatException e) {
System.out.println(e.getLastErrorText());
return;
}
// Open a session channel. A negative return value indicates failure.
int channelNum = ssh.openSessionChannel();
if (channelNum < 0) {
System.out.println(ssh.getLastErrorText());
return;
}
if (ssh.channelIsOpen(channelNum)) {
System.out.println("The channel is open.");
} else {
System.out.println("The channel is not open.");
}
// Send CLOSE, which immediately marks the channel locally closed.
try {
ssh.channelSendClose(channelNum);
} catch (ChilkatException e) {
System.out.println(e.getLastErrorText());
return;
}
if (ssh.channelIsOpen(channelNum)) {
System.out.println("Still open.");
} else {
System.out.println("The channel is now closed.");
}
ssh.disconnect();
}
}