Sample code for 30+ languages & platforms
Lua

Get Received SSH Text into a StringBuilder

See more SSH Examples

Demonstrates the Chilkat Ssh.GetReceivedSb method, which decodes a channel's receive buffer and appends the text to a StringBuilder. The arguments are the channel number, the charset, and the StringBuilder. The receive buffer is cleared afterward.

Background: Because this appends rather than replaces, it is the natural choice for accumulating output across repeated reads — call it in a loop and the StringBuilder grows into the complete transcript. It also avoids creating a new string on every retrieval, which matters when a command produces a large amount of text.

Chilkat Lua Downloads

Lua
local chilkat = require("chilkat")

-- Demonstrates the Ssh.GetReceivedSb method, which decodes the channel's receive buffer and
-- appends the text to a StringBuilder.  The 1st argument is the channel number, the 2nd is the
-- charset, and the 3rd is the StringBuilder.  The receive buffer is cleared afterward.

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, "ls -l /tmp")
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

-- Append the received text to a StringBuilder.  Existing content is preserved.
local sb = chilkat.StringBuilder.new()
success = ssh:get_received_sb(channelNum, "utf-8", sb)
if not success then
    print(ssh.last_error_text)
    return
end

print("Characters received: " .. sb.length)
local output = sb:get_as_string()
print(output)

ssh:disconnect()