无法将我的ssh客户端连接到远程计算机

时间:2015-02-11 11:16:35

标签: ssh remote-access

我从libSSH下载并编译了libssh 0.6.1,并将ssh.lib,ssh.dll链接到visual c ++项目。 下面的代码编译并运行正常,但是当调用ssh_connect()时,它返回-1:连接失败:没有错误。 此外,我使用putty连接到我的远程机器,它工作正常。 这是我的代码:

// sshClient.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <stdlib.h>
#include <libssh/libssh.h> 


  int _tmain(int argc, _TCHAR* argv[])
    {
         ssh_session my_ssh_session;  

         int verbosity = SSH_LOG_PROTOCOL;  
         int port = 22; 
         char* host="127.0.0.1";
         ssh_channel channel;
         int rc; 

         //I create a session 
         my_ssh_session = ssh_new();  
         if (my_ssh_session == NULL)   
             exit(-1);  
         ssh_options_set(my_ssh_session, SSH_OPTIONS_HOST, host);  
         ssh_options_set(my_ssh_session, SSH_OPTIONS_LOG_VERBOSITY, &verbosity);  
         ssh_options_set(my_ssh_session, SSH_OPTIONS_PORT, &port); 
         ssh_options_set(my_ssh_session, SSH_OPTIONS_USER,"true");  
           rc = ssh_connect(my_ssh_session);  
           if (rc != SSH_OK)  {    
               fprintf(stderr, "Error connecting to 192.168.78.131 : %s\n",            ssh_get_error(my_ssh_session));  
               exit(-1); 
           } 
               ssh_disconnect(my_ssh_session); 
               ssh_free(my_ssh_session);

         //Here I create a channel 
         channel = ssh_channel_new(my_ssh_session);  

         if (channel == NULL) 
             return SSH_ERROR;
         if (SSH_OK != ssh_channel_open_session(channel)) {
             printf("ssh_channel_open_session");
             ssh_channel_free(channel);  
             return rc;
         }


         //My remote command  ls -l under true Folder 
         rc = ssh_channel_request_exec(channel, "ls -l");
         if (rc != SSH_OK){  ssh_channel_close(channel);
         ssh_channel_free(channel); 
         return rc;
         }
         char buffer[256];
         unsigned int nbytes;
         nbytes = ssh_channel_read(channel, buffer, sizeof(buffer), 0);
         while (nbytes > 0){  
             if (fwrite(buffer, 1, nbytes, stdout) != nbytes)  
             {    ssh_channel_close(channel);   
             ssh_channel_free(channel);    
             return SSH_ERROR; 
             } 
             nbytes = ssh_channel_read(channel, buffer, sizeof(buffer), 0);
         }
         if (nbytes < 0){ 
             ssh_channel_close(channel); 
             ssh_channel_free(channel);  
             return SSH_ERROR;
         }

         ssh_channel_send_eof(channel); 
         ssh_channel_close(channel); 
         ssh_channel_free(channel);

         ssh_free(my_ssh_session);
         system("pause");
        return 0;
    }

1 个答案:

答案 0 :(得分:0)

检查您的主机IP地址。我猜你忘了更改示例源文件中的IP地址。