LibSSH2简单入门-exec、sftp

这篇具有很好参考价值的文章主要介绍了LibSSH2简单入门-exec、sftp。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

LibSSH2简单入门-exec、sftp

1、libssh2官方地址:libssh2

libssh2的官方文档和官方示例代码非常的棒,基本可以直接参考

官方文档:libssh2 docs

官方示例:libssh2 examples

2、推荐阅读两个示例,基本可以完成对libssh2的理解和使用了

2.1、ssh2_exec.c 通过libssh2在远端机器上执行指令,并获取指令的返回值

/* Copyright (C) The libssh2 project and its contributors.
 *
 * 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.
 *
 * $ ./ssh2_exec 127.0.0.1 user password "uptime"
 *
 * SPDX-License-Identifier: BSD-3-Clause
 */ 
 
#include "libssh2_setup.h"
#include <libssh2.h>
 
#ifdef HAVE_SYS_SOCKET_H
#include <sys/socket.h>
#endif
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#ifdef HAVE_NETINET_IN_H
#include <netinet/in.h>
#endif
#ifdef HAVE_ARPA_INET_H
#include <arpa/inet.h>
#endif
 
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
static const char *hostname = "127.0.0.1";
static const char *commandline = "uptime";
static const char *pubkey = "/home/username/.ssh/id_rsa.pub";
static const char *privkey = "/home/username/.ssh/id_rsa";
static const char *username = "user";
static const char *password = "password";
 
static int waitsocket(libssh2_socket_t 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((int)(socket_fd + 1), readfd, writefd, NULL, &timeout);
    return rc;
}
 
int main(int argc, char *argv[])
{
    uint32_t hostaddr;
    libssh2_socket_t sock;
    struct sockaddr_in sin;
    const char *fingerprint;
    int rc;
    LIBSSH2_SESSION *session = NULL;
    LIBSSH2_CHANNEL *channel;
    int exitcode;
    char *exitsignal = (char *)"none";
    ssize_t bytecount = 0;
    size_t len;
    LIBSSH2_KNOWNHOSTS *nh;
    int type;
 
#ifdef WIN32
    WSADATA wsadata;
 
    rc = WSAStartup(MAKEWORD(2, 0), &wsadata);
    if(rc) {
        fprintf(stderr, "WSAStartup failed with error: %d\n", rc);
        return 1;
    }
#endif
 
    if(argc > 1) {
        hostname = argv[1];  /* must be ip address only */ 
    }
    if(argc > 2) {
        username = argv[2];
    }
    if(argc > 3) {
        password = argv[3];
    }
    if(argc > 4) {
        commandline = argv[4];
    }
 
    rc = libssh2_init(0);

    if(rc) {
        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);
    if(sock == LIBSSH2_INVALID_SOCKET) {
        fprintf(stderr, "failed to create socket.\n");
        goto shutdown;
    }
 
    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))) {
        fprintf(stderr, "failed to connect.\n");
        goto shutdown;
    }
 
    /* Create a session instance */ 
    session = libssh2_session_init();

    if(!session) {
        fprintf(stderr, "Could not initialize SSH session.\n");
        goto shutdown;
    }
 
    /* 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);
        goto shutdown;
    }
 
    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;
        int check = libssh2_knownhost_checkp(nh, hostname, 22,
                                             fingerprint, len,
                                             LIBSSH2_KNOWNHOST_TYPE_PLAIN|
                                             LIBSSH2_KNOWNHOST_KEYENC_RAW,
                                             &host);
 
        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,
                                                        pubkey, privkey,
                                                        password)) ==
              LIBSSH2_ERROR_EAGAIN);
        if(rc) {
            fprintf(stderr, "Authentication by public key failed.\n");
            goto shutdown;
        }
    }
 
#if 0
    libssh2_trace(session, ~0);

#endif
 
    /* Exec non-blocking on the remote host */ 
    do {
        channel = libssh2_channel_open_session(session);
        if(channel ||
           libssh2_session_last_error(session, NULL, NULL, 0) !=
           LIBSSH2_ERROR_EAGAIN)
            break;
        waitsocket(sock, session);
    } while(1);
    if(!channel) {
        fprintf(stderr, "Error\n");
        exit(1);
    }
    while((rc = libssh2_channel_exec(channel, commandline)) == LIBSSH2_ERROR_EAGAIN) {
        waitsocket(sock, session);
    }
    if(rc) {
        fprintf(stderr, "exec error\n");
        exit(1);
    }
    for(;;) {
        ssize_t nread;
        /* loop until we block */ 
        do {
            char buffer[0x4000];
            nread = libssh2_channel_read(channel, buffer, sizeof(buffer));
            if(nread > 0) {
                ssize_t i;
                bytecount += nread;
                fprintf(stderr, "We read:\n");
                for(i = 0; i < nread; ++i)
                    fputc(buffer[i], stderr);
                fprintf(stderr, "\n");
            }
            else {
                if(nread != LIBSSH2_ERROR_EAGAIN)
                    /* no need to output this for the EAGAIN case */ 
                    fprintf(stderr, "libssh2_channel_read returned %d\n",
                            (int)nread);
            }
        }
        while(nread > 0);
 
        /* this is due to blocking that would occur otherwise so we loop on
           this condition */ 
        if(nread == 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, (int)bytecount);
    libssh2_channel_free(channel);
    channel = NULL;
 
shutdown:
 
    if(session) {
        libssh2_session_disconnect(session, "Normal Shutdown");
        libssh2_session_free(session);

    }
 
    if(sock != LIBSSH2_INVALID_SOCKET) {
        shutdown(sock, 2);
#ifdef WIN32
        closesocket(sock);
#else
        close(sock);
#endif
    } 
    fprintf(stderr, "all done\n");
    libssh2_exit();
    return 0;
}

