Sample code for 30+ languages & platforms
Lianja

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

Lianja
llSuccess = .F.

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

loSsh = createobject("CkSsh")

lnSshPort = 22
llSuccess = loSsh.Connect("ssh.example.com",lnSshPort)
if (llSuccess = .F.) then
    ? loSsh.LastErrorText
    release loSsh
    return
endif

//  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.
lcPassword = "mySshPassword"

llSuccess = loSsh.AuthenticatePw("mySshLogin",lcPassword)
if (llSuccess = .F.) then
    ? loSsh.LastErrorText
    release loSsh
    return
endif

//  Keep stderr in its own buffer rather than merging it into the normal receive buffer.
loSsh.StderrToStdout = .F.

lnChannelNum = loSsh.OpenSessionChannel()
if (lnChannelNum < 0) then
    ? loSsh.LastErrorText
    release loSsh
    return
endif

//  Run a command that writes to both stdout and stderr.
llSuccess = loSsh.SendReqExec(lnChannelNum,"ls /etc/hosts /no/such/path")
if (llSuccess = .F.) then
    ? loSsh.LastErrorText
    release loSsh
    return
endif

//  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.
loSsh.ReadTimeoutMs = 15000

llSuccess = loSsh.ChannelReceiveToClose(lnChannelNum)
if (llSuccess = .F.) then
    ? loSsh.LastErrorText
    release loSsh
    return
endif

lcStdoutText = loSsh.GetReceivedText(lnChannelNum,"utf-8")
if (loSsh.LastMethodSuccess = .F.) then
    ? loSsh.LastErrorText
    release loSsh
    return
endif

? "STDOUT: " + lcStdoutText

lcStderrText = loSsh.GetReceivedStderrText(lnChannelNum,"utf-8")
if (loSsh.LastMethodSuccess = .F.) then
    ? loSsh.LastErrorText
    release loSsh
    return
endif

? "STDERR: " + lcStderrText

loSsh.Disconnect()


release loSsh