簡體   English   中英

在Winform C#中的cmd.exe中輸入參數和密碼

[英]Input arguments and password in cmd.exe in winform C#

我必須使用cmd.exe建立ssh連接。 我在winform應用程序中使用按鈕來完成該過程。 傳遞用於ssh連接的命令后, cmd.exe會提示您輸入密碼。 除了傳遞ssh -p root@localhost命令(用於建立連接)外,如何傳遞密碼作為參數? 我必須將cmd.exe作為后台進程運行。 請幫忙。 謝謝。

我是C#的新手,也是我嘗試過的代碼之一:

    private void button2_Click(object sender, EventArgs e)
    {
         try
         {
             System.Diagnostics.Process process = new System.Diagnostics.Process();
             System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
             startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
             startInfo.FileName = "cmd.exe"; 
             startInfo.RedirectStandardInput = true;
             startInfo.UseShellExecute = false;

             using (StreamWriter sw = process.StandardInput)
             {
                if (sw.BaseStream.CanWrite)
                {
                    sw.WriteLine("/c ssh -p 2022 root@localhost"); //first comand i need to enter
                    sw.WriteLine("/c alpine");//command to be typed as password in response to 1st cmd's output
                    sw.WriteLine("/c mount.sh");//command to be typed nest in response to 2nd cmd's next output
                }
             }
        }
        catch {}
    }

您需要Start您的process

在此之前,您需要將startinfo分配給您的process

另外,如果您不想打開窗口,則應使用CreateNoWindow而不是將WindowStyle設置為Hidden

我這樣更改了您的代碼:

        ProcessStartInfo startInfo = new ProcessStartInfo();
        startInfo.FileName = "cmd.exe";
        startInfo.RedirectStandardInput = true;
        startInfo.UseShellExecute = false;
        startInfo.CreateNoWindow = true;
        Process process = new Process();
        process.StartInfo = startInfo;
        process.Start();

        using (StreamWriter sw = process.StandardInput)
        {
            if (sw.BaseStream.CanWrite)
            {
                sw.WriteLine("/c ssh -p 2022 root@localhost"); //first comand i need to enter
                sw.WriteLine("/c alpine");//command to be typed as password in response to 1st cmd's output
                sw.WriteLine("/c mount.sh");//command to be typed nest in response to 2nd cmd's next output
            }
        }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM