George
George

Reputation: 310

C# how can I run cygwin scp and put in password using Process and StandardInputWriter?

With this code I see the login window prompting for a password but I can't seem to write the password to the shell window.

        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);

I know I can get this to work with cygwin expect but would rather use c# to interact with the windows input / output.

Upvotes: 0

Views: 975

Answers (2)

reegs
reegs

Reputation: 26

Try this:

    [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();

EDIT: Be sure to include \n at the end of pass.

Upvotes: 1

Davide Piras
Davide Piras

Reputation: 44605

this code works fine as expected and with no need to call Flush or 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");
    }
}

are you 100% sure that your cygwin is just waiting for the pwd?

Upvotes: 0

Related Questions