Advertisement
Combreal

wslFromWindows.cpp

Jun 2nd, 2018
276
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.55 KB | None | 0 0
  1. #include <windows.h>
  2. #include <shellapi.h>
  3. #include <shlobj.h>
  4. #include <iostream>
  5. #include <string>
  6. #include <fstream>
  7. #include <stdexcept>
  8. #include <stdio.h>
  9.  
  10. std::string exec(const char* cmd)
  11. {
  12.     char buffer[128];
  13.     std::string result = "";
  14.     FILE* pipe = _popen(cmd, "r");
  15.     if(!pipe) throw std::runtime_error("_popen() failed!");//popen for POSIX
  16.     try
  17.     {
  18.         while(!feof(pipe))
  19.         {
  20.             if(fgets(buffer, 128, pipe) != NULL)
  21.             {
  22.                 result += buffer;
  23.             }
  24.         }
  25.     }
  26.     catch(...)
  27.     {
  28.         _pclose(pipe);
  29.         throw;
  30.     }
  31.     _pclose(pipe);
  32.     return result;
  33. }
  34.  
  35. LPWSTR stringToLPWSTR(const std::string& instr)
  36. {
  37.     int bufferlen = ::MultiByteToWideChar(CP_ACP, 0, instr.c_str(), instr.size(), NULL, 0);
  38.     LPWSTR widestr = new WCHAR[bufferlen + 1];
  39.     ::MultiByteToWideChar(CP_ACP, 0, instr.c_str(), instr.size(), widestr, bufferlen);
  40.     widestr[bufferlen] = 0;
  41.     return widestr;
  42. }
  43.  
  44. bool fileExist(const char *fileName)
  45. {
  46.     std::ifstream infile(fileName);
  47.     return infile.good();
  48. }
  49.  
  50. int main(void)
  51. {
  52.     std::string command;
  53.     if(!fileExist("C:\\Windows\\SysWOW64\\bash.exe"))
  54.     {
  55.         ShellExecuteW(NULL, L"open", L"cmd.exe", L" /C mklink C:\\Windows\\SysWOW64\\bash.exe C:\\Windows\\System32\\bash.exe", NULL, SW_HIDE);
  56.     }
  57.     //command = " /C C:\\Windows\\SysWOW64\\bash.exe -c ls > test.txt";
  58.     //ShellExecuteW(NULL, L"open", L"cmd.exe", stringToLPWSTR(command), NULL, SW_HIDE);
  59.     std::cout<<exec("cmd.exe /C C:\\Windows\\SysWOW64\\bash.exe -c ls")<<std::endl;
  60.     system("pause");
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement