C
C
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 C Downloads
#include <C_CkSsh.h>
#include <C_CkBinData.h>
void ChilkatSample(void)
{
BOOL success;
HCkSsh ssh;
int sshPort;
const char *password;
int channelNum;
HCkBinData bd;
success = FALSE;
// 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 = CkSsh_Create();
sshPort = 22;
success = CkSsh_Connect(ssh,"ssh.example.com",sshPort);
if (success == FALSE) {
printf("%s\n",CkSsh_lastErrorText(ssh));
CkSsh_Dispose(ssh);
return;
}
// 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 = "mySshPassword";
success = CkSsh_AuthenticatePw(ssh,"mySshLogin",password);
if (success == FALSE) {
printf("%s\n",CkSsh_lastErrorText(ssh));
CkSsh_Dispose(ssh);
return;
}
channelNum = CkSsh_OpenSessionChannel(ssh);
if (channelNum < 0) {
printf("%s\n",CkSsh_lastErrorText(ssh));
CkSsh_Dispose(ssh);
return;
}
// Run a command whose output may be binary.
success = CkSsh_SendReqExec(ssh,channelNum,"cat /usr/bin/hostname");
if (success == FALSE) {
printf("%s\n",CkSsh_lastErrorText(ssh));
CkSsh_Dispose(ssh);
return;
}
// 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_putReadTimeoutMs(ssh,15000);
success = CkSsh_ChannelReceiveToClose(ssh,channelNum);
if (success == FALSE) {
printf("%s\n",CkSsh_lastErrorText(ssh));
CkSsh_Dispose(ssh);
return;
}
// Append the raw received bytes to a BinData. Existing bytes in the BinData are preserved.
bd = CkBinData_Create();
success = CkSsh_GetReceivedBd(ssh,channelNum,bd);
if (success == FALSE) {
printf("%s\n",CkSsh_lastErrorText(ssh));
CkSsh_Dispose(ssh);
CkBinData_Dispose(bd);
return;
}
printf("Bytes received: %d\n",CkBinData_getNumBytes(bd));
CkSsh_Disconnect(ssh);
CkSsh_Dispose(ssh);
CkBinData_Dispose(bd);
}