PureBasic
PureBasic
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 PureBasic Downloads
IncludeFile "CkStringBuilder.pb"
IncludeFile "CkSsh.pb"
Procedure ChilkatExample()
success.i = 0
; 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.
ssh.i = CkSsh::ckCreate()
If ssh.i = 0
Debug "Failed to create object."
ProcedureReturn
EndIf
sshPort.i = 22
success = CkSsh::ckConnect(ssh,"ssh.example.com",sshPort)
If success = 0
Debug CkSsh::ckLastErrorText(ssh)
CkSsh::ckDispose(ssh)
ProcedureReturn
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.
password.s = "mySshPassword"
success = CkSsh::ckAuthenticatePw(ssh,"mySshLogin",password)
If success = 0
Debug CkSsh::ckLastErrorText(ssh)
CkSsh::ckDispose(ssh)
ProcedureReturn
EndIf
channelNum.i = CkSsh::ckOpenSessionChannel(ssh)
If channelNum < 0
Debug CkSsh::ckLastErrorText(ssh)
CkSsh::ckDispose(ssh)
ProcedureReturn
EndIf
success = CkSsh::ckSendReqExec(ssh,channelNum,"ls -l /tmp")
If success = 0
Debug CkSsh::ckLastErrorText(ssh)
CkSsh::ckDispose(ssh)
ProcedureReturn
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.
CkSsh::setCkReadTimeoutMs(ssh, 15000)
success = CkSsh::ckChannelReceiveToClose(ssh,channelNum)
If success = 0
Debug CkSsh::ckLastErrorText(ssh)
CkSsh::ckDispose(ssh)
ProcedureReturn
EndIf
; Append the received text to a StringBuilder. Existing content is preserved.
sb.i = CkStringBuilder::ckCreate()
If sb.i = 0
Debug "Failed to create object."
ProcedureReturn
EndIf
success = CkSsh::ckGetReceivedSb(ssh,channelNum,"utf-8",sb)
If success = 0
Debug CkSsh::ckLastErrorText(ssh)
CkSsh::ckDispose(ssh)
CkStringBuilder::ckDispose(sb)
ProcedureReturn
EndIf
Debug "Characters received: " + Str(CkStringBuilder::ckLength(sb))
output.s = CkStringBuilder::ckGetAsString(sb)
Debug output
CkSsh::ckDisconnect(ssh)
CkSsh::ckDispose(ssh)
CkStringBuilder::ckDispose(sb)
ProcedureReturn
EndProcedure