2016-11-25 47 views
1

我正在嘗試編寫一個C#控制檯應用程序,該應用程序將通過cmd啓動runas.exe,然後以該用戶身份運行另一個應用程序。我採取了下面列出的建議之一(並添加了一點),因爲它似乎是最有前途的。在控制檯應用程序中編寫cmd命令

Process cmd = new Process(); 
ProcessStartInfo startinfo = new ProcessStartInfo("cmd.exe", @"/K C:\Windows\System32\runas.exe /noprofile /user:DOMAIN\USER'c:\windows\system32\notepad.exe\'") 
{ 
    RedirectStandardInput = true, 
    UseShellExecute = false 
}; 
cmd.StartInfo = startinfo; 
cmd.Start(); 
StreamWriter stdInputWriter = cmd.StandardInput; 
stdInputWriter.Write("PASSWORD"); 
cmd.WaitForExit(); 

當我啓動它要求輸入密碼前的命令本身造成那裏是一個錯誤與runas.exe

enter image description here

的應用程序,我敢肯定UseShellExecute = false導致的錯誤,但如果沒有它,StreamWriter不能正常工作,所以我不知道該怎麼辦。

+0

您是否試過: stdInputWriter.WriteLine(「password」); ? 也許你只是沒有確認輸入? –

+1

@JakubSzułakiewicz但我仍然需要聲明streamwriter,如果我不用'Process.StandardInput'來做,我應該怎樣聲明它? – BlueBarren

回答

0

我發現在following post的溶液。我不得不放棄我正在使用的大部分結構,但現在我可以使用下面列出的代碼成功運行記事本作爲我想要的用戶。

var pass = new SecureString(); 
pass.AppendChar('p'); 
pass.AppendChar('a'); 
pass.AppendChar('s'); 
pass.AppendChar('s'); 
pass.AppendChar('w'); 
pass.AppendChar('o'); 
pass.AppendChar('r'); 
pass.AppendChar('d'); 
var runFileAsUser = new ProcessStartInfo 
{ 
    FileName = "notepad", 
    UserName = "username", 
    Domain = "domain", 
    Password = pass, 
    UseShellExecute = false, 
    RedirectStandardOutput = true, 
    RedirectStandardError = true 
}; 
Process.Start(runFileAsUser); 
2

的/ C參數運行comman線和終止,所以你看不到的結果(這是一個大C),看她:http://ss64.com/nt/cmd.html

嘗試使用「/ K」。 我用你的命令做了它,我在另一個窗口看到結果。

ProcessStartInfo startInfo = new ProcessStartInfo("cmd", "/K ping PC -t"); 
Process.Start(startInfo); 
+0

好東西!這讓我運行命令,現在看到他們,我必須弄清楚如何輸入一個C#變量到CMD – BlueBarren

+0

@BlueBarren謝謝,你甚至可以標記答案爲解決方案:) –

+0

以及我的問題還沒有解決:P – BlueBarren

1

你的過程應該有RedirectStandardInput =真

var p = new Process(); 
var startinfo = new ProcessStartInfo("cmd.exe", @"/C C:\temp\input.bat") 
{ 
    RedirectStandardInput = true, 
    UseShellExecute = false 
}; 
p.StartInfo = startinfo; 
p.Start(); 
StreamWriter stdInputWriter = p.StandardInput;   
stdInputWriter.Write("y");  

該程序啓動input.bat,然後發送y到它的標準輸入值。

爲了完整起見,input.bat例如:

set /p input=text?: 
echo %input% 
+0

我使用'「/ K」'所以我可以看到cmd窗口正在做什麼,但它仍然關閉,爲什麼?它在工作之前。無論哪種方式,我不知道你的方法正在工作,因爲我想要的命令是啓動記事本,但它不會出現。 – BlueBarren

+0

在我的環境中運行帶有/ K和/ C的記事本是否會在路徑中顯示記事本? – Ofiris

+0

路徑是'c:\ windows \ system32 \ notepad.exe \'我知道它的作品,因爲當我試圖@MarksimSimkin的回答cmd命令工作正常 – BlueBarren

相關問題