PureBasic
PureBasic
Get Received SSH Bytes into a BinData
See more SSH Examples
Demonstrates the Chilkat Ssh.GetReceivedBd method, which appends the bytes currently in a channel's normal receive buffer to a BinData. The first argument is the channel number and the second is the BinData. The channel receive buffer is cleared afterward; existing bytes in the BinData are preserved.
Background: When the remote command emits binary — a tarball, an image, a compressed stream — decoding it as text through a charset would corrupt it.
BinData keeps the bytes exactly as received, so you can write them to a file, hash them, or hand them to another API. Like the StringBuilder form it appends, making it easy to accumulate across successive reads. On failure the BinData is left unchanged.Chilkat PureBasic Downloads
IncludeFile "CkBinData.pb"
IncludeFile "CkSsh.pb"
Procedure ChilkatExample()
success.i = 0
; Demonstrates the Ssh.GetReceivedBd method, which appends the bytes currently in a channel's
; receive buffer to a BinData. The 1st argument is the channel number and the 2nd is the
; BinData. The channel 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
; Run a command whose output may be binary.
success = CkSsh::ckSendReqExec(ssh,channelNum,"cat /usr/bin/hostname")
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 raw received bytes to a BinData. Existing bytes in the BinData are preserved.
bd.i = CkBinData::ckCreate()
If bd.i = 0
Debug "Failed to create object."
ProcedureReturn
EndIf
success = CkSsh::ckGetReceivedBd(ssh,channelNum,bd)
If success = 0
Debug CkSsh::ckLastErrorText(ssh)
CkSsh::ckDispose(ssh)
CkBinData::ckDispose(bd)
ProcedureReturn
EndIf
Debug "Bytes received: " + Str(CkBinData::ckNumBytes(bd))
CkSsh::ckDisconnect(ssh)
CkSsh::ckDispose(ssh)
CkBinData::ckDispose(bd)
ProcedureReturn
EndProcedure