例如,我想打开一个会话和一个通道,然后执行严格的不同命令。我有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");
它可以正确执行但是当我想执行另一个命令它不执行时,我应该返回进程的开始首先初始化会话并再次获取通道。
对于每个命令都不是好的解决方案。 一旦初始化会话而不是一次又一次地为每个命令使用它,是否可以这样做?