2.2、sftp_write_nonblock.c 使用libssh2进行sftp将本端文件传输到远端机器上的功能

/* Copyright (C) The libssh2 project and its contributors.
 *
 * Sample showing how to do SFTP non-blocking write transfers.
 *
 * 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:
 *
 * $ ./sftp_write_nonblock 192.168.0.1 user password thisfile /tmp/storehere
 *
 * SPDX-License-Identifier: BSD-3-Clause
 */ 
 
#include "libssh2_setup.h"
#include <libssh2.h>
#include <libssh2_sftp.h>
 
#ifdef HAVE_SYS_SOCKET_H
#include <sys/socket.h>
#endif
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#ifdef HAVE_NETINET_IN_H
#include <netinet/in.h>
#endif
#ifdef HAVE_ARPA_INET_H
#include <arpa/inet.h>
#endif
 
#include <stdio.h>
#include <time.h>   
 
static const char *pubkey = "/home/username/.ssh/id_rsa.pub";
static const char *privkey = "/home/username/.ssh/id_rsa";
static const char *username = "username";
static const char *password = "password";
static const char *loclfile = "sftp_write_nonblock.c";
static const char *sftppath = "/tmp/sftp_write_nonblock.c";
 
static int waitsocket(libssh2_socket_t 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((int)(socket_fd + 1), readfd, writefd, NULL, &timeout);
 
    return rc;
}
 
