以下是包含必备头文件
#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 WIN32WSADATA wsadata;int err;err = WSAStartup(MAKEWORD(2, 0), &wsadata);if(err != 0) {fprintf(stderr, "WSAStartup failed with error: %d\n", err);return 1;}
#endifif(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 WIN32closesocket(sock);
#elseclose(sock);
#endiffprintf(stderr, "all done!\n");libssh2_exit();return 0;
}

linux libssh2 实例相关推荐

  1. Alibaba Cloud Linux 2.1903 LTS 64位服务器yum源下载404,Alibaba Cloud Linux 2实例中使用docker-ce、epel等YUM源安装软件失败

    [Alibaba Cloud Linux 2.1903 LTS 64位]服务器yum源下载404 failure: repodata/repomd.xml from docker-ce-stable: ...

  2. Linux:进程实例信息(/proc)

    https://blog.csdn.net/test1280/article/details/73632333 Linux:进程实例信息(/proc) 问几个问题: 1.怎么知道一个进程对应哪个可执行 ...

  3. linux下dds软件,【数据库】Linux 单实例环境下实现Oracle数据库和DDS软件的开机自动重启...

    Linux 单实例环境下实现Oracle数据库和DDS软件的开机自动重启1.修改/etc/oratab# vi /etc/orataboradb:/opt/ora10/product/10.2 首页 ...

  4. 操作系统笔记——Linux系统实例分析、Windows系统实例分析

    文章目录 传送门 Linux进程管理 Linux进程组成 Linux进程链表 Linux进程控制 用户进程创建与撤销 0,1,2号进程 Linux进程切换 Linux进程调度 内核同步 Linux储存 ...

  5. linux服务器关机后计划任务还能进行,宝塔面板计划任务定时安全重启Linux服务器实例操作...

    这篇文章主要为大家详细介绍了宝塔面板计划任务定时安全重启Linux服务器实例操作,具有一定的参考价值,感兴趣的小伙伴们可以参考一下,有需要的朋友可以收藏方便以后借鉴. 宝塔面板有很多"神&q ...

  6. Python 技术篇-用paramiko库实现winodws本地文件上传至linux服务器实例演示

    利用 paramiko 库可以实现 linux 服务器的管理. 如果想管理 windows 服务器的话就麻烦一点了,我用 flask 服务实现的,可以看我的这篇文章: Python 技术篇-用 fla ...

  7. linux程序实例获取,Linux命令备忘实例(4)——获取内容

    Linux中的所有内容都是以文件的方式表示的,会有很多需求需要我们获取文件的内容,查看部分或者全部内容.当然最直接方式就是使用编辑器打开文件查看,比如vim.vi.emacs等.这里主要关注的是she ...

  8. linux数据库实例开机启动不了,linux下Oracle数据库实例开机自启动设置

    linux下数据库实例开机自启动设置 1.改动/oratab [root@org54 ~]# vi/etc/oratab     --把N改为Y,例如以下提示 # This file is used ...

  9. arm嵌入式linux应用实例开发pdf,零点起步——ARM嵌入式Linux应用开发入门一书的源代码...

    代码片段和文件信息 属性            大小     日期    时间   名称 ----------- ---------  ---------- -----  ---- 文件      2 ...

最新文章

  1. 不看你都不知道,原来码农的诞生这么不容易
  2. Git之提交项目到远程github
  3. AndroidStudio权威教程 AS添加第三方库的6种方式(Jar module so等)
  4. Struts2框架学习Action命名空间创建方式
  5. php 开启 pathinfo,nginx下PHP开启pathinfo模式
  6. gradient渐变IE兼容处理
  7. jquery for循环_前端基础入门五(掌握jQuery的常用api,实现动态效果)
  8. 10个优质的Java练手项目
  9. 教你一键式下载iOS旧版APP(2021年有效)
  10. 安装Hadoop3.2.1(很多坑)
  11. H264码流中SPS的获取
  12. 微信小程序:高德地图在小程序中的实践(含静态地图)
  13. 真无线蓝牙耳机哪个品牌好?2023年真无线降噪耳机盘点
  14. Link context for 0x01 connection handle could not be fetched.
  15. 音频怎么转换文件格式?教你轻松转换
  16. TexturePacker批处理python
  17. 数据与模型混合驱动的区域综合能源系统双层优化调度决策方法——阅读理解
  18. HTML5与CSS3的新特性。
  19. 智能优化算法之松鼠算法(Squirrel search algorithm)
  20. 阿尔法ct_X光、CT、B超、核磁共振、核医学到底有什么不同?

热门文章

  1. Linux 操作系统原理 — 网络 I/O 虚拟化
  2. Golang 编程 — Go Micro 微服务框架
  3. python-简单测试wsgi
  4. JAVA微信APP支付接口整合
  5. 苹果回应中情局攻击事件:许多漏洞已经得到解决
  6. Uva 11396 爪分解
  7. 动静结合学内核:linux idle进程和init进程浅析
  8. Leetcode: Reverse Linked List II
  9. javascript简单应用
  10. 团队Blog功能改进