Sample code for 30+ languages & platforms
Lua

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 Lua Downloads

Lua
local chilkat = require("chilkat")

-- 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.

local ssh = chilkat.Ssh.new()

local sshPort = 22
local success = ssh:connect("ssh.example.com", sshPort)
if not success then
    print(ssh.last_error_text)
    return
end

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

success = ssh:authenticate_pw("mySshLogin", password)
if not success then
    print(ssh.last_error_text)
    return
end

local channelNum = ssh:open_session_channel()
if channelNum < 0 then
    print(ssh.last_error_text)
    return
end

success = ssh:send_req_exec(channelNum, "grep -q root /etc/passwd")
if not success then
    print(ssh.last_error_text)
    return
end

-- 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.read_timeout_ms = 15000

success = ssh:channel_receive_to_close(channelNum)
if not success then
    print(ssh.last_error_text)
    return
end

-- Retrieve the exit status immediately, before calling unrelated SSH methods or releasing the
-- channel, because the completed channel record can be discarded.
if ssh:channel_received_exit_status(channelNum) then
    local exitStatus = ssh:get_channel_exit_status(channelNum)
    print("Exit status: " .. exitStatus)

    -- By convention, 0 means the remote command succeeded.
    if exitStatus == 0 then
        print("The remote command succeeded.")
    else
        print("The remote command reported a failure.")
    end
end

ssh:disconnect()