例如,我想打开一个会话和一个频道,然后执行不同的命令。我有 InitializeSSHSession 和 Initialize SSH 通道方法可以在下面看到。
void Computer::InitializeSSHSession()
{
ssh_session remoteSSHSession = ssh_new();
if ( remoteSSHSession )
{
QString password = this->GetPassword();
QString remoteIP = this->GetIP();
QString userName = this->GetUserNameW();
ssh_options_set(remoteSSHSession, SSH_OPTIONS_HOST, remoteIP.toStdString().c_str());
ssh_options_set(remoteSSHSession, SSH_OPTIONS_LOG_VERBOSITY, &sessionVerbosity);
ssh_options_set(remoteSSHSession, SSH_OPTIONS_PORT, &sessionPort);
ssh_options_set(remoteSSHSession, SSH_OPTIONS_USER, userName.toStdString().c_str());
int remoteConnection = ssh_connect(remoteSSHSession);
if ( remoteConnection == SSH_OK )
{
int authenticateControl = ssh_userauth_password(remoteSSHSession, NULL, password.toStdString().c_str());
if ( authenticateControl == SSH_AUTH_SUCCESS )
{
InitializeSSHChannel(remoteSSHSession);
}
else
{
remoteSSHSession = NULL;
}
}
else
{
remoteSSHSession = NULL;
}
}
else
{
remoteSSHChannel = NULL;
}
}
void Computer::InitializeSSHChannel(ssh_session remoteSSHSession)
{
remoteSSHChannel = ssh_channel_new(remoteSSHSession);
if ( remoteSSHChannel )
{
int channelControl = ssh_channel_open_session(remoteSSHChannel);
if ( channelControl != SSH_OK )
{
EventLogger::LogMessage(true, "SSH channel sesssion failed!");
ssh_channel_free(remoteSSHChannel);
}
}
}
总的来说,我正在初始化会话并获得这样的频道:
InitializeSSHSession();
ssh_channel channel = GetSSHChannel();
接着
int rc = ssh_channel_request_exec(channel, "ls -l");
没关系,它可以正确执行,但是当我想执行另一个命令时它没有执行,我应该返回进程的开始,首先初始化会话并再次获取通道。
这不是每个命令的好解决方案。是否可以在初始化会话后执行此操作,而不是为每个命令一次又一次地使用它?