【问题标题】:C# how can I run cygwin scp and put in password using Process and StandardInputWriter?C# 如何运行 cygwin scp 并使用 Process 和 StandardInputWriter 输入密码?
【发布时间】:2011-11-23 01:21:53
【问题描述】:

使用此代码,我看到登录窗口提示输入密码,但我似乎无法将密码写入 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 expect 一起工作,但宁愿使用 c# 与 windows 输入/输出交互。

【问题讨论】:

    标签: c# cygwin scp


    【解决方案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();
    

    编辑:一定要在pass 的末尾加上\n

    【讨论】:

      【解决方案2】:

      此代码可以正常工作,无需调用 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 只是在等待密码吗?

      【讨论】:

        猜你喜欢
        • 2018-09-26
        • 2011-09-10
        • 1970-01-01
        • 2019-02-15
        • 2013-11-24
        • 2017-03-06
        • 2019-08-25
        • 2011-05-07
        • 2022-10-19
        相关资源
        最近更新 更多