帮我写一段c语言在Linux下基于libssh的远程执行命令的代码
时间: 2024-02-09 08:09:34 浏览: 32
好的,以下是基于libssh的远程执行命令的C语言代码,适用于Linux系统:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <libssh/libssh.h>
int ssh_execute(ssh_session session, const char *command) {
ssh_channel channel = ssh_channel_new(session);
if (channel == NULL) {
fprintf(stderr, "Error: Failed to create SSH channel.\n");
return SSH_ERROR;
}
if (ssh_channel_open_session(channel) != SSH_OK) {
fprintf(stderr, "Error: Failed to open SSH channel session: %s.\n", ssh_get_error(session));
ssh_channel_free(channel);
return SSH_ERROR;
}
if (ssh_channel_request_exec(channel, command) != SSH_OK) {
fprintf(stderr, "Error: Failed to execute command: %s.\n", ssh_get_error(session));
ssh_channel_close(channel);
ssh_channel_free(channel);
return SSH_ERROR;
}
char buffer[1024];
ssize_t bytes_received;
while ((bytes_received = ssh_channel_read(channel, buffer, sizeof(buffer), 0)) > 0) {
fwrite(buffer, 1, bytes_received, stdout);
}
if (bytes_received < 0) {
fprintf(stderr, "Error: Failed to receive command output: %s.\n", ssh_get_error(session));
ssh_channel_close(channel);
ssh_channel_free(channel);
return SSH_ERROR;
}
ssh_channel_send_eof(channel);
ssh_channel_close(channel);
ssh_channel_free(channel);
return SSH_OK;
}
int main(int argc, char **argv) {
if (argc != 5) {
fprintf(stderr, "Usage: %s <host> <port> <user> <password>\n", argv[0]);
return EXIT_FAILURE;
}
const char *host = argv[1];
const int port = atoi(argv[2]);
const char *user = argv[3];
const char *password = argv[4];
ssh_session session = ssh_new();
if (session == NULL) {
fprintf(stderr, "Error: Failed to create SSH session.\n");
return EXIT_FAILURE;
}
ssh_options_set(session, SSH_OPTIONS_HOST, host);
ssh_options_set(session, SSH_OPTIONS_PORT, &port);
ssh_options_set(session, SSH_OPTIONS_USER, user);
if (ssh_connect(session) != SSH_OK) {
fprintf(stderr, "Error: Failed to connect: %s.\n", ssh_get_error(session));
ssh_free(session);
return EXIT_FAILURE;
}
if (ssh_userauth_password(session, NULL, password) != SSH_AUTH_SUCCESS) {
fprintf(stderr, "Error: Failed to authenticate: %s.\n", ssh_get_error(session));
ssh_disconnect(session);
ssh_free(session);
return EXIT_FAILURE;
}
const char *command = "ls -l";
if (ssh_execute(session, command) != SSH_OK) {
ssh_disconnect(session);
ssh_free(session);
return EXIT_FAILURE;
}
ssh_disconnect(session);
ssh_free(session);
return EXIT_SUCCESS;
}
```
请注意将 `<host>`, `<port>`, `<user>` 和 `<password>` 替换为实际的值,以及将 `"ls -l"` 替换为实际的命令。