39.linux下安装libssh2:测试远程执行shell命令

一:libssh2介绍:

1.libssh2是一个C 函数库,用来实现SSH2协议。
SSH2是一套安全通讯协议框架(早期的SSH1由于存在安全漏洞),基于SSH2协议的产品主要有openssh,putty,SSH Secure Shell Client等,这些都是开源的,但是这些代码非常难懂而且复杂,一个个函数深层次的调用很快就让人在C语言代码的海洋中迷失了方向,妄图通过从这些开源软件中抽取程序代码段来“组装”自己的应用程序是非一般人所能实现的。不过还好网络上出现了一些开源的SSH2开发库,利用这些开发库开发自己的SSH2程序却要简单得多,由于这些开发库都是开源的,往往是针对linux平台的,而且一般只提供了源代码。

二:安装:

1.下载:

https://www.libssh2.org/

2.解压安装:

sudo tar -zxvf libssh2-1.9.0.tar.gz -C .
mkdir install_lib
sudo ./configure --prefix=/home/aston/huawei/libssh2-1.9.0/install_lib --with-openssl CPPFLAGS="-I/home/aston/huawei/openssl-1.1.1d/install_lib/include" LDFLAGS="-L/home/aston/huawei/openssl-1.1.1d/install_lib/lib"

sudo make
sudo make install

注:
CPPFLAGS需指定openssl的头文件路径;
LDFLAGS需指定openssl的库路径;

3.安装完成:

在这里插入图片描述

三:测试ssh2功能:远程执行主机shell命令:

测试文件:

"D:\share\source_insight\main_135\obs_sdk\libssh2-1.9.0\example\ssh2_exec.c"

代码:

/*
 * Sample showing how to use libssh2 to execute a command remotely.
 *
 * The sample code has fixed values for host name, user name, password
 * and command to run.
 *
 * Run it like this:
 *
 * $ ./ssh2_exec 127.0.0.1 user password "uptime"
 *
 */

//#include "libssh2_config.h"
#include <libssh2.h>

#include <sys/socket.h> 
#include <netinet/in.h> 
#include <unistd.h> 
#include <arpa/inet.h> 
#include <stdlib.h>


#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_SYS_SELECT_H
# include <sys/select.h>
#endif
# ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#ifdef HAVE_ARPA_INET_H
# include <arpa/inet.h>
#endif
#ifdef HAVE_SYS_TIME_H
#include <sys/time.h>
#endif
#include <sys/types.h>
#ifdef HAVE_STDLIB_H
#include <stdlib.h>
#endif
#include <fcntl.h>
#include <errno.h>
#include <stdio.h>
#include <ctype.h>

static int waitsocket(int socket_fd, LIBSSH2_SESSION *session)
{
    struct timeval timeout;
    int rc;
    fd_set fd;
    fd_set *writefd = NULL;
    fd_set *readfd = NULL;
    int dir;

    timeout.tv_sec = 10;
    timeout.tv_usec = 0;

    FD_ZERO(&fd);

    FD_SET(socket_fd, &fd);

    /* now make sure we wait in the correct direction */
    dir = libssh2_session_block_directions(session);

    if(dir & LIBSSH2_SESSION_BLOCK_INBOUND)
        readfd = &fd;

    if(dir & LIBSSH2_SESSION_BLOCK_OUTBOUND)
        writefd = &fd;

    rc = select(socket_fd + 1, readfd, writefd, NULL, &timeout);

    return rc;
}

int main(int argc, char *argv[])
{
    const char *hostname = "127.0.0.1";
    const char *commandline = "uptime";
    const char *username    = "user";
    const char *password    = "password";
    unsigned long hostaddr;
    int sock;
	
    struct sockaddr_in sin;
    const char *fingerprint;
    LIBSSH2_SESSION *session;
    LIBSSH2_CHANNEL *channel;
    int rc;
    int exitcode;
    char *exitsignal = (char *)"none";
    int bytecount = 0;
    size_t len;
    LIBSSH2_KNOWNHOSTS *nh;
    int type;

    if(argc > 1)
        /* must be ip address only */
        hostname = argv[1];

    if(argc > 2) {
        username = argv[2];
    }
    if(argc > 3) {
        password = argv[3];
    }
    if(argc > 4) {
        commandline = argv[4];
    }

    rc = libssh2_init(0);
    if(rc != 0) {
        fprintf(stderr, "libssh2 initialization failed (%d)\n", rc);
        return 1;
    }

    hostaddr = inet_addr(hostname);

    /* 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 */
    session = libssh2_session_init();
    if(!session)
        return -1;

    /* 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
     */
    while((rc = libssh2_session_handshake(session, sock)) ==
           LIBSSH2_ERROR_EAGAIN);
    if(rc) {
        fprintf(stderr, "Failure establishing SSH session: %d\n", rc);
        return -1;
    }

    nh = libssh2_knownhost_init(session);
    if(!nh) {
        /* eeek, do cleanup here */
        return 2;
    }

    /* read all hosts from here */
    libssh2_knownhost_readfile(nh, "known_hosts",
                               LIBSSH2_KNOWNHOST_FILE_OPENSSH);

    /* store all known hosts to here */
    libssh2_knownhost_writefile(nh, "dumpfile",
                                LIBSSH2_KNOWNHOST_FILE_OPENSSH);

    fingerprint = libssh2_session_hostkey(session, &len, &type);
    if(fingerprint) {
        struct libssh2_knownhost *host;
#if LIBSSH2_VERSION_NUM >= 0x010206
        /* introduced in 1.2.6 */
        int check = libssh2_knownhost_checkp(nh, hostname, 22,
                                             fingerprint, len,
                                             LIBSSH2_KNOWNHOST_TYPE_PLAIN|
                                             LIBSSH2_KNOWNHOST_KEYENC_RAW,
                                             &host);
#else
        /* 1.2.5 or older */
        int check = libssh2_knownhost_check(nh, hostname,
                                            fingerprint, len,
                                            LIBSSH2_KNOWNHOST_TYPE_PLAIN|
                                            LIBSSH2_KNOWNHOST_KEYENC_RAW,
                                            &host);
#endif
        fprintf(stderr, "Host check: %d, key: %s\n", check,
                (check <= LIBSSH2_KNOWNHOST_CHECK_MISMATCH)?
                host->key:"<none>");

        /*****
         * At this point, we could verify that 'check' tells us the key is
         * fine or bail out.
         *****/
    }
    else {
        /* eeek, do cleanup here */
        return 3;
    }
    libssh2_knownhost_free(nh);

    if(strlen(password) != 0) {
        /* We could authenticate via password */
        while((rc = libssh2_userauth_password(session, username, password)) ==
               LIBSSH2_ERROR_EAGAIN);
        if(rc) {
            fprintf(stderr, "Authentication by password failed.\n");
            goto shutdown;
        }
    }
    else {
        /* Or by public key */
        while((rc = libssh2_userauth_publickey_fromfile(session, username,
                                                         "/home/user/"
                                                         ".ssh/id_rsa.pub",
                                                         "/home/user/"
                                                         ".ssh/id_rsa",
                                                         password)) ==
               LIBSSH2_ERROR_EAGAIN);
        if(rc) {
            fprintf(stderr, "\tAuthentication by public key failed\n");
            goto shutdown;
        }
    }

#if 0
    libssh2_trace(session, ~0);
#endif

    /* Exec non-blocking on the remove host */
    while((channel = libssh2_channel_open_session(session)) == NULL &&
          libssh2_session_last_error(session, NULL, NULL, 0) ==
          LIBSSH2_ERROR_EAGAIN) {
        waitsocket(sock, session);
    }
    if(channel == NULL) {
        fprintf(stderr, "Error\n");
        exit(1);
    }
    while((rc = libssh2_channel_exec(channel, commandline)) ==
           LIBSSH2_ERROR_EAGAIN) {
        waitsocket(sock, session);
    }
    if(rc != 0) {
        fprintf(stderr, "Error\n");
        exit(1);
    }
    for(;;) {
        /* loop until we block */
        int rc;
        do {
            char buffer[0x4000];
            rc = libssh2_channel_read(channel, buffer, sizeof(buffer) );
            if(rc > 0) {
                int i;
                bytecount += rc;
                fprintf(stderr, "We read:\n");
                for(i = 0; i < rc; ++i)
                    fputc(buffer[i], stderr);
                fprintf(stderr, "\n");
            }
            else {
                if(rc != LIBSSH2_ERROR_EAGAIN)
                    /* no need to output this for the EAGAIN case */
                    fprintf(stderr, "libssh2_channel_read returned %d\n", rc);
            }
        }
        while(rc > 0);

        /* this is due to blocking that would occur otherwise so we loop on
           this condition */
        if(rc == LIBSSH2_ERROR_EAGAIN) {
            waitsocket(sock, session);
        }
        else
            break;
    }
    exitcode = 127;
    while((rc = libssh2_channel_close(channel)) == LIBSSH2_ERROR_EAGAIN)
        waitsocket(sock, session);

    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 bytecount: %d\n", exitcode, bytecount);

    libssh2_channel_free(channel);
    channel = NULL;

shutdown:

    libssh2_session_disconnect(session,
                               "Normal Shutdown, Thank you for playing");
    libssh2_session_free(session);

    close(sock);
    fprintf(stderr, "all done\n");

    libssh2_exit();

    return 0;
}


2.报错:没有libssh2_config.h头文件:
解决:注释掉,再添加必要的C库头文件即可。

//#include "libssh2_config.h"
#include <libssh2.h>

#include <sys/socket.h> 
#include <netinet/in.h> 
#include <unistd.h> 
#include <arpa/inet.h> 
#include <stdlib.h>

3.执行本地aston用户的命令:显示主目录文件列表:

./app.out 127.0.0.1 aston root ls

在这里插入图片描述
在这里插入图片描述
4.如需要指令长指令,如:ls -l ,则需要使用双引号括起来"ls -l"
在这里插入图片描述

四:移植libssh2:

sudo tar -zxvf libssh2-1.9.0.tar.gz -C .
sudo chown -R aston libssh2-1.9.0
mkdir install_lib

