SSH远程执行命令

时间:2016-11-10 06:24:00

标签: c networking ssh packets libssh

我正在尝试ssh到远程服务器并执行一个简单的命令。使用libssh库和以下代码,

ssh_key pKey;
ssh_session session;
ssh_channel channel;
int rc = ssh_pki_import_privkey_file(PC_PRIVATE_KEY_FILE, NULL, NULL, NULL, &pKey);
char buffer[1024];
unsigned int nbytes;

printf("Session...\n");
session = ssh_new();
if (session == NULL) exit(-1);

ssh_options_set(session, SSH_OPTIONS_HOST, PC_HOST);
ssh_options_set(session, SSH_OPTIONS_USER, PC_USER);
ssh_options_set(session, SSH_OPTIONS_PORT, &PC_PORT);
ssh_options_set(session, SSH_OPTIONS_LOG_VERBOSITY, &PC_VERBOSITY);

printf("Connecting...\n");
rc = ssh_connect(session);
if (rc != SSH_OK) error(session);

printf("Channel...\n");
channel = ssh_channel_new(session);
if (channel == NULL) exit(-1);

printf("Opening...\n");
rc = ssh_channel_open_session(channel);
if (rc != SSH_OK) error(session);

printf("Executing remote command...\n");
rc = ssh_channel_request_exec(channel, "ls -l");
if (rc != SSH_OK) error(session);

printf("Received:\n");
nbytes = ssh_channel_read(channel, buffer, sizeof(buffer), 0);
while (nbytes > 0) {
    fwrite(buffer, 1, nbytes, stdout);
    nbytes = ssh_channel_read(channel, buffer, sizeof(buffer), 0);
}

ssh connect成功运行,但当它到达创建通道的代码部分并执行命令时,我收到以下消息:

channel_open:  Creating a channel 43 with 64000 window and 32768 max packet
packet_send2:  packet: wrote [len=44,padding=19,comp=24,payload=24]
channel_open:  Sent a SSH_MSG_CHANNEL_OPEN type session for channel 43
ssh_socket_unbuffered_write:  Enabling POLLOUT for socket
ssh_packet_socket_callback:  packet: read type 3 [len=12,padding=6,comp=5,payload=5]
ssh_packet_process:  Dispatching handler for packet type 3
ssh_packet_unimplemented:  Received SSH_MSG_UNIMPLEMENTED (sequence number 3)

我做了一些研究,发现question on superuser与我遇到的问题相似,但却对问题的最高答案感到困惑。另外,question on stackoverflow,但没有解决我的问题。

我不确定如何解决我的问题。任何帮助将不胜感激。

0 个答案:

没有答案