int main(int argc, char *argv[])
{
    uint32_t hostaddr;
    libssh2_socket_t sock;
    int i, auth_pw = 1;
    struct sockaddr_in sin;
    const char *fingerprint;
    int rc;
    LIBSSH2_SESSION *session = NULL;
    LIBSSH2_SFTP *sftp_session;
    LIBSSH2_SFTP_HANDLE *sftp_handle;
    FILE *local;
    char mem[1024 * 100];
    size_t nread;
    ssize_t nwritten;
    char *ptr;
    time_t start;
    libssh2_struct_stat_size total = 0;
    int duration;
 
#ifdef WIN32
    WSADATA wsadata;
 
    rc = WSAStartup(MAKEWORD(2, 0), &wsadata);
    if(rc) {
        fprintf(stderr, "WSAStartup failed with error: %d\n", rc);
        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];
    }
    if(argc > 4) {
        loclfile = argv[4];
    }
    if(argc > 5) {
        sftppath = argv[5];
    }
 
    rc = libssh2_init(0);

    if(rc) {
        fprintf(stderr, "libssh2 initialization failed (%d)\n", rc);
        return 1;
    }
 
    local = fopen(loclfile, "rb");
    if(!local) {
        fprintf(stderr, "Cannot open local file %s\n", loclfile);
        return 1;
    }
 
    /*
     * The application code is responsible for creating the socket
     * and establishing the connection
     */ 
    sock = socket(AF_INET, SOCK_STREAM, 0);
    if(sock == LIBSSH2_INVALID_SOCKET) {
        fprintf(stderr, "failed to create socket.\n");
        goto shutdown;
    }
 
    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))) {
        fprintf(stderr, "failed to connect.\n");
        goto shutdown;
    }
 
    /* Create a session instance */ 
    session = libssh2_session_init();

    if(!session) {
        fprintf(stderr, "Could not initialize SSH session.\n");
        goto shutdown;
    }
 
    /* Since we have set non-blocking, tell libssh2 we are 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);
        goto shutdown;
    }
 
    /* At this point we have not yet 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");
 
    if(auth_pw) {
        /* 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,

                                                        pubkey, privkey,
                                                        password)) ==
              LIBSSH2_ERROR_EAGAIN);
        if(rc) {
            fprintf(stderr, "Authentication by public key failed.\n");
            goto shutdown;
        }
    }
 
    fprintf(stderr, "libssh2_sftp_init().\n");

    do {
        sftp_session = libssh2_sftp_init(session);

 
        if(!sftp_session &&
           libssh2_session_last_errno(session) != LIBSSH2_ERROR_EAGAIN) {

            fprintf(stderr, "Unable to init SFTP session\n");
            goto shutdown;
        }
    } while(!sftp_session);
 
    fprintf(stderr, "libssh2_sftp_open().\n");

    /* Request a file via SFTP */ 
    do {
        sftp_handle = libssh2_sftp_open(sftp_session, sftppath,

                                        LIBSSH2_FXF_WRITE |
                                        LIBSSH2_FXF_CREAT |
                                        LIBSSH2_FXF_TRUNC,
                                        LIBSSH2_SFTP_S_IRUSR |
                                        LIBSSH2_SFTP_S_IWUSR |
                                        LIBSSH2_SFTP_S_IRGRP |
                                        LIBSSH2_SFTP_S_IROTH);
        if(!sftp_handle &&
           libssh2_session_last_errno(session) != LIBSSH2_ERROR_EAGAIN) {

            fprintf(stderr, "Unable to open file with SFTP: %ld\n",
                    libssh2_sftp_last_error(sftp_session));

            goto shutdown;
        }
    } while(!sftp_handle);
 
    fprintf(stderr, "libssh2_sftp_open() is done, now send data.\n");

    start = time(NULL);
    do {
        nread = fread(mem, 1, sizeof(mem), local);
        if(nread <= 0) {
            /* end of file */ 
            break;
        }
        ptr = mem;
 
        total += nread;
 
        do {
            /* write data in a loop until we block */ 
            while((nwritten = libssh2_sftp_write(sftp_handle, ptr, nread)) ==

                  LIBSSH2_ERROR_EAGAIN) {
                waitsocket(sock, session);
            }
            if(nwritten < 0)
                break;
            ptr += nwritten;
            nread -= nwritten;
        } while(nread);
    } while(nwritten > 0);
 
    duration = (int)(time(NULL) - start);
 
    fprintf(stderr, "%ld bytes in %d seconds makes %.1f bytes/sec\n",
            (long)total, duration, (double)total / duration);
 
    fclose(local);
    libssh2_sftp_close(sftp_handle);

    libssh2_sftp_shutdown(sftp_session);

 
shutdown:
 
    if(session) {
        while(libssh2_session_disconnect(session, "Normal Shutdown") ==

              LIBSSH2_ERROR_EAGAIN);
        libssh2_session_free(session);

    }
 
    if(sock != LIBSSH2_INVALID_SOCKET) {
        shutdown(sock, 2);
#ifdef WIN32
        closesocket(sock);
#else
        close(sock);
#endif
    }
 
    fprintf(stderr, "all done\n");
 
    libssh2_exit();

 
    return 0;
}

注:示例代码中的fingerprint可以不一定需要使用。文章来源地址https://www.toymoban.com/news/detail-745443.html

到了这里,关于LibSSH2简单入门-exec、sftp的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • CPPTest实战演示(CppTest libssh)

      CppTest是一个可移植、功能强大但简单的单元测试框架,用于处理C++中的自动化测试。重点在于可用性和可扩展性。支持多种输出格式,并且可以轻松添加新的输出格式。 CppTest下载地址Sourceforge Github地址 下面编写实际测试用例,来熟练CppTest库使用。 该接口是对libssh库

    2024年04月28日
    浏览(30)
  • eBPF 入门开发实践教程十一:在 eBPF 中使用 libbpf 开发用户态程序并跟踪 exec() 和 exit() 系统调用

    eBPF (Extended Berkeley Packet Filter) 是 Linux 内核上的一个强大的网络和性能分析工具。它允许开发者在内核运行时动态加载、更新和运行用户定义的代码。 在本教程中,我们将了解内核态和用户态的 eBPF 程序是如何协同工作的。我们还将学习如何使用原生的 libbpf 开发用户态程序,

    2024年02月07日
    浏览(47)
  • Docker 报错:OCI runtime exec failed: exec failed: unable to start container process: exec: “xxx“: exec

    前言 最近在学狂神 Docker 网络时遇到的问题,查看容器内部网络地址报错信息如上。 报错原因: 我们下载的Tomcat镜像是精简版的,运行并进入 tomcat01 容器后发现没有ip addr 和 ping 命令。 解决方式: 安装 iproute2:apt install -y iproute2 安装 ping:apt-get install -y iputils-ping 解决过程

    2024年02月02日
    浏览(50)
  • linux 之 shell脚本实现SFTP下载、上传文件、执行sftp命令

    需求方通过sftp不定时的上传一批用户(SBXDS_ACC_M_任务ID_yyyymmddHHMMSS.csv),需要我们从这些用户中找出满足条件的用户。然后把这些结果用户通过文件的形式上传到ftp。 ip1能连接hive库环境,不能连接sftp。 ip2不能连接hive库环境,能连接sftp。 ip1和ip2是共享盘,能同时访问公共目录

    2024年02月19日
    浏览(70)
  • 使用Docker 报错OCI runtime exec failed: exec failed: unable to start container process: exec: “xxx“: exe

    前些天在使用 Docker 运行一个容器时,遇到了一个报错:OCI runtime exec failed: exec failed: unable to start container process: exec: “xxx“: exec。 这个错误让我有些烦躁,因为我刚刚将容器创建好,准备执行相关命令时,却发现容器无法正常启动。在经过一番排查和尝试后,我终于找到了解

    2024年02月15日
    浏览(38)
  • nginx 代理sftp,达到访问nginx服务器就间接访问sftp服务器

    测试环境部署规划: 192.168.0.101 nginx 服务器    192.168.0.102 sftp 服务器  192.168.0.103  作为客户端去访问,这里三台机器选用centos 7.9系统,客户端可以使用window,软件访问sftp服务! 首先 1.在192.168.0.101机器上部署nginx  步骤: #安装依赖 yum install gcc pcre-devel openssl-devel  wget -y 

    2024年02月16日
    浏览(69)
  • LightDB ecpg 支持 exec sql execute ... end-exec【24.1】【oracle 兼容】

    LightDB 从24.1 版本开始支持 oracle pro*c 中执行匿名块的语法(之前可以通过do 语句执行匿名块): 因为匿名块不是SQL标准的一部分,所以此用法也不存在于SQL标准中。 需要注意的是由于内部实现方式的原因,在匿名块中不能使用 $AnonBlockStmt$ ,示例如下:

    2024年03月14日
    浏览(57)
  • OCI runtime exec failed: exec failed: unable to start container process:

    测试使用docker容器名字ping通容器与容器之间,出现 OCI runtime exec failed: exec failed: unable to start container process: exec: “ping”: executable file not found in $PATH: unknown 报错 重新测试 成功!

    2024年02月13日
    浏览(54)
  • 简单编程代码表白c语言,简单编程代码入门图标

    大家好,给大家分享一下简单编程代码表白手机版,很多人还不知道这一点。下面详细解释一下。现在让我们来看看! 大家好,本文将围绕python程序编程代码大全展开说明,python编程游戏代码是一个很多人都想弄明白的事情,想搞清楚python代码大全简单需要先了解以下几个事

    2024年02月04日
    浏览(47)
  • sftp常用命令介绍

    1. sftp 登录sftp服务器 sftp user@ip ​​​​​​ 如需要看全部命令:则使用help即可 2. pwd和lpwd 、 ls和lls 、cd和lcd 等 sftp登录之后默认操作是远程服务器,当需要操作本地时,就需要在前边加“l”,“l”代表local的意思。这样就可以同时在远程和本地实现对应的操作。 3. !comma

    2024年02月07日
    浏览(70)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包