Skip to content

Instantly share code, notes, and snippets.

@vanyasem
Last active March 4, 2025 09:02
Show Gist options
  • Save vanyasem/4c931f186c48da7b98b0f5518f1c6c64 to your computer and use it in GitHub Desktop.
Save vanyasem/4c931f186c48da7b98b0f5518f1c6c64 to your computer and use it in GitHub Desktop.
Minimal example to test which shell is used by `ssh_channel_request_exec`
#include <libssh/libssh.h>
#include <iostream>
#include <cstring>
int main() {
// Create SSH session
ssh_session session = ssh_new();
if (!session) {
std::cerr << "Failed to create SSH session" << std::endl;
return 1;
}
// Set connection options
ssh_options_set(session, SSH_OPTIONS_HOST, "your_hostname");
ssh_options_set(session, SSH_OPTIONS_USER, "your_username");
// Connect to server
if (ssh_connect(session) != SSH_OK) {
std::cerr << "Connection failed: " << ssh_get_error(session) << std::endl;
ssh_free(session);
return 1;
}
// Authenticate using private key
int auth = ssh_userauth_autopubkey(session, nullptr);
if (auth != SSH_AUTH_SUCCESS) {
std::cerr << "Authentication failed: " << ssh_get_error(session) << std::endl;
ssh_disconnect(session);
ssh_free(session);
return 1;
}
// Create channel
ssh_channel channel = ssh_channel_new(session);
if (!channel) {
std::cerr << "Channel creation failed: " << ssh_get_error(session) << std::endl;
ssh_disconnect(session);
ssh_free(session);
return 1;
}
// Open channel session
if (ssh_channel_open_session(channel) != SSH_OK) {
std::cerr << "Channel open failed: " << ssh_get_error(session) << std::endl;
ssh_channel_free(channel);
ssh_disconnect(session);
ssh_free(session);
return 1;
}
// Execute remote command
if (ssh_channel_request_exec(channel, "echo $0") != SSH_OK) {
std::cerr << "Command execution failed: " << ssh_get_error(session) << std::endl;
ssh_channel_close(channel);
ssh_channel_free(channel);
ssh_disconnect(session);
ssh_free(session);
return 1;
}
// Read and print output
char buffer[256];
int nbytes;
while ((nbytes = ssh_channel_read(channel, buffer, sizeof(buffer), 0)) > 0) {
std::cout.write(buffer, nbytes);
}
// Cleanup
ssh_channel_send_eof(channel);
ssh_channel_close(channel);
ssh_channel_free(channel);
ssh_disconnect(session);
ssh_free(session);
return 0;
}
@vanyasem
Copy link
Author

vanyasem commented Mar 4, 2025

Replace the placeholders:

  • your_hostname with your SSH server hostname/IP
  • your_username with your SSH username

Compile with:

g++ -o ssh_example ssh_example.cpp -lssh

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment