【发布时间】:2020-12-19 06:36:09
【问题描述】:
我有这个功能,可以通过ssh连接到远程系统:
std::string _ErrMsg;
int _RetVal = 0;
MyException errMsg;
int port = 22;
try
{
if (my_ssh_session == NULL) {
std::cout << "Error creating ssh session" << std::endl;
throw MyException("Error in creating session");
_RetVal = -1;
return _RetVal;
}
ssh_options_set(my_ssh_session, SSH_OPTIONS_HOST, (const void*)(authentication.ip));
ssh_options_set(my_ssh_session, SSH_OPTIONS_USER, (const void*)(authentication.userName));
ssh_options_set(my_ssh_session, SSH_OPTIONS_PORT, &port);
int rc = ssh_connect(my_ssh_session);
if (rc != SSH_OK) {
std::cout << "Error with connecting" << std::endl;
_ErrMsg = ssh_get_error(my_ssh_session);
ssh_free(my_ssh_session);
_RetVal = -2;
throw MyException(_ErrMsg);
}
rc = ssh_userauth_password(my_ssh_session, NULL, (const char*)(authentication.pw));
if (rc != SSH_AUTH_SUCCESS) {
std::cout << "Authentication failed " << ssh_get_error(my_ssh_session) << std::endl;
_ErrMsg = ssh_get_error(my_ssh_session);
ssh_disconnect(my_ssh_session);
ssh_free(my_ssh_session);
_RetVal = -3;
throw MyException(_ErrMsg);
}
}
catch (MyException& e)
{
throw e;
}
return _RetVal;
还有这个通过ssh channel执行命令的函数:
std::string ssh::exec_ssh_command(char* command)
{
std::string receive = "";
std::string err;
int rc, nbytes;
char buffer[2000];
MyException errMsg;
try {
my_ssh_session = ssh_new();
ssh_channel channel = ssh_channel_new(my_ssh_session);
if (channel == NULL)
{
receive = "Channel allocation failed.";
throw MyException(receive);
}
rc = ssh_channel_open_session(channel);
if (rc != SSH_OK)
{
free_channel(channel);
receive = "Opening session channel failed.";
throw MyException(receive);
}
rc = ssh_channel_request_exec(channel, command);
if (rc != SSH_OK) {
receive = "Channel's request executing failed.";
free_channel(channel);
throw MyException(receive);
}
nbytes = ssh_channel_read(channel, buffer, sizeof(buffer), 0);
receive = buffer;
if (nbytes > 0)
{
receive.erase(nbytes - 1, 2000);
}
else
{
receive = "Error in command: not found or wrong syntax";
throw MyException(receive);
}
if (nbytes < 0)
{
receive = "Error in reading data from channel ";
throw MyException(receive);
}
free_channel(channel);
free_session(my_ssh_session);
}
catch (MyException& err)
{
throw err;
}
return receive;
}
当一个错误的命令被发送到这个函数时,我想抛出一个异常。例如,如果我发送此命令:ls /sys/class/net | se -n - 1p。如果我在终端上运行这个命令,我得到这个错误:se: command not found。当我像这样运行它时:ls /sys/class/net | sed -n -s 1p | grep 'something irrelevant',它什么也没有。它以两种方式都没有提供任何输出。 nbytes 将是0。有什么办法可以接受se: command not found ??
【问题讨论】:
-
不相关,考虑使用带有自定义删除功能的
std::unique_ptr以防止泄露您的 ssh_session 和通道。
标签: c++ linux exception libssh