程序調用plink.exe發送命令設置路由

    項目要求程序調用cmd.exe然後執行plink.exe登錄到路由器,然後執行路由器的命令對其進行設置。本體和cmd.exe交換數據,發送命令到cmd.exe然後從其獲取執行的結果進行判斷。代碼如下:

初始化代碼:

BOOL CMotorolaSetDlg::OpenCMDProcess()
{
    SECURITY_ATTRIBUTES sa;
    STARTUPINFO si;
    TCHAR cmdLine[256] = {0};
    TCHAR wcRcvBuff[1024] = {0};
    PROCESS_INFORMATION ProcessInformation;

    sa.nLength=sizeof(sa);
    sa.lpSecurityDescriptor=0;
    sa.bInheritHandle=true;

    if(!CreatePipe(&(this->m_hReadPipe1),&(this->m_hWritePipe1),&sa,0))
    {
        return FALSE;
    }
    if(!CreatePipe(&(this->m_hReadPipe2),&(this->m_hWritePipe2),&sa,0))
    {
        return FALSE;
    }

    ZeroMemory(&si,sizeof(si));
    GetStartupInfo(&si);
    si.dwFlags = STARTF_USESHOWWINDOW|STARTF_USESTDHANDLES;
    si.wShowWindow = SW_HIDE;
    si.hStdInput = this->m_hReadPipe2;
    si.hStdOutput = si.hStdError = this->m_hWritePipe1;

    GetSystemDirectory(cmdLine,sizeof(cmdLine));
    _tcscat(cmdLine, _T("\\cmd.exe"));
    if(CreateProcess(cmdLine,NULL,NULL,NULL,TRUE,0,NULL,NULL,&si,&ProcessInformation) == 0)
    {
        return FALSE;
    }

    return TRUE;

}

發送命令到cmd.exe的代碼:

BOOL CMotorolaSetDlg::SndCmdToPipe(CString csCmd)
{
    BOOL bRet = FALSE;
    unsigned long ulBytesRead = 0;
    char* pcCmd = NULL;

    pcCmd = CStringToChar(csCmd);

    bRet = WriteFile(this->m_hWritePipe2, pcCmd,csCmd.GetLength()+1,&ulBytesRead,0);

    if(pcCmd != NULL)
    {
        delete pcCmd;
    }

    return bRet;
}

從cmd.exe接收反饋的代碼:

BOOL CMotorolaSetDlg::RcvDataFromPipe(TCHAR* pwcBuff, DWORD dwLen)
{
    BOOL bRet = FALSE;
    unsigned long ulBytesRead = 0;
    
    if(dwLen > sizeof(pwcBuff) && pwcBuff == NULL)
    {
        bRet = FALSE;
    }
    else
    {
        memset(pwcBuff, 0, dwLen);
        bRet = PeekNamedPipe(this->m_hReadPipe1,pwcBuff,dwLen,&ulBytesRead,0,0);
        if(bRet)    
        {
            bRet = ReadFile(this->m_hReadPipe1,pwcBuff,dwLen,&ulBytesRead,0);
        }
        else
        {
            bRet = FALSE;
        }
    }


    return bRet;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章