sudo ./configure --prefix=/home/aston/huawei_linux/libssh2-1.9.0/install_lib --host=arm-linux CC=/opt/hisi-linux/x86-arm/arm-hisiv300-linux/target/bin/arm-hisiv300-linux-gcc CXX=/opt/hisi-linux/x86-arm/arm-hisiv300-linux/target/bin/arm-hisiv300-linux-g++ --with-openssl CFLAGS="-I/home/aston/huawei_linux/openssl-1.1.1d/install_lib/include -I/home/aston/huawei_linux/zlib-1.2.11/install_lib/include" LDFLAGS="-L/home/aston/huawei_linux/openssl-1.1.1d/install_lib/lib -L/home/aston/huawei_linux/zlib-1.2.11/install_lib/lib -lcrypto -lssl -ldl -lpthread -lz"

/home/aston/huawei_linux/zlib-1.2.11/install_lib/lib
sudo make
sudo make install

注:
CPPFLAGS 需指定openssl的头文件路径;
LDFLAGS 需指定openssl的库路径;

报错1:

…/src/.libs/libssh2.so: undefined reference to `dlopen’
解决: ./configure的LDFLAGS添加参数: -ldl -lpthread
LDFLAGS="-L/home/aston/huawei_linux/openssl-1.1.1d/install_lib/lib -ldl -lpthread"

报错2:

../src/.libs/libssh2.so: undefined reference to `deflate'
../src/.libs/libssh2.so: undefined reference to `inflate'
../src/.libs/libssh2.so: undefined reference to `inflateInit_'
../src/.libs/libssh2.so: undefined reference to `deflateInit_'
../src/.libs/libssh2.so: undefined reference to `zError'
../src/.libs/libssh2.so: undefined reference to `pthread_atfork'
../src/.libs/libssh2.so: undefined reference to `inflateEnd'
../src/.libs/libssh2.so: undefined reference to `deflateEnd'
collect2: error: ld returned 1 exit status

解决: ./configure的LDFLAGS添加参数: -lz

LDFLAGS="-L/home/aston/huawei_linux/openssl-1.1.1d/install_lib/lib -L/home/aston/huawei_linux/zlib-1.2.11/install_lib/lib -ldl -lpthread -lz"

遇到的问题3:

/opt/hisi-linux/x86-arm/arm-himix400-linux/host_bin/../lib/gcc/arm-linux-gnueabi/7.3.0/../../../../arm-linux-gnueabi/bin/ld: warning: libssl.so.1.1, needed by ../src/.libs/libssh2.so, not found (try using -rpath or -rpath-link)
/opt/hisi-linux/x86-arm/arm-himix400-linux/host_bin/../lib/gcc/arm-linux-gnueabi/7.3.0/../../../../arm-linux-gnueabi/bin/ld: warning: libcrypto.so.1.1, needed by ../src/.libs/libssh2.so, not found (try using -rpath or -rpath-link)
/opt/hisi-linux/x86-arm/arm-himix400-linux/host_bin/../lib/gcc/arm-linux-gnueabi/7.3.0/../../../../arm-linux-gnueabi/bin/ld: ../src/.libs/libssh2.so: undefined reference to `EVP_MD_CTX_free@OPENSSL_1_1_0'
/opt/hisi-linux/x86-arm/arm-himix400-linux/host_bin/../lib/gcc/arm-linux-gnueabi/7.3.0/../../../../arm-linux-gnueabi/bin/ld: ../src/.libs/libssh2.so: undefined reference to `EVP_PKEY2PKCS8@OPENSSL_1_1_0'
/opt/hisi-linux/x86-arm/arm-himix400-linux/host_bin/../lib/gcc/arm-linux-gnueabi/7.3.0/../../../../arm-linux-gnueabi/bin/ld: ../src/.libs/libssh2.so: undefined reference to `DSA_free@OPENSSL_1_1_0'
/opt/hisi-linux/x86-arm/arm-himix400-linux/host_bin/../lib/gcc/arm-linux-gnueabi/7.3.0/../../../../arm-linux-gnueabi/bin/ld: ../src/.libs/libssh2.so: undefined reference to `BN_rand@OPENSSL_1_1_0'

原因是:未添加库的连接:-lcrypto -lssl 参数:

LDFLAGS="-L/opt/huawei_linux/openssl-1.1.1d/install_lib/lib -L/opt/huawei_linux/zlib-1.2.11/install_lib/lib -lcrypto -lssl -ldl -lpthread -lz"

重新编译成功.

六:ARM设备上测试:(暂未成功)

测试:

./app.out 127.0.0.1 root root "ls"
./app.out 127.0.0.1 "" "" "ls"
./app.out 127.0.0.1 "" "" "ls"
./app.out 127.0.0.1 "" "" "ls"
./app.out 127.0.0.1 root "" ls
./app.out 127.0.0.1 root root ls
./app.out 192.168.1.141 aston root "ls"
./app.out 192.168.1.141 root root "ls"
好的,以下是基于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"` 替换为实际的命令
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值