精华内容
下载资源
问答
  • 求助linux下编译libssh2问题
    2021-05-14 12:53:45

    求助linux下编译libssh2问题

    linux编译libssh2时问题如下,/usr/bin/ld: /opt/openssl/lib/libcrypto.a(hmac.o): relocation R_X86_64_32 against `a local symbol' can not be used when making a shared object; recompile with -fPIC/opt/openssl/lib/libcrypto.a Bad valuecollect2: ld returned 1 exit status有哪位大侠知道怎么解决吗? openssl编译时已经使用了./config -fPIC参数,谢谢了。

    更新时间:2019-03-16 09:55

    最满意答案

    一直这样使用,无问题(注:$THIRD_PARTY_HOME不是环境变量,而是脚本中定义的变量,以下是脚本中自动化调用):./config --prefix=$THIRD_PARTY_HOME/openssl shared threadstar xzf $thrift.tar.gzcd $thrift./configure --prefix=$THIRD_PARTY_HOME/thrift \ --with-boost=$THIRD_PARTY_HOME/boost \ --with-libevent=$THIRD_PARTY_HOME/libevent \ CPPFLAGS="-I$THIRD_PARTY_HOME/openssl/include" \ LDFLAGS="-ldl -L$THIRD_PARTY_HOME/openssl/lib" \ --with-qt4=no --with-c_glib=no --with-csharp=no \ --with-java=no --with-erlang=no --with-python=no \ --with-perl=no --with-ruby=no --with-haskell=no \ --with-go=no --with-d=no

    fykkkaibe 2014-05-02 回答

    其他回答

    回复 maxer025 可是,你使用 -fPIC 用对了么?

    fykkkaibe 2014-05-02 回答

    网上找的, CFLAGS="-O3 -fPIC" 也用过,都一样的错误啊

    fykkkaibe 2014-05-02 回答

    回复 maxer025 openssl 的编译还是比较麻烦的,用包管理器安装吧,不要自己编译了。而且你这个问题,未必加了 -fPIC 就能解决。

    fykkkaibe 2014-05-02 回答

    编译openssl ./config -fPIC --prefix=/opt/openssl编译libssh2 CFLAGS="-O3 -fPIC" ./configure --prefix=/opt/libssh2 --with-libssl-prefix=/opt/openssl

    fykkkaibe 2014-05-02 回答

    谁告诉你 -fPIC 是这么用的?

    fykkkaibe 2014-05-02 回答

    相关问答

    一直这样使用,无问题(注:$THIRD_PARTY_HOME不是环境变量,而是脚本中定义的变量,以下是脚本中自动化调用):./config --prefix=$THIRD_PARTY_HOME/openssl shared threadstar xzf $thrift.tar.gzcd $thrift./configure --prefix=$THIRD_PARTY_HOME/thrift \ --with-boost=$THIRD_PARTY_HOME/boost \ --with-libeve

    ...

    弄清楚了。 您必须使用CMake创建构建环境。 将您的CMake bin目录添加到环境PATH变量。 使用root libssh2中的命令提示符: mkdir build

    cd build

    cmake -G "Visual Studio 14 2015 Win64" ..

    cmake --build .

    这将创建一个MDd静态调试库。 对于常规的MD静态发布库,运行: cmake --build . --config Release

    Figured it out. You have to cr

    ...

    我不认为你已经走了这么远,钥匙码就成了问题。 从您给出的消息中,我怀疑您调用了异步函数,但将其视为同步,错误输出而不是等待。 假设我们有以下代码段: n = recv(socket, buffer, sizeof buffer, 0);

    if (n == -1) {

    err(1, "Error receiving data from socket");

    }

    在大多数情况下,这对于同步套接字来说非常好,但

    ...

    对于第一个错误,我同意harmic,您可以手动添加.lib文件到您的项目来解决库链接失败:添加.lib文件:Properties> Linker-> Input-> Additional Dependencies,添加.lib文件路径:Properties> Linker-> General-> Additional Dependencies。 对于第二个错误,问题是您没有链接到Ws2_32.lib库。 要解决此问题,您可以将以下代码添加到项目的源文件中。 #pragma comment(lib,

    ...

    你应该使用libssh2_channel_read函数来读取远程标准输出: http://www.libssh2.org/libssh2_channel_read.html you should use the libssh2_channel_read function to read the remote stdout: http://www.libssh2.org/libssh2_channel_read.html

    我找到了一种增加块大小的方法。 块大小在libssh2库中是硬编码的,您必须从libssh2站点下载源代码,然后编辑sftp.h文件中给出的常量,即#SFTP_READ_SIZE 8000或您想要的大小,但要确保它不应该更多比你的缓冲区大小。 然后重建库。 I have found a way to increase the chunk size. The chunk size is hard coded in the libssh2 library you have to download th

    ...

    至少在我的情况下,这是由于尝试使用gcc编译新版本的libssh2,并链接到以前使用Solaris cc编译的openssl库。 通过添加一个CC环境变量强制configure来使用Solaris cc命令,就像这样,我可以让它编译: CC="/opt/solstudio12.2/bin/cc" ./configure --prefix=/export/home/ixbuild/local --disable-static

    看看我之前执行的安装中的笔记,之前我不需要这样做,所以配置脚本在某种程度

    ...

    在RTFM并进行一些测试之后,我发现libssh2_userauth_publickey_fromfile将返回不同的错误代码,具体取决于服务器是否接受密钥,或密码短语是否错误。 所以,这是一个非常低效的解决方案(因为它调用libssh2_userauth_publickey_fromfile ,因此协议的所有密钥交换部分至少两次)。 int nAttempts = 3; // number of attempts the user gets at entering the passphrase

    ...

    看起来pygit2还不支持libgit2的凭证网络操作。 有一些API讨论正在进行 ,但没有最终确定。 编辑:看起来这个已经实施,因为这个答案被接受了。 该文档对此有一些注释。 It looks like pygit2 doesn't support libgit2's credentialed network operations just yet. There's some API discussion happening, but nothing is finalized. EDIT: Lo

    ...

    我强烈建议使用本机Windows应用程序升级您的Perl版本。 如果您安装最新版本的Strawberry Perl (撰写本文时为5.24.1.1),则包含libssh2-1.7.0 。 然后,它允许您成功构建,安装和使用Net :: SSH2 。 这是代码的输出: c:\>perl ssh.pl

    1.7.067328SSH-2.0-libssh2_1.7.0

    好像它已经在构建中存在了一段时间,但如果你正在升级,我会去最新和最好的。 I would highly recommend upgrad

    ...

    更多相关内容
  • 这段代码去掉libssh2_channel_request_pty 代码不加libssh2_channel_read ,libssh2_channel_read 当无数据读时,正常返回0. 代码加上libssh2_channel_request_pty 时,libssh2_channel_read 当无数据读时永久...
  • 当执行的命令返回的结果数据量较大时,libssh2_channel_read()只能读取channel的一部分,不知道怎样才能读取全部的数据。 //下面是读取channel的代码 for( ;; ) { libssh2_channel_receive_window...
  • SSH_LIBSSH2源码 C

    2012-03-30 00:47:21
    SSH_LIBSSH2 源码C
  • linux libssh2 实例

    千次阅读 2020-02-19 14:10:46
    #include "libssh2_config.h" #include<libssh2.h> #include<libssh2_sftp.h> 以下为定义的静态子串常量 const char *keyfile1 = "~/.ssh/id_rsa.pub"; const char *keyfile2 = "~/.ssh/id_rsa"; ...
    以下是包含必备头文件
    
    #include "libssh2_config.h"
    #include<libssh2.h>
    #include<libssh2_sftp.h>

    以下为定义的静态子串常量

    const char *keyfile1 = "~/.ssh/id_rsa.pub";
    const char *keyfile2 = "~/.ssh/id_rsa";
    const char *username = "username";
    const char *password = "password";
    
    unsigned long hostaddr;
    int rc, sock, i, auth_pw = 0;
    struct sockaddr_in_sin;
    const char *fingerprint;
    char * userauthlist;
    LIBSSH2_SESSION *session;
    LIBSSH2_CHANNEL *channel;

    连接到SSH2步骤:

    (1)建立socket并连接到远程主机SSH2服务(22端口);

    (2)创建一个LIBSSH2_SESSION 实例并启动它。启动动作包括设置欢迎横幅、交换密钥并且设置加密、压缩和MAC层。

    session = libssh2_session_init();   //创建一个会话实例
    if(libssh2_session_handshake(session, sock))
    {
      fprintf(stderr, "Failure establishing SSH session");
      return -1;
    }

    (3)认证:检查主机密钥指纹并检查可用的认证方式。

    fingerprint = libssh2_hostkey_hash(session, LIBSSH2_HOSTKEY_HASH_SHA1);
    userauthlist = libssh2_userauth_list(session, username, strlen(username));
    if(strstr(userauthlist, "password") != NULL)
    {
      auth_pw |= 1;
    }
    if(strstr(userauthlist, "keyboad-interactive") != NULL)
    {
      auth_pw |= 2;
    }
    if(strstr(userauthlist, "publickey") != NULL)
    {
      auth_pw |= 4;
    }

    (4)如果在参数列表中设置了认证方式,则将认证方式设为命令中的方式(前提是该方式是通过上个步骤检测可用的)。

    if(argc > 4)
    {
      if((auth_pw & 1) && !strcasecmp(argv[4], "-p"))
      {
        auth_pw = 1;
      }
      if((auth_pw & 2) && !strcasecmp(argv[4], "-i"))
      {
        auth_pw = 2;
      }
      if((auth_pw && 4) && !strcasecmp(argv[4], "-k"))
      {
        auth_pw = 4;
      }
    }

    (5)根据上一步选定的认证方式开始认证。

    if (auth_pw & 1) {
            /* We could authenticate via password */ 
            if (libssh2_userauth_password(session, username, password)) {
    
                fprintf(stderr, "\tAuthentication by password failed!\n");
                goto shutdown;
            } else {
                fprintf(stderr, "\tAuthentication by password succeeded.\n");
            }
        } else if (auth_pw & 2) {
            /* Or via keyboard-interactive */ 
            if (libssh2_userauth_keyboard_interactive(session, username,
    
                                                      &kbd_callback) ) {
                fprintf(stderr,
                    "\tAuthentication by keyboard-interactive failed!\n");
                goto shutdown;
            } else {
                fprintf(stderr,
                    "\tAuthentication by keyboard-interactive succeeded.\n");
            }
        } else if (auth_pw & 4) {
            /* Or by public key */ 
            if (libssh2_userauth_publickey_fromfile(session, username, keyfile1,
    
                                                    keyfile2, password)) {
                fprintf(stderr, "\tAuthentication by public key failed!\n");
                goto shutdown;
            } else {
                fprintf(stderr, "\tAuthentication by public key succeeded.\n");
            }
        } else {
            fprintf(stderr, "No supported authentication methods found!\n");
            goto shutdown;
        }

    (6)请求一个shell

    if(!(channel = libssh2_channel_open_session(session)))

    (7)设置一些环境变量,并上传给服务器

    libssh2_channel_setenv(channel, "F00", "bar");

    (8)请求一个vanilla的终端模拟。

    libssh2_channel_request_pty(channel, "vanilla")

    (9)在上一步请求的pty上开启SHELL。

    libssh2_channel_shell(channel)

    (10)至此,可以交互使用shell了

    libssh2_channel_read();
    libssh2_channel_read_stderr();
    libssh2_channel_write();
    
    libssh2_channel_write_stderr();
    
    
    /* 打开或关闭阻塞模式 */
    
    libssh2_channel_set_blocking();
    
    /* 如果服务器发送EOF */
    
    libssh2_channel_eof()返回非0;
    
    /* 关闭channel */
    
    libssh2_channel_close();
    
    /* 释放一个channel */
    
    libssh2_channel_free();

    (11)ssh交互完成后,关闭会话并释放会话

    libssh2_session_disconnect(session, "Normal Shutdown");
    libssh2_session_free(session);

    (12)关闭sock并退出libssh2

    close(sock);
    libssh2_exit();

    官网实例以作参考:

    https://github.com/libssh2/libssh2/blob/master/example/ssh2.c

    /*
     * Sample showing how to do SSH2 connect.
     *
     * The sample code has default values for host name, user name, password
     * and path to copy, but you can specify them on the command line like:
     *
     * "ssh2 host user password [-p|-i|-k]"
     */
    
    #include "libssh2_config.h"
    #include <libssh2.h>
    #include <libssh2_sftp.h>
    
    #ifdef HAVE_WINDOWS_H
    # include <windows.h>
    #endif
    #ifdef HAVE_WINSOCK2_H
    # include <winsock2.h>
    #endif
    #ifdef HAVE_SYS_SOCKET_H
    # include <sys/socket.h>
    #endif
    #ifdef HAVE_NETINET_IN_H
    # include <netinet/in.h>
    #endif
    # ifdef HAVE_UNISTD_H
    #include <unistd.h>
    #endif
    # ifdef HAVE_ARPA_INET_H
    #include <arpa/inet.h>
    #endif
    
    #include <sys/types.h>
    #include <fcntl.h>
    #include <errno.h>
    #include <stdio.h>
    #include <ctype.h>
    
    
    const char *keyfile1 = "~/.ssh/id_rsa.pub";
    const char *keyfile2 = "~/.ssh/id_rsa";
    const char *username = "username";
    const char *password = "password";
    
    
    static void kbd_callback(const char *name, int name_len,
                             const char *instruction, int instruction_len,
                             int num_prompts,
                             const LIBSSH2_USERAUTH_KBDINT_PROMPT *prompts,
                             LIBSSH2_USERAUTH_KBDINT_RESPONSE *responses,
                             void **abstract)
    {
        (void)name;
        (void)name_len;
        (void)instruction;
        (void)instruction_len;
        if(num_prompts == 1) {
            responses[0].text = strdup(password);
            responses[0].length = strlen(password);
        }
        (void)prompts;
        (void)abstract;
    } /* kbd_callback */
    
    
    int main(int argc, char *argv[])
    {
        unsigned long hostaddr;
        int rc, sock, i, auth_pw = 0;
        struct sockaddr_in sin;
        const char *fingerprint;
        char *userauthlist;
        LIBSSH2_SESSION *session;
        LIBSSH2_CHANNEL *channel;
    
    #ifdef WIN32
        WSADATA wsadata;
        int err;
    
        err = WSAStartup(MAKEWORD(2, 0), &wsadata);
        if(err != 0) {
            fprintf(stderr, "WSAStartup failed with error: %d\n", err);
            return 1;
        }
    #endif
    
        if(argc > 1) {
            hostaddr = inet_addr(argv[1]);
        }
        else {
            hostaddr = htonl(0x7F000001);
        }
    
        if(argc > 2) {
            username = argv[2];
        }
        if(argc > 3) {
            password = argv[3];
        }
    
        rc = libssh2_init(0);
        if(rc != 0) {
            fprintf(stderr, "libssh2 initialization failed (%d)\n", rc);
            return 1;
        }
    
        /* Ultra basic "connect to port 22 on localhost".  Your code is
         * responsible for creating the socket establishing the connection
         */
        sock = socket(AF_INET, SOCK_STREAM, 0);
    
        sin.sin_family = AF_INET;
        sin.sin_port = htons(22);
        sin.sin_addr.s_addr = hostaddr;
        if(connect(sock, (struct sockaddr*)(&sin),
                    sizeof(struct sockaddr_in)) != 0) {
            fprintf(stderr, "failed to connect!\n");
            return -1;
        }
    
        /* Create a session instance and start it up. This will trade welcome
         * banners, exchange keys, and setup crypto, compression, and MAC layers
         */
        session = libssh2_session_init();
        if(libssh2_session_handshake(session, sock)) {
            fprintf(stderr, "Failure establishing SSH session\n");
            return -1;
        }
    
        /* At this point we havn't authenticated. The first thing to do is check
         * the hostkey's fingerprint against our known hosts Your app may have it
         * hard coded, may go to a file, may present it to the user, that's your
         * call
         */
        fingerprint = libssh2_hostkey_hash(session, LIBSSH2_HOSTKEY_HASH_SHA1);
        fprintf(stderr, "Fingerprint: ");
        for(i = 0; i < 20; i++) {
            fprintf(stderr, "%02X ", (unsigned char)fingerprint[i]);
        }
        fprintf(stderr, "\n");
    
        /* check what authentication methods are available */
        userauthlist = libssh2_userauth_list(session, username, strlen(username));
        fprintf(stderr, "Authentication methods: %s\n", userauthlist);
        if(strstr(userauthlist, "password") != NULL) {
            auth_pw |= 1;
        }
        if(strstr(userauthlist, "keyboard-interactive") != NULL) {
            auth_pw |= 2;
        }
        if(strstr(userauthlist, "publickey") != NULL) {
            auth_pw |= 4;
        }
    
        /* if we got an 4. argument we set this option if supported */
        if(argc > 4) {
            if((auth_pw & 1) && !strcasecmp(argv[4], "-p")) {
                auth_pw = 1;
            }
            if((auth_pw & 2) && !strcasecmp(argv[4], "-i")) {
                auth_pw = 2;
            }
            if((auth_pw & 4) && !strcasecmp(argv[4], "-k")) {
                auth_pw = 4;
            }
        }
    
        if(auth_pw & 1) {
            /* We could authenticate via password */
            if(libssh2_userauth_password(session, username, password)) {
                fprintf(stderr, "\tAuthentication by password failed!\n");
                goto shutdown;
            }
            else {
                fprintf(stderr, "\tAuthentication by password succeeded.\n");
            }
        }
        else if(auth_pw & 2) {
            /* Or via keyboard-interactive */
            if(libssh2_userauth_keyboard_interactive(session, username,
                                                     &kbd_callback) ) {
                fprintf(stderr,
                        "\tAuthentication by keyboard-interactive failed!\n");
                goto shutdown;
            }
            else {
                fprintf(stderr,
                        "\tAuthentication by keyboard-interactive succeeded.\n");
            }
        }
        else if(auth_pw & 4) {
            /* Or by public key */
            if(libssh2_userauth_publickey_fromfile(session, username, keyfile1,
                                                   keyfile2, password)) {
                fprintf(stderr, "\tAuthentication by public key failed!\n");
                goto shutdown;
            }
            else {
                fprintf(stderr, "\tAuthentication by public key succeeded.\n");
            }
        }
        else {
            fprintf(stderr, "No supported authentication methods found!\n");
            goto shutdown;
        }
    
        /* Request a shell */
        channel = libssh2_channel_open_session(session);
        if(!channel) {
            fprintf(stderr, "Unable to open a session\n");
            goto shutdown;
        }
    
        /* Some environment variables may be set,
         * It's up to the server which ones it'll allow though
         */
        libssh2_channel_setenv(channel, "FOO", "bar");
    
        /* Request a terminal with 'vanilla' terminal emulation
         * See /etc/termcap for more options
         */
        if(libssh2_channel_request_pty(channel, "vanilla")) {
            fprintf(stderr, "Failed requesting pty\n");
            goto skip_shell;
        }
    
        /* Open a SHELL on that pty */
        if(libssh2_channel_shell(channel)) {
            fprintf(stderr, "Unable to request shell on allocated pty\n");
            goto shutdown;
        }
    
        /* At this point the shell can be interacted with using
         * libssh2_channel_read()
         * libssh2_channel_read_stderr()
         * libssh2_channel_write()
         * libssh2_channel_write_stderr()
         *
         * Blocking mode may be (en|dis)abled with: libssh2_channel_set_blocking()
         * If the server send EOF, libssh2_channel_eof() will return non-0
         * To send EOF to the server use: libssh2_channel_send_eof()
         * A channel can be closed with: libssh2_channel_close()
         * A channel can be freed with: libssh2_channel_free()
         */
    
      skip_shell:
        if(channel) {
            libssh2_channel_free(channel);
            channel = NULL;
        }
    
        /* Other channel types are supported via:
         * libssh2_scp_send()
         * libssh2_scp_recv2()
         * libssh2_channel_direct_tcpip()
         */
    
      shutdown:
    
        libssh2_session_disconnect(session,
                                   "Normal Shutdown, Thank you for playing");
        libssh2_session_free(session);
    
    #ifdef WIN32
        closesocket(sock);
    #else
        close(sock);
    #endif
        fprintf(stderr, "all done!\n");
    
        libssh2_exit();
    
        return 0;
    }

     

     

     

    展开全文
  • 主要有两个类,代码如下:Ssh2头文件#ifndef SSH2_H #define SSH2_H #include "Channel.h" #include &lt;libssh2.h&gt; #ifdef WIN32 #pragma comment(lib,"Ws2_32.lib") #endif ...

    一、下载libssh2

        下载地址:https://download.csdn.net/download/wyansai/10494932

    二、QSshManager类

    #ifndef __SSH2_H
    #define __SSH2_H
    
    #include <libssh2.h>
    #include <vector>
    #include <mutex>
    #include <memory>
    
    #ifdef WIN32
    #pragma comment(lib,"Ws2_32.lib")
    #endif
    
    class QSshManager
    {
    public:
    	QSshManager();
    	virtual ~QSshManager();
    
    	bool connect(const char *szIp, int nPort = 22);
    
    	bool login(const char *szUserName, const char *szPassword);
    
    	// 返回值表示渠道的序号。如果返回-1,创建失败;
    	int createChannel(const char *szChannelTerm = "vanilla");
    
    	std::string read(int channelNo, const char *szEnd = "$", int timeout = 3000);
    
    	bool write(int channelNo, const char *szData);
    
    private:
    	SOCKET m_socket;
    	LIBSSH2_SESSION *m_session;
    	std::vector<LIBSSH2_CHANNEL*> m_channels;
    	std::vector<std::mutex *> m_channel_mutexs;
    };
    
    #endif // __SSH2_H

    ----------------------------

    #include "QSshManager.h"
    
    QSshManager::QSshManager() : m_session(nullptr), m_socket(INVALID_SOCKET)
    {
    	libssh2_init(0);
    }
    
    QSshManager::~QSshManager()
    {
    	if (!m_channels.empty()){
    		for (auto channel : m_channels) if (nullptr != channel) libssh2_channel_free(channel);
    		m_channels.clear();
    	}
    	if (!m_channel_mutexs.empty()){
    		for (auto mtx : m_channel_mutexs) delete mtx;
    		m_channel_mutexs.clear();
    	}
    
    	if (nullptr != m_session){
    		libssh2_session_disconnect(m_session, "Bye bye, Thank you");
    		libssh2_session_free(m_session);
    		m_session = nullptr;
    	}
    	
    	libssh2_exit();
    
    	if (INVALID_SOCKET != m_socket) closesocket(m_socket);
    
    #ifdef WIN32
    	WSACleanup();
    #endif
    }
    
    bool QSshManager::connect(const char *szIp, int nPort)
    {
    	
    #ifdef WIN32    
    	WSADATA wsa;
    	if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0) return false;
    #endif  
    
    	m_socket = socket(AF_INET, SOCK_STREAM, 0);
    
    	sockaddr_in sin;
    	sin.sin_family = AF_INET;
    	sin.sin_port = htons(nPort);
    	sin.sin_addr.s_addr = inet_addr(szIp);
    	return ::connect(m_socket, (sockaddr*)(&sin), sizeof(sockaddr_in)) == 0;
    }
    
    bool QSshManager::login(const char *szUserName, const char *szPassword)
    {
    	m_session = libssh2_session_init();
    
    	if (libssh2_session_handshake(m_session, m_socket)) return false;
    
    	libssh2_hostkey_hash(m_session, LIBSSH2_HOSTKEY_HASH_SHA1);
    
    	libssh2_userauth_list(m_session, szUserName, strlen(szUserName));
    
    	return !libssh2_userauth_password(m_session, szUserName, szPassword);
    }
    
    
    int QSshManager::createChannel(const char *szChannelTerm)
    {
    	if (nullptr == m_session) return -1;
    
    	LIBSSH2_CHANNEL* channel = libssh2_channel_open_session(m_session);
    
    	if (channel && !libssh2_channel_request_pty(channel, szChannelTerm))
    	{
    		if (!libssh2_channel_shell(channel)) {
    			m_channels.push_back(channel);
    			m_channel_mutexs.push_back(new std::mutex);
    			return m_channels.size() - 1;
    		}
    	}
    
    	if (channel) libssh2_channel_free(channel);
    
    	return -1;
    }
    
    std::string QSshManager::read(int channelNo, const char *szEnd, int timeout)
    {
    	std::string data;
    
    	if (channelNo > (m_channels.size() - 1)) return data;
    
    	std::lock_guard<std::mutex> locker(*m_channel_mutexs.at(channelNo));
    
    	LIBSSH2_CHANNEL * channel = m_channels.at(channelNo);
    
    	if (nullptr == channel) return data;
    
    	std::shared_ptr<LIBSSH2_POLLFD> fds = std::make_shared<LIBSSH2_POLLFD>();
    
    	fds->type = LIBSSH2_POLLFD_CHANNEL;
    	fds->fd.channel = channel;
    	fds->events = LIBSSH2_POLLFD_POLLIN | LIBSSH2_POLLFD_POLLOUT;
    
    	auto compareEndNoSpace = [](const std::string& str, const std::string& endstr){
    		size_t pos = str.rfind(endstr);
    		return pos != std::string::npos && str.substr(pos, endstr.size()) == endstr;
    	};
    	
    	do{
    		int rc = (libssh2_poll(fds.get(), 1, 10));
    
    		if ((rc >= 1) && (fds->revents & LIBSSH2_POLLFD_POLLIN))
    		{
    			char buffer[64 * 1024] = {0};
    			size_t n = libssh2_channel_read(channel, buffer, sizeof(buffer));
    
    			if (n != LIBSSH2_ERROR_EAGAIN){
    				if (n > 0) data.append(buffer);
    				if (n <= 0 || strlen(szEnd) == 0 || compareEndNoSpace(data,szEnd)) return data;
    			}
    		}
    
    		timeout -= 50;
    		Sleep(50);
    	}while (timeout > 0);
    
    	return data;
    }
    
    bool QSshManager::write(int channelNo, const char *szData)
    {
    	std::lock_guard<std::mutex> locker(*m_channel_mutexs.at(channelNo));
    
    	LIBSSH2_CHANNEL * channel = m_channels.at(channelNo);
    
    	if (nullptr == channel) return false;
    
    	std::string send_data = szData;
    	send_data.append("\n");
    
    	return libssh2_channel_write_ex(channel, 0, send_data.c_str(), send_data.size()) == send_data.size();
    }
    

    三、在Qt中使用如下:

    void sshDemo::on_pushButton_ssh_clicked()
    {
    	QSshManager ssh;
    
    	if (!ssh.connect("192.168.71.129")){
    		qDebug() << QString("连接失败"); return;
    	}
    
    	if (!ssh.login("php", "php")){
    		qDebug() << QString("登录失败"); return;
    	}
    
    	int channelNo = ssh.createChannel("ubuntu1");
    
    	if (channelNo == -1) {
    		qDebug() << QString("创建channel失败"); return;
    	}
    
    	qDebug() << ssh.read(channelNo).c_str();
    
    	ssh.write(channelNo, "ls");
    	qDebug() << ssh.read(channelNo).c_str();
    
    }

    PS:引用这个类,一定要放在Qt的头文件之上,不然会报wsa重定义之类的错误,如下:

    #pragma once
    
    #include "QSshManager.h"
    #include <QtWidgets>
    #include <vld.h>
    #include "ui_sshDemo.h"







    展开全文
  • libssh2_sftp.h> #include<string> #include <arpa/inet.h> #include <sys/socket.h> using std::string; enum MSSH2ErrorCode{ socketError, initSSH2Error, connectEr

    1.mSSH2头文件源码及说明

    1.1源码

    #include <libssh2.h>
    #include <libssh2_sftp.h>
    #include<string>
    #include <arpa/inet.h>
    #include <sys/socket.h>
    using std::string;
    
    enum MSSH2ErrorCode{
        socketError,
        initSSH2Error,
        connectError,
        initSessionError,
        passwordAuthenticationMethodNotAllow,
        usernameOrPasswordError,
        openSessionError,
        requestPtyError,
        openShellError,
        noError
    };
    class MSSH2
    {
    private:
        int sock;
        int rc;
        struct sockaddr_in sin;
        LIBSSH2_SESSION *session;
        LIBSSH2_CHANNEL *channel;
        MSSH2ErrorCode initSSH2();
        MSSH2ErrorCode connectSSH(const string &hostaddr);
        MSSH2ErrorCode initSession();
        MSSH2ErrorCode isAllowPasswordAuthenticationMethod(const string &username);
        MSSH2ErrorCode userauthPassword(const string &username,const string &password);
        MSSH2ErrorCode openSession();
        MSSH2ErrorCode requestPty();    // 保留
        MSSH2ErrorCode openShell(); // 保留
        void closeChannel();
        void closeSession();
    public:
        MSSH2();
        MSSH2ErrorCode start(const string &hostaddr,const string &username,const string &password);
        string execCmd(const string &cmd);
        ~MSSH2();
    };

    1.2说明

    private中包含了一些初始化操作需要用到的函数,比如初始化ssh,初始化会话,初始化套接字等。

    public中包含了启动mSSH2和执行命令的函数。

    该类的使用过程是:创建一个mSSH2对象,然后start,然后execCmd即可。使用过程比较简单,但是需要提前安装libssh2。

    2.mSSH2的具体实现

    #include "mSSH2.h"
    
    MSSH2::MSSH2()
    {
        sock = socket(AF_INET, SOCK_STREAM, 0);
    }
    
    MSSH2ErrorCode MSSH2::initSSH2()
    {
        rc = libssh2_init(0);
        if (rc != 0)
        {
            return MSSH2ErrorCode::initSSH2Error;
        }
        return MSSH2ErrorCode::noError;
    }
    
    MSSH2ErrorCode MSSH2::connectSSH(const string &hostAddr)
    {
        /* Ultra basic "connect to port 22 on localhost"
         * Your code is responsible for creating the socket establishing the
         * connection
         */
        unsigned long hostaddr = inet_addr(hostAddr.c_str());
        sin.sin_family = AF_INET;
        sin.sin_port = htons(22);
        sin.sin_addr.s_addr = hostaddr;
        if (connect(sock, (struct sockaddr *)(&sin), sizeof(struct sockaddr_in)) != 0)
        {
            return MSSH2ErrorCode::connectError;
        }
        return MSSH2ErrorCode::noError;
    }
    
    MSSH2ErrorCode MSSH2::initSession()
    {
         /* Create a session instance */
        session = libssh2_session_init();
    
        /* tell libssh2 we want it all done non-blocking */
        // libssh2_session_set_blocking(session, 0);
        
        /* ... start it up. This will trade welcome banners, exchange keys,
         * and setup crypto, compression, and MAC layers
         */
        if (libssh2_session_handshake(session, sock))
        {
            return MSSH2ErrorCode::initSessionError;
        }
        return MSSH2ErrorCode::noError;
    }
    
    MSSH2ErrorCode MSSH2::isAllowPasswordAuthenticationMethod(const string &username)
    {
        char *userauthlist = libssh2_userauth_list(session, username.c_str(), strlen(username.c_str()));
        if (strstr(userauthlist, "password") == NULL)
        {
            return MSSH2ErrorCode::passwordAuthenticationMethodNotAllow;
        }
        return MSSH2ErrorCode::noError;
    }
    
    MSSH2ErrorCode MSSH2::userauthPassword(const string &username, const string &password)
    {
        if (libssh2_userauth_password(session, username.c_str(), password.c_str()))
        {
            return MSSH2ErrorCode::usernameOrPasswordError;
        }
        return MSSH2ErrorCode::noError;
    }
    
    MSSH2ErrorCode MSSH2::openSession()
    {
        channel = libssh2_channel_open_session(session);
        if(!channel)
        {
            return MSSH2ErrorCode::openSessionError;
        }
        return MSSH2ErrorCode::noError;
    }
    // 弃用
    MSSH2ErrorCode MSSH2::requestPty()
    {
        if(libssh2_channel_request_pty(channel, "vanilla")) {
            return MSSH2ErrorCode::requestPtyError;
        }
        return MSSH2ErrorCode::noError;
    }
    //弃用
    MSSH2ErrorCode MSSH2::openShell()
    {
        if(libssh2_channel_shell(channel)) {
            return MSSH2ErrorCode::openShellError;
        }
        return MSSH2ErrorCode::noError;
    }
    
    MSSH2ErrorCode MSSH2::start(const string &hostaddr,const string &username,const string &password)
    {
        if(sock == -1)
        {
            return MSSH2ErrorCode::socketError;
        }
    
        MSSH2ErrorCode mSSH2ErrorCode = initSSH2();
        if(mSSH2ErrorCode!=MSSH2ErrorCode::noError)
        {
            return mSSH2ErrorCode;
        }
    
        mSSH2ErrorCode = connectSSH(hostaddr);
        if(mSSH2ErrorCode!=MSSH2ErrorCode::noError)
        {
            return mSSH2ErrorCode;
        }
    
        mSSH2ErrorCode = initSession();
        if(mSSH2ErrorCode!=MSSH2ErrorCode::noError)
        {
            return mSSH2ErrorCode;
        }
    
        mSSH2ErrorCode = isAllowPasswordAuthenticationMethod(username);
        if(mSSH2ErrorCode!=MSSH2ErrorCode::noError)
        {
            return mSSH2ErrorCode;
        }
    
        mSSH2ErrorCode = userauthPassword(username,password);
        if(mSSH2ErrorCode!=MSSH2ErrorCode::noError)
        {
            return mSSH2ErrorCode;
        }
    
        mSSH2ErrorCode =openSession();
        if(mSSH2ErrorCode!=MSSH2ErrorCode::noError)
        {
            return mSSH2ErrorCode;
        }
        /*
        mSSH2ErrorCode =requestPty();
        if(mSSH2ErrorCode!=MSSH2ErrorCode::noError)
        {
            return mSSH2ErrorCode;
        }
    
        mSSH2ErrorCode =openShell();
        if(mSSH2ErrorCode!=MSSH2ErrorCode::noError)
        {
            return mSSH2ErrorCode;
        }
        */
        return MSSH2ErrorCode::noError;
    }
    string MSSH2::execCmd(const string &cmd)
    {
        // exec cmd
        rc = libssh2_channel_exec(channel,cmd.c_str());
        if(rc !=0)
        {
            return "";
        }
        // get end
        char buffer[0x4000];
        rc = libssh2_channel_read(channel, buffer, sizeof(buffer) );
        if(rc >0)
        {
            return buffer;
        }
        else
        {
            return "";
        }
    }
    
    void MSSH2::closeChannel()
    {
        int exitcode = 127;
        rc = libssh2_channel_close(channel);
    
        char *exitsignal = (char *)"none";
        if(rc == 0) {
            exitcode = libssh2_channel_get_exit_status(channel);
            libssh2_channel_get_exit_signal(channel, &exitsignal,
                                            NULL, NULL, NULL, NULL, NULL);
        }
    
        if(exitsignal)
            fprintf(stderr, "\nGot signal: %s\n", exitsignal);
        else
            fprintf(stderr, "\nEXIT: %d\n", exitcode);
    
        libssh2_channel_free(channel);
        channel = NULL;
    }
    
    void MSSH2::closeSession()
    {
        libssh2_session_disconnect(session,
                                   "Normal Shutdown, Thank you for playing");
        libssh2_session_free(session);
    }
    
    MSSH2::~MSSH2()
    {
        if (channel)
        {
            closeChannel();
        }
        if (session)
        {
            closeSession();
        }
        close(sock);
        libssh2_exit();
    }

    3.mSSH2的使用

    #include"mSSH2.h"
    #include<iostream>
    using std::cout;
    
    int main(int argc,char *argv[])
    {
        MSSH2 mSSH2;
        if(mSSH2.start("127.0.0.1","ubuntu","123456")!=MSSH2ErrorCode::noError)
        {
            cout<<"start error\n";
            return 0;
        }
        std::cout<<mSSH2.execCmd("ls -ltr");
        return 0;
    }

    展开全文
  • libssh2使用

    千次阅读 2019-08-28 18:30:47
    在项目中,使用ssh连接远程服务过程中,由于服务端底层修改,导致ssh执行命令异常,方案采用模拟putty客户端方式...2,当时操作步骤1时,会出现数据格式存在问题,因此可以修改API, #define MAX_PTY_SIZE (40960...
  • libssh2的简单应用

    万次阅读 2013-06-26 15:23:27
    首先,libssh2.lib的这个库一定要有(下载地址提供:http://download.csdn.net/detail/wyc6668205/5651661) 其次,介绍一下libssh2的官网:www.libssh2.org;虽然这个网站里面内容是全英文的,我想所有的计算机...
  • C/C++编程:libssh2 API学习

    千次阅读 2021-01-20 16:48:58
    libssh2_version #include <libssh2.h> const char * libssh2_version(int required_version); 描述: 如果required_version小于或等于使用中的libssh2的版本号,则将libssh2的版本号作为指向零终止字符...
  • 1:下载源码:libssh2https://www.libssh2.org/ 2.OpenSSL安装 编译libssh2需要安装OpenSSL,这里自己编译库比较复杂,直接安装带库的包比较方便: 直接从Win32/Win64 OpenSSL Installer for Windows - ...
  • #include "libssh2_config.h" #include <libssh2.h> #ifdef HAVE_WINSOCK2_H #include <winsock2.h> #endif #ifdef HAVE_SYS_SOCKET_H #include <sys/socket.h> #endif #ifdef HAVE_NETINET_IN_H...
  • 请教大家一个问题,在用libssh2_channel_read()读取通道的内容时,需要多次读取,但是读到最后libssh2_channel_read() 没有返回, do { rc = libssh2_channel_read(channel,buf,1023); fprintf(stderr,"%s\n...
  • libssh2--ssh2实例

    2018-10-19 14:35:00
    #include "libssh2_config.h"#include<libssh2.h>#include<libssh2_sftp.h> 上述为所包含必备头文件。 以下为定义的静态子串常量 const char *keyfile1 = "~/.ssh/id_rsa.pub"; const char *key...
  • 环境配置 1、官网 2、下载地址 3、开始: ...$ tar -xvf libssh2-1.9.0-20210118.tar.gz $ cd libssh2-1.9.0-20210118/ version: 1.9.0-20210118 Host type: x86_64-pc-linux-gnu Install pre
  • } /* 至此,可以交互使用shell了 * libssh2_channel_read() * libssh2_channel_read_stderr() * libssh2_channel_write() * libssh2_channel_write_stderr() * * Blocking mode may be (en|dis)abled with(打开或...
  • 目录一:libssh2介绍:二:安装:二:测试ssh2功能:远程执行主机shell命令: 一:libssh2介绍: 1.libssh2是一个C 函数库,用来实现SSH2协议。 SSH2是一套安全通讯协议框架(早期的SSH1由于存在安全漏洞),基于SSH...
  • 比如,c/c++语言可以使用libssh2;python可以使用paramkio库等。但这些库网上的帮助,都不是很全,都比较浅显。shell自动化,最基本的三个需求,一个是适合多重类型的操作系统;二是要能够支持交互式shell,比如使用...
  • 使用libssh2连接到远程服务器

    千次阅读 2018-01-30 15:35:00
    libssh2-1.7.0.tar.gz示例代码:libssh2-1.7.0.tar.gz\libssh2-1.7.0\example官网示例https://www.libssh2.org/examples/libssh2 进行 SFTP 文件传输libssh2的官网:www.libssh2.org;这里面提供了很多例子,比如FTP...
  • /* loop until we fail */ while((rc = libssh2_sftp_read(sftp_handle, mem, sizeof(mem))) == LIBSSH2_ERROR_EAGAIN) { spin++; waitsocket(sock, session); /* now we wait */ } if(rc > 0) { total += rc; ...
  • 代码如下:#include #include #include #include #include #include #include #include #include #include #include #include #include #include #define COPYRIGHT "SSH2 v1.0\nCopyright (C) 2014 \n\n"struct ...
  • 交叉编译libssh2

    2021-09-14 10:48:42
    需要实现sftp从服务器上下载文件,通过调用openssl+libssh2里的接口实现,在libssh2中example中有sftp的实现源码,可以在此基础上进行修改。 交叉编译过程: 1.openssl.1.1.1l.tar.gz ... 配置命令:./Configure ...
  • /** * CSSHClient.h * @file 说明信息.. * DATE February 13 2015 * * @author Ming_zhang */ ...#ifndef _CSSHCLIENT_H_ ... rc = libssh2_channel_read( m_hSSHChannel, buffer, sizeof(buffer) ); if...
  • libssh2_channel_read(channel, &buf, 1); fprintf(stdout, "%c", buf); fflush(stdout); } if (select(fileno(stdin)+1,&set,NULL,NULL,&timeval_out) > 0) if (read(fileno(stdin), &buf, 1) > 0) libssh...
  • libssh

    2018-10-18 17:47:00
    libssh2_channel_open:在通道错误消息中修复了speeling错误; msvc:修复了14个编译警告; tests:HAVE_NETINET_IN_H未正确定义; openssl:添加OpenSSL 1.1.0兼容性; cmake:添加CLEAR_MEMORY选项,类似...
  • 最近涉及到sftp通信编码。上传测试代码记录一下。... #include "libssh2/win32/libssh2_config.h" #endif #include <mutex> #include <memory> #include <QThread>...
  • ActivePerl + OpenSSL + Zlib + Libssh2 + Visual Studio 2008 SSH2是一套安全通讯协议框架(早期的SSH1由于存在安全漏洞,现在已经不用了),基于SSH2协议的产品目前主要有openssh(http://www.openssh.org/),...

空空如也

空空如也

1 2 3 4 5 ... 7
收藏数 138
精华内容 55
关键字:

libssh2_channel_read