3、开始:
$ wget https://www.libssh2.org/snapshots/libssh2-1.9.0-20210118.tar.gz
$ tar -xvf libssh2-1.9.0-20210118.tar.gz
$ cd libssh2-1.9.0-20210118/
// 前提是系统中有了 autoconf, automake and libtool
$ autoreconf -fi
$ ./configure
$ make
工具:clion
2、cmakelist
cmake_minimum_required(VERSION 3.16)
project(ssh2_learn)
set(CMAKE_CXX_STANDARD 11)
include_directories(/usr/local/include)
link_directories(/usr/local/lib)
add_executable(${PROJECT_NAME} main.cpp)
target_link_libraries (${PROJECT_NAME} -lssh2)
3、main.cpp
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#define COPYRIGHT "jnSSH2 v1.0\nCopyright (C) 2011 Niu.Chenguang \n\n"
struct termios _saved_tio;
int tio_saved = 0;
static int _raw_mode(void)
{
int rc;
struct termios tio;
rc = tcgetattr(fileno(stdin), &tio);
if (rc != -1) {
_saved_tio = tio;
tio_saved = 1;
cfmakeraw(&tio);
rc = tcsetattr(fileno(stdin), TCSADRAIN, &tio);
}
return rc;
}
static int _normal_mode(void)
{
if (tio_saved)
return tcsetattr(fileno(stdin), TCSADRAIN, &_saved_tio);
return 0;
}
int main (int argc, char *argv[])
{
int sock = 0;
unsigned long hostaddr = 0;
short port = 22;
char *username = NULL;
char *password = NULL;
struct sockaddr_in sin;
LIBSSH2_SESSION *session;
LIBSSH2_CHANNEL *channel;
int nfds = 1;
char buf;
LIBSSH2_POLLFD *fds = NULL;
/* Struct winsize for term size */
struct winsize w_size;
struct winsize w_size_bck;
/* For select on stdin */
fd_set set;
struct timeval timeval_out;
timeval_out.tv_sec = 0;
timeval_out.tv_usec = 10;
printf(COPYRIGHT);
if (argc > 4) {
hostaddr = inet_addr(argv[1]);
port = htons(atoi(argv[2]));
username = argv[3];
password = argv[4];
}
else {
fprintf(stderr, "Usage: %s ip port user password\n", basename(argv[0]));
return -1;
}
if (libssh2_init (0) != 0) {
fprintf (stderr, "libssh2 initialization failed\n");
return -1;
}
sock = socket (AF_INET, SOCK_STREAM, 0);
sin.sin_family = AF_INET;
sin.sin_port = port;
sin.sin_addr.s_addr = hostaddr;
if (connect(sock, (struct sockaddr *) &sin, sizeof(struct sockaddr_in)) != 0) {
fprintf (stderr, "Failed to established connection!\n");
return -1;
}
/* Open a session */
session = libssh2_session_init();
if (libssh2_session_startup (session, sock) != 0) {
fprintf(stderr, "Failed Start the SSH session\n");
return -1;
}
/* Authenticate via password */
if (libssh2_userauth_password(session, username, password) != 0) {
fprintf(stderr, "Failed to authenticate\n");
close(sock);
goto ERROR;
}
/* Open a channel */
channel = libssh2_channel_open_session(session);
if ( channel == NULL ) {
fprintf(stderr, "Failed to open a new channel\n");
close(sock);
goto ERROR;
}
/* Request a PTY */
if (libssh2_channel_request_pty( channel, "xterm") != 0) {
fprintf(stderr, "Failed to request a pty\n");
close(sock);
goto ERROR;
}
/* Request a shell */
if (libssh2_channel_shell(channel) != 0) {
fprintf(stderr, "Failed to open a shell\n");
close(sock);
goto ERROR;
}
if (_raw_mode() != 0) {
fprintf(stderr, "Failed to entered in raw mode\n");
close(sock);
goto ERROR;
}
while (1) {
FD_ZERO(&set);
FD_SET(fileno(stdin),&set);
ioctl(fileno(stdin), TIOCGWINSZ, &w_size);
if ((w_size.ws_row != w_size_bck.ws_row) ||
(w_size.ws_col != w_size_bck.ws_col)) {
w_size_bck = w_size;
libssh2_channel_request_pty_size(channel, w_size.ws_col, w_size.ws_row);
}
if ((fds = static_cast<LIBSSH2_POLLFD *>(malloc(sizeof(LIBSSH2_POLLFD)))) == NULL)
break;
fds[0].type = LIBSSH2_POLLFD_CHANNEL;
fds[0].fd.channel = channel;
fds[0].events = LIBSSH2_POLLFD_POLLIN;
fds[0].revents = LIBSSH2_POLLFD_POLLIN;
if (libssh2_poll(fds, nfds, 0) >0) {
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)
libssh2_channel_write(channel, &buf, 1);
free (fds);
if (libssh2_channel_eof(channel) == 1)
break;
}
if (channel) {
libssh2_channel_free (channel);
channel = NULL;
}
_normal_mode();
libssh2_exit();
return 0;
ERROR:
libssh2_session_disconnect(session, "Session Shutdown, Thank you for playing");
libssh2_session_free(session);
return -1;
}
使用libssh2库实现支持密码参数的ssh2客户端
https://github.com/libssh2/libssh2/blob/master/example/ssh2.c
工具:clion
1、创建一个工程,并将源码中的libssh2_config.h
复制到目录中 (\libssh2-1.8.2\example\libssh2_config.h-----编译成功后libssh2_config.h.in生成的)
2、cmakelist
cmake_minimum_required(VERSION 3.16)
project(ssh2_learn)
set(CMAKE_CXX_STANDARD 11)
include_directories(/usr/local/include)
link_directories(/usr/local/lib)
add_executable(${PROJECT_NAME} main.cpp)
target_link_libraries (${PROJECT_NAME} -lssh2)
3、main.cpp
/*
*显示如何进行SSH2连接的示例。
*
*示例代码具有主机名,用户名,密码
*和复制路径的默认值,但是您可以在命令行上指定它们,例如:
*
* "ssh2 host user password [-p|-i|-k]"
*/
#include "libssh2_config.h"
#include
#include
#ifdef HAVE_WINDOWS_H
#include
#endif
#ifdef HAVE_WINSOCK2_H
#include
#endif
#ifdef HAVE_SYS_SOCKET_H
#include
#endif
#ifdef HAVE_NETINET_IN_H
#include
#endif
#ifdef HAVE_UNISTD_H
#include
#endif
#ifdef HAVE_ARPA_INET_H
#include
#endif
#include
#include
#include
#include
#include
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".
* 负责创建建立连接的socket
*/
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;
}
/*
* 创建一个会话实例并启动它:初始化一个ssh连接
*/
session = libssh2_session_init();
if(libssh2_session_handshake(session, sock)) {
fprintf(stderr, "无法建立SSH会话\n");
return -1;
}
/*至此,我们尚未通过身份验证。
* 要做的第一件事是针对我们已知的主机检查主机密钥的指纹
*/
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");
/* 检查可用的身份验证方法 */
userauthlist = libssh2_userauth_list(session, username, strlen(username));
fprintf(stderr, "身份验证方法: %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(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, "\t通过公钥验证成功.\n");
}
}
else {
fprintf(stderr, "未找到支持的身份验证方法!\n");
goto shutdown;
}
/* 请求一个shell */
channel = libssh2_channel_open_session(session);
if(!channel) {
fprintf(stderr, "无法打开会话\n");
goto shutdown;
}
/* 设置一些环境变量,并上传给服务器
*/
libssh2_channel_setenv(channel, "FOO", "bar");
/* 请求一个vanilla的终端模拟
* 有关更多选项,请参见/etc/termcap
*/
if(libssh2_channel_request_pty(channel, "vanilla")) {
fprintf(stderr, "请求pty失败\n");
goto skip_shell;
}
/* 在上一步请求的pty上开启SHELL */
if(libssh2_channel_shell(channel)) {
fprintf(stderr, "无法在分配的pty上请求shell \n");
goto shutdown;
}
/* 至此,可以交互使用shell了
* 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()
* 如果服务器发送EOF, libssh2_channel_eof() 将返回非0
* 要向服务器发送EOF,请使用: libssh2_channel_send_eof()
* 可以使用以下命令关闭通道: libssh2_channel_close()
* 可以使用以下命令释放通道: libssh2_channel_free()
*/
skip_shell:
if(channel) {
libssh2_channel_free(channel);
channel = NULL;
}
/* 通过以下方式支持其他通道类型:
* libssh2_scp_send()
* libssh2_scp_recv2()
* libssh2_channel_direct_tcpip()
*/
//ssh交互完成后,关闭会话并释放会话
shutdown:
libssh2_session_disconnect(session,
"正常关机,感谢您的参与");
libssh2_session_free(session);
//关闭sock并退出libssh2
#ifdef WIN32
closesocket(sock);
#else
close(sock);
#endif
fprintf(stderr, "全部完成!\n");
libssh2_exit();
return 0;
}
此例子为源码中的例子: https://github.com/libssh2/libssh2/blob/master/example/ssh2_exec.c
工具:clion
1、创建一个工程,并将源码中的libssh2_config.h
复制到目录中
2、cmakelist
cmake_minimum_required(VERSION 3.16)
project(ssh2_learn)
set(CMAKE_CXX_STANDARD 11)
include_directories(/usr/local/include)
link_directories(/usr/local/lib)
add_executable(${PROJECT_NAME} main.cpp)
target_link_libraries (${PROJECT_NAME} -lssh2)
3、将https://github.com/libssh2/libssh2/blob/master/example/ssh2_exec.c拷贝到main.cpp中
/*
* 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
#ifdef HAVE_WINSOCK2_H
#include
#endif
#ifdef HAVE_SYS_SOCKET_H
#include
#endif
#ifdef HAVE_NETINET_IN_H
#include
#endif
#ifdef HAVE_SYS_SELECT_H
#include
#endif
#ifdef HAVE_UNISTD_H
#include
#endif
#ifdef HAVE_ARPA_INET_H
#include
#endif
#include
#include
#include
#include
#include
#include
#include
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;
#ifdef WIN32
WSADATA wsadata;
WSAStartup(MAKEWORD(2,0), &wsadata);
#endif
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:"" );
/*****
* 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);
#ifdef WIN32
closesocket(sock);
#else
close(sock);
#endif
fprintf(stderr, "all done\n");
libssh2_exit();
return 0;
}
4、编译运行
使用libssh2库实现支持密码参数的ssh2客户端
使用 libssh2 拷贝文件到不同机器(类似 scp)
libssh