Sample code for 30+ languages & platforms
Lua

Get Text Received on the SSH stderr Buffer

See more SSH Examples

Demonstrates the Chilkat Ssh.GetReceivedStderrText method, which decodes and returns the text accumulated in a channel's separate stderr buffer. The first argument is the channel number and the second is the charset. The stderr buffer is cleared after the text is returned.

Background: This is only meaningful when StderrToStdout is false, which keeps error output in its own buffer instead of merging it into the normal receive buffer. Separating the two lets a program parse a command's real output cleanly while still capturing diagnostics — important because many Unix tools write warnings to stderr that would otherwise corrupt the parsed result. With merging enabled, this buffer stays empty and the text appears via GetReceivedText instead.

Chilkat Lua Downloads

Lua
local chilkat = require("chilkat")

-- Demonstrates the Ssh.GetReceivedStderrText method, which decodes and returns the text in a
-- channel's separate stderr buffer.  The 1st argument is the channel number and the 2nd is the
-- charset.  The stderr buffer is cleared after the text is returned.

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

-- Keep stderr in its own buffer rather than merging it into the normal receive buffer.
ssh.stderr_to_stdout = false

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

-- Run a command that writes to both stdout and stderr.
success = ssh:send_req_exec(channelNum, "ls /etc/hosts /no/such/path")
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

local stdoutText = ssh:get_received_text(channelNum, "utf-8")
if not ssh.last_method_success then
    print(ssh.last_error_text)
    return
end

print("STDOUT: " .. stdoutText)

local stderrText = ssh:get_received_stderr_text(channelNum, "utf-8")
if not ssh.last_method_success then
    print(ssh.last_error_text)
    return
end

print("STDERR: " .. stderrText)

ssh:disconnect()