/**
* CSSHClient.h
* @file 说明信息..
* DATE February 13 2015
*
* @author Ming_zhang
*/ #ifndef _CSSHCLIENT_H_
#define _CSSHCLIENT_H_ /***********************Global Variable Declare***************/
//#define -1; ///< 定义 的宏为0。
////////////////////////////////////////////////////////////// /************************INCLUDE FILES*************************/
#include <string>
extern "C"
{
#include "libssh2.h"
};
using namespace std;
/////////////////////////////////////////////////////////////// /**
* @brief SSH2协议进行远程登录
*
*/
class CSSHClient
{
public: // Constructors & Destructor
CSSHClient();
virtual ~CSSHClient();
static int Init();
static int ClearUp();
int Login(string sIp,int nPort,string sUser,string sPasswd);
int Logout();
int ExecuteCommand(string sCommand);
private:
int WaitSocket(int socket_fd, LIBSSH2_SESSION *session);
private:
SOCKET m_nSSHSocket;
LIBSSH2_SESSION *m_hSSHSession ;
LIBSSH2_CHANNEL *m_hSSHChannel ; }; #endif
/**
* CSSHClient.cpp
* @file 说明信息..
* DATE February 13 2015
*
* @author Ming_zhang
*/ /************************INCLUDE FILES*************************/
#include "stdafx.h"
#include "CSSHClient.h" #include <libssh2.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 #include <time.h>
#include <sys/types.h>
#include <stdlib.h>
#include <fcntl.h>
#include <errno.h>
#include <stdio.h>
#include <ctype.h> #include <stdexcept>
using namespace std; #pragma comment(lib,"libssh2.lib") /////////////////////////////////////////////////////////////// CSSHClient::CSSHClient():m_nSSHSocket(INVALID_SOCKET)
,m_hSSHSession(0)
,m_hSSHChannel(0)
{
} CSSHClient::~CSSHClient()
{
} int CSSHClient::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 CSSHClient::Login(string sIp,int nPort,string sUser,string sPasswd)
{
ENTER_FUN(m_hSSHChannel); if(m_nSSHSocket!=INVALID_SOCKET)
{
WLE("<%s>Error: m_nSSHSocket=[%d] can't relogin\n",_FUN_,m_nSSHSocket);
return RET_FAIL;
}
string commandline ="ls /root/";
char *exitsignal=(char *)"none";
const char *fingerprint;
int exitcode;
#ifdef WIN32
WSADATA wsadata;
WSAStartup(MAKEWORD(2,0), &wsadata);
#endif
struct sockaddr_in sin;
int bytecount = 0;
size_t len;
LIBSSH2_KNOWNHOSTS *nh;
int type;
int rc = 0;
//建立SOCKET 连接
m_nSSHSocket = socket(AF_INET, SOCK_STREAM, 0);
memset(&sin, 0, sizeof(struct sockaddr_in));
sin.sin_family = AF_INET;
sin.sin_port = htons(nPort);
sin.sin_addr.S_un.S_addr = inet_addr(sIp.c_str());
try
{ int nRet = connect(m_nSSHSocket, (struct sockaddr*)(&sin),sizeof(struct sockaddr_in));
if ( nRet!= 0)
{
WLI("<%s>Error: connect==[%d]\n ",_FUN_);
throw logic_error("Fail connect");
} m_hSSHSession = libssh2_session_init();
if (!m_hSSHSession)
{
WLI("<%s>Error: libssh2_session_init = [%d]\n",_FUN_,m_hSSHSession);
throw logic_error("Fail libssh2_session_init");
} /* ... start it up. This will trade welcome banners, exchange keys,
* and setup crypto, compression, and MAC layers
*/
while ((rc = libssh2_session_handshake(m_hSSHSession, m_nSSHSocket)) ==LIBSSH2_ERROR_EAGAIN); if (rc)
{
WLI("<%s>Error: libssh2_session_handshake = [%d]\n",_FUN_,rc);
throw logic_error("Fail libssh2_session_handshake");
}
nh = libssh2_knownhost_init(m_hSSHSession);
if(!nh)
{
WLI("<%s>Error: libssh2_knownhost_init = [%d]\n",_FUN_,nh);
throw logic_error("Fail libssh2_knownhost_init");
}
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(m_hSSHSession, &len, &type);
if(fingerprint)
{
struct libssh2_knownhost *host;
#if LIBSSH2_VERSION_NUM >= 0x010206
/* introduced in 1.2.6 */
int check = libssh2_knownhost_checkp(nh, sIp.c_str(), 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
WLI( "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 */
WLI("<%s>Error: libssh2_session_hostkey = [%d]\n",_FUN_,fingerprint);
throw logic_error("Fail libssh2_session_hostkey");
}
libssh2_knownhost_free(nh); if ( strlen(sPasswd.c_str()) != 0 )
{
/* We could authenticate via password */
while ((rc = libssh2_userauth_password(m_hSSHSession, sUser.c_str(), sPasswd.c_str())) ==LIBSSH2_ERROR_EAGAIN); if (rc)
{
WLI("<%s>Error: Authentication by password failed.\n",_FUN_,fingerprint);
throw logic_error("Fail libssh2_userauth_password");
}
}
else
{
/* Or by public key */
while ((rc = libssh2_userauth_publickey_fromfile(m_hSSHSession, sUser.c_str(),
"/home/user/"
".ssh/id_rsa.pub",
"/home/user/"
".ssh/id_rsa",
sPasswd.c_str())) ==
LIBSSH2_ERROR_EAGAIN);
if (rc)
{
WLI("<%s>Error: Authentication by public key failed.\n",_FUN_,fingerprint);
throw logic_error("Fail libssh2_userauth_password"); }
}
}
catch (logic_error &e)
{
WLE("<%s>Error: Desc[%s]\n",_FUN_,e.what()); return RET_FAIL;
}
return RET_OK;
} int CSSHClient::Logout()
{
char *exitsignal=(char *)"none";
int exitcode= 0 ;
int rc = 0; if(m_hSSHSession!=0)
{
libssh2_session_disconnect(m_hSSHSession,"Normal Shutdown, Thank you for playing");
libssh2_session_free(m_hSSHSession);
m_hSSHSession = NULL;
} if(m_nSSHSocket!=INVALID_SOCKET)
{
#ifdef WIN32
closesocket(m_nSSHSocket);
#else
close(m_nSSHSocket);
#endif
m_nSSHSocket = INVALID_SOCKET;
} return RET_OK;
}
int CSSHClient::ExecuteCommand(string commandline)
{
ENTER_FUN(CSSHClient::ExecuteCommand); if(m_hSSHSession==0)
{
WLE("<%s>Error: m_hSSHSession==0 commandline[%s]\n",_FUN_,commandline.c_str());
return RET_FAIL;
}
char *exitsignal=(char *)"none";
/* Exec non-blocking on the remove host */
while( (m_hSSHChannel = libssh2_channel_open_session(m_hSSHSession)) == NULL &&libssh2_session_last_error(m_hSSHSession,NULL,NULL,0) ==LIBSSH2_ERROR_EAGAIN )
{
WaitSocket(m_nSSHSocket, m_hSSHSession);
}
if( m_hSSHChannel == NULL )
{
WLI("<%s>Error: libssh2_channel_open_session [%d].\n",_FUN_,m_hSSHChannel);
//throw logic_error("Fail libssh2_channel_open_session");
return RET_FAIL;
} int bytecount = 0;
int rc = 0;
int exitcode = 0;
while( (rc = libssh2_channel_exec(m_hSSHChannel, commandline.c_str()))==LIBSSH2_ERROR_EAGAIN )
{
WaitSocket(m_nSSHSocket, m_hSSHSession);
}
for( ;; )
{
/* loop until we block */
int rc;
do
{
char buffer[0x4000];
rc = libssh2_channel_read( m_hSSHChannel, buffer, sizeof(buffer) );
if( rc > 0 )
{
int i;
bytecount += rc;
TRACE("We read:\n");
for( i=0; i < rc; ++i )
TRACE("%c",buffer[i]);
TRACE("\n");
}
else {
if( rc != LIBSSH2_ERROR_EAGAIN )
TRACE( "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(m_nSSHSocket, m_hSSHSession);
}
else
break;
} if(m_hSSHChannel!=0)
{//释放 Channel
while( (rc = libssh2_channel_close(m_hSSHChannel)) == LIBSSH2_ERROR_EAGAIN )WaitSocket(m_nSSHSocket, m_hSSHSession);
if( rc == 0 )
{
exitcode = libssh2_channel_get_exit_status( m_hSSHChannel );
libssh2_channel_get_exit_signal(m_hSSHChannel, &exitsignal,NULL, NULL, NULL, NULL, NULL);
}
if(m_hSSHChannel!=0)
libssh2_channel_free(m_hSSHChannel);
m_hSSHChannel = 0;
} if( rc != 0 )
{
WLI("<%s>Error: libssh2_channel_exec [%d].\n",_FUN_,rc);
return RET_FAIL;
} WLE("<%s> Info:Success sCommand[%s]\n",_FUN_,commandline.c_str());
return RET_OK;
} int CSSHClient::Init()
{
ENTER_FUN(CSSHClient::Init);
int rc = libssh2_init (0);
if (rc != 0)
{
WLI("<%s>Error: libssh2_init = [%d]\n",_FUN_,rc);
return RET_FAIL;
}
return RET_OK;
} int CSSHClient::ClearUp()
{
libssh2_exit();
return RET_OK;
}

对 linux server进行远程运行命令。能够通过 libss2 库进行。以下是 使用这个库的类的定义
</pre><pre name="code" class="cpp">


libssh2进行远程运行LINUX命令的更多相关文章

  1. php 运行linux命令 与 linux下命令行执行php

    1.php运行linux命令 exec函数:string exec(string command, string [array], int [return_var]);  执行函数后不输出结果,返回最 ...

  2. Windows下运行Linux命令

    安装Gow软件,Gow-0.7.0.exe,这样就可以在Windows命令行运行Linux命令,比如通过scp把Windows下的文件拷贝到Linux下. 直接运行安装,不会生成任何客户端,直接使用W ...

  3. 利用java实现可远程执行linux命令的小工具

    在linux的脚本中,如果不对机器做其他的处理,不能实现在linux的机器上执行命令.为了解决这个问题,写了个小工具来解决这个问题. 后面的代码是利用java实现的可远程执行linux命令的小工具,代 ...

  4. java运行Linux命令

    <%@ page language="java" import="java.util.*,java.io.*" pageEncoding="UT ...

  5. 在windows cgywinportable上,通过运行linux命令,批量改动文件名。

    在windows cgywinportable上.通过运行linux命令.批量改动文件名. 实例:将当前文件夹下的全部文件名称加上.sql find ./ -type f -exec mv {}  ' ...

  6. 在Windows上远程运行Linux程序

    1.在Windows主机上安装X Server软件,如Cygwin带的XWin Server 2.在Windows主机上启动X服务器,并将Linux主机设为允许访问该Windows主机上的X服务器. ...

  7. 如何远程运行PowerShell命令?

    首先, 被remote运行PowerShell的windows必须已经join了domain. 其次, 该Windows的PowerShell必须开启对remote command的接受, 运行下面的 ...

  8. 如何在windows下运行Linux命令?(转载)

    在windows上可以运行或使用linux下面的命令吗?可以,小编今天就来分享怎么样让Windows支持Linux命令,做这些安装和设置后,就可以非常方便的在windows系统中使用linux下面的命 ...

  9. 在window的cmd窗口下运行linux命令

    之前看很多视频老师都是用Linux命令操作命令框,感觉很方便,自己在cmd窗口试了一下,所有这些命令都提示不是内部或外部命令,后来发现了windows还有一个powershell命令行工具,用起来似乎 ...

随机推荐

  1. Linux学习,部署django项目到服务器,及安装python,uwsgi等

    开启网络 vi /etc/sysconfig/network-script/ifcfg-eth0 onboot=yes 退出保存 service network restart ping www.ba ...

  2. Vue+ElementUI: 手把手教你做一个audio组件

    目的 本项目的目的是教你如何实现一个简单的音乐播放器(这并不难) 本项目并不是一个可以用于生产环境的element播放器,所以并没有考虑太多的兼容性问题 本项目不是ElementUI的一个音频插件,只 ...

  3. CF17E Palisection(回文树)

    题意翻译 给定一个长度为n的小写字母串.问你有多少对相交的回文子 串(包含也算相交) . 输入格式 第一行是字符串长度n(1<=n<=2*10^6),第二行字符串 输出格式 相交的回文子串 ...

  4. 我的投资案例(3)-看好互联网和金融两大朝阳行业,参投入股垂直金融招聘平台"职业梦CareerDream.cn"

     作为一名喜欢读书,关注中国和欧美国家发展的知识青年,  同时作为一名程序员和对金融投资感兴趣的业余爱好者,本人一直看好  以IT互联网为代表的科技和以投资VC为代表的金融,这2大朝阳行业的发展.   ...

  5. linux命令su与su-的差别

    su命令和su -命令最大的本质差别就是: su仅仅是切换了root身份.但Shell环境仍然是普通用户的Shell. 而su -连用户和Shell环境一起切换成root身份了. 仅仅有切换了Shel ...

  6. 用motion实现家庭视频监控

    需求?当然不是为了艳照.你们这些猥琐的人类! 毕竟家里总会有没人的时候,出门走到半路忘记煤气灶是不是关了,还得回去看看. 在这个科技以人为本的时代,当然应该是拿出智能手机联网看看啦.还有万一有人闯空门 ...

  7. android selector设置button点击效果(具体)以及常见问题

    button的点击效果学习起来其实比較easy,此点对开发人员来说也是使用的比較频繁的一个知识点,与它相关的还有编辑框的获取焦点时改变背景颜色.选择button选择时改变字体颜色等等.这些其实都是用到 ...

  8. 17. IntelliJ IDEA + Maven创建Java Web项目

    转自:https://www.cnblogs.com/Terry-Wu/p/8006475.html 1. Maven简介 相对于传统的项目,Maven 下管理和构建的项目真的非常好用和简单,所以这里 ...

  9. BZOJ 1012 单调队列+二分

    思路: 维护一个单减的序列 序号是单增的 每回二分查找第一个比询问的大的值 我手懒 用得lower_bound //By SiriusRen #include <cstdio> #incl ...

  10. SQLHelper--java类

    package richard; import java.beans.Statement; import java.sql.Connection; import java.sql.DriverMana ...