Swift
Swift
Get the Exit Status of a Remote SSH Command
See more SSH Examples
Demonstrates the Chilkat Ssh.GetChannelExitStatus method, which returns the remote process exit status for a channel. The only argument is the channel number. Call it only after ChannelReceivedExitStatus returns true.
Background: The exit status is how you learn whether a remote command actually succeeded — recall that a successful
exec request only means the request was accepted. By Unix convention 0 means success and any nonzero value indicates a failure. Retrieve it promptly after the receive operation and before calling unrelated SSH methods or releasing the channel, since the completed channel record can be discarded.Chilkat Swift Downloads
func chilkatTest() {
var success: Bool = false
// Demonstrates the Ssh.GetChannelExitStatus method, which returns the remote process exit
// status for a channel. The only argument is the channel number. Call it only after
// ChannelReceivedExitStatus returns true.
let ssh = CkoSsh()!
var sshPort: Int = 22
success = ssh.connect(hostname: "ssh.example.com", port: sshPort)
if success == false {
print("\(ssh.lastErrorText!)")
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.
var password: String? = "mySshPassword"
success = ssh.authenticatePw(login: "mySshLogin", password: password)
if success == false {
print("\(ssh.lastErrorText!)")
return
}
var channelNum: Int = ssh.openSessionChannel().intValue
if channelNum < 0 {
print("\(ssh.lastErrorText!)")
return
}
success = ssh.sendReqExec(channelNum: channelNum, command: "grep -q root /etc/passwd")
if success == false {
print("\(ssh.lastErrorText!)")
return
}
// IMPORTANT: Set a read timeout. ReadTimeoutMs defaults to 0, which means no limit -- without
// it, this call waits forever if the server never sends channel close.
ssh.readTimeoutMs = 15000
success = ssh.channelReceive(toClose: channelNum)
if success == false {
print("\(ssh.lastErrorText!)")
return
}
// Retrieve the exit status immediately, before calling unrelated SSH methods or releasing the
// channel, because the completed channel record can be discarded.
if ssh.channelReceivedExitStatus(channelNum: channelNum) {
var exitStatus: Int = ssh.getChannelExitStatus(channelNum: channelNum).intValue
print("Exit status: \(exitStatus)")
// By convention, 0 means the remote command succeeded.
if exitStatus == 0 {
print("The remote command succeeded.")
}
else {
print("The remote command reported a failure.")
}
}
ssh.disconnect()
}