gpt4 book ai didi

c++ - LibSSH C++ 包装器 - 离开范围时的基本远程连接段错误

转载 作者:太空宇宙 更新时间:2023-11-04 13:34:19 26 4
gpt4 key购买 nike

我是 libssh 的新手,正在尝试连接到远程机器以运行一些命令。所有的连接和命令都没有错误地返回,但是程序在离开作用域时会出现段错误。我究竟做错了什么?

代码

#include <string>
#include <iostream>
using namespace std;

#define SSH_NO_CPP_EXCEPTIONS
#include <libssh/libsshpp.hpp>

int main()
{
ssh::Session session;

//Set options
session.setOption(SSH_OPTIONS_HOST, "192.168.200.101");
session.setOption( SSH_OPTIONS_USER, "user" );

//Connect to host
session.connect();

//Authenticate user
session.userauthPassword( "password" );

//Open channel
ssh::Channel channel( session );
channel.openSession();

//Do something
channel.requestExec( "ps_aux" );

//Close channel
channel.sendEof();
channel.close();

//Disconnect
session.disconnect();

return 0;
}

GDB 跟踪

Program received signal SIGSEGV, Segmentation fault.
0x00007ffff3a70a2f in ssh_channel_free () from /usr/local/lib/libssh.so.4
(gdb) where
#0 0x00007ffff3a70a2f in ssh_channel_free () from /usr/local/lib/libssh.so.4
#1 0x000000000059f436 in ssh::Channel::~Channel() ()
#2 0x000000000059e603 in main ()

最佳答案

经过一段时间的努力,我们有了一个可行的解决方案。第一个障碍是识别远程主机必须是“已知主机”。之后,对我来说,有必要在运行我的可执行文件之前获取环境。最后,我需要给它一些时间来处理 sleep( 1 )。享受吧。

#include <iostream>
using namespace std;

#include <libssh/libsshpp.hpp>

int main()
{
int port = 22;

//Can use SSH_LOG_PROTOCOL here for verbose output
int verbosity = SSH_LOG_NOLOG;

ssh::Session session;

try
{
session.setOption( SSH_OPTIONS_LOG_VERBOSITY, &verbosity );
session.setOption( SSH_OPTIONS_PORT, &port );
session.setOption( SSH_OPTIONS_USER, "user" );
session.setOption( SSH_OPTIONS_HOST, "192.168.52.101" );

session.connect();

if( session.isServerKnown() != SSH_SERVER_KNOWN_OK )
{
if( session.writeKnownhost() != SSH_OK )
{
cout << "writeKnownHost failed" << endl;
}
else
{
session.connect();
}
}

if( session.userauthPassword( "password" ) != SSH_AUTH_SUCCESS )
{
cout << "failed auth" << endl;
}

ssh::Channel channel( session );
channel.openSession();
//Source environment if necessary, run executable
channel.requestExec( "source /path/to/set_env.sh; /path/to/executable/..." );
channel.close();
channel.sendEof();

//Unfortunate brute force step, the exec call needed some time
sleep( 1 );

}
catch( ssh::SshException e )
{
std::cout << "Error during connection : ";
std::cout << e.getError() << std::endl;
}

return 0;
}

关于c++ - LibSSH C++ 包装器 - 离开范围时的基本远程连接段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30223185/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com