C#如何使用Process和StandardInputWriter运行cygwin scp并输入密码?

时间:2011-09-22 17:33:22

标签: c# cygwin scp

使用此代码,我看到登录窗口提示输入密码,但我似乎无法将密码写入shell窗口。

        Process scp = new Process();
        scp.StartInfo.FileName = @"c:\cygwin\bin\scp";
        scp.StartInfo.Arguments = "/cygdrive/c" + path + " " + username + "@" + ServerName + ":/cygdrive/c/Temp/.";
        scp.StartInfo.UseShellExecute = false;
        scp.StartInfo.RedirectStandardOutput = true;
        scp.StartInfo.RedirectStandardError = true;
        scp.StartInfo.RedirectStandardInput = true;
        scp.Start();

        //I've tried this with no success:
        using (StreamWriter sw = scp.StandardInput)
        {
            if (sw.BaseStream.CanWrite)
            {
                sw.WriteLine(pass);
            }
        }
        // Another failed attempt:
        scp.StandardInput.Write(pass + Environment.NewLine);
        scp.StandardInput.Flush();
        Thread.Sleep(1000);

我知道我可以使用cygwin期望它,但宁可使用c#与windows输入/输出进行交互。

2 个答案:

答案 0 :(得分:1)

试试这个:

    [DllImport("user32.dll")]
    static extern bool SetForegroundWindow(IntPtr hWnd);

    Process scp = new Process();
    scp.StartInfo.FileName = @"c:\cygwin\bin\scp";
    scp.StartInfo.Arguments = "/cygdrive/c" + path + " " + username + "@" + ServerName + ":/cygdrive/c/Temp/.";
    scp.StartInfo.UseShellExecute = false;
    scp.StartInfo.RedirectStandardOutput = true;
    scp.StartInfo.RedirectStandardError = true;
    scp.StartInfo.RedirectStandardInput = true;
    scp.Start();

    Process[] p = Process.GetProcessesByName("cmd");
    SetForegroundWindow(p[0].MainWindowHandle);
    SendKeys.SendWait(pass);

    scp.WaitForExit();

编辑:务必在\n的末尾添加pass

答案 1 :(得分:0)

此代码可以正常工作,无需调用Flush或Sleep:

Process p = new Process();
ProcessStartInfo info = new ProcessStartInfo();
info.FileName = "cmd.exe";
info.RedirectStandardInput = true;
info.UseShellExecute = false;

p.StartInfo = info;
p.Start();

using (StreamWriter sw = p.StandardInput)
{
    if (sw.BaseStream.CanWrite)
    {
        sw.WriteLine("dir");
    }
}

100%确定你的cygwin正在等待pwd吗?