当前位置:   article > 正文

基于openwrt和libssh2实现ssh的远程登录_openwrt ssh

openwrt ssh

libssh2的支持

openwrt本身带有libssh和libssh2两种三方库。我们需要修改编译使其参与编译
  • 1
./scripts/feeds update -a
./scripts/feeds install -a
  • 1
  • 2

执行make menuconfig操作,勾选你想要的三方库
在这里插入图片描述

ssh服务器的连接

这里需要注意的主要就是makefile里面记得添加ssh2的依赖,要不编译或者运行会出问题,
其他想做的操作,替换新建文件的逻辑就可以

#include "rk_stick.h"


int main(int argc, char **argv)
{
    LIBSSH2_SESSION *session = NULL;
    const char *hostname = "192.168.180.8";
    const char *username = "toybrick";
    const char *password = "toybrick";
    int rc = -1, sock;

    // 初始化libssh2库
    rc = libssh2_init(0);
    if (rc != 0) {
        fprintf(stderr, "Failed to initialize libssh2\n");
        return -1;
    }

    // 创建套接字
    sock = socket(AF_INET, SOCK_STREAM, 0);
    if (sock == -1) {
        fprintf(stderr, "Failed to create socket\n");
        return -1;
    }

    // 连接到远程主机
    struct sockaddr_in sin;
    sin.sin_family = AF_INET;
    sin.sin_port = htons(22);
    sin.sin_addr.s_addr = inet_addr(hostname);

    if (connect(sock, (struct sockaddr*)(&sin), sizeof(struct sockaddr_in)) != 0) {
        fprintf(stderr, "Failed to connect to remote host\n");
        close(sock);
        return -1;
    }

    // 创建SSH会话
    session = libssh2_session_init();
    if (!session) {
        fprintf(stderr, "Failed to create SSH session\n");
        return -1;
    }

    // 连接到SSH服务器
    rc = libssh2_session_startup(session, sock);
    if (rc) {
        fprintf(stderr, "Failed to establish SSH session\n");
        libssh2_session_free(session);
        return -1;
    }

    // 认证
    rc = libssh2_userauth_password(session, username, password);
    if (rc) {
        fprintf(stderr, "Authentication failed\n");
        libssh2_session_free(session);
        return -1;
    }

    // 执行远程命令
    LIBSSH2_CHANNEL *channel = libssh2_channel_open_session(session);
    if (channel) {
        libssh2_channel_exec(channel, "touch /tmp/test.config");
        libssh2_channel_close(channel);
        libssh2_channel_free(channel);
    }

    // 关闭会话
    libssh2_session_disconnect(session, "Bye bye, thanks for playing");
    libssh2_session_free(session);

    // 关闭libssh2库
    libssh2_exit();

    return 0;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77

结果验证

在服务器的tmp目录下查看是否有test.config文件
在这里插入图片描述

声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop】
推荐阅读
相关标签
  

闽ICP备14008679号