I want to create an SFTP account via ASP.NET app. For defining its password I need to type it twice
root@localhost:~# passwd fadwa
Enter new password:
Retype new password:
passwd: password updated successfully
To do so via C# code, I've tried the following after consulting a lot of solutions here, but it doesn't work.
using (var client = new SshClient("xx.xxx.xxx.xxx", 22, "root", "********"))
{
client.Connect();
ShellStream shellStream = client.CreateShellStream(string.Empty, 0, 0, 0, 0, 0);
StreamWriter stream = new StreamWriter(shellStream);
StreamReader reader = new StreamReader(shellStream);
stream.WriteLine("passwd fadwa"); // It displays -1
stream.WriteLine("fadwa");
stream.WriteLine("fadwa");
Console.WriteLine(reader.Read()); // It displays -1
client.Disconnect();
}
I've tried it even without using the StreamWriter
but directly :
shellStream.WriteLine("passwd fadwa\n" + "fadwa\n" + "fadwa\n");
while (true) Console.WriteLine(shellStream.Read());
also
shellStream.WriteLine("passwd fadwa");
shellStream.WriteLine("fadwa");
shellStream.WriteLine("fadwa");
while (true) Console.WriteLine(shellStream.Read());
And I got this, It stuck there!!
Any suggestions why it didn't work or other solution? I think I ve tried already the second solution and It worked, but not now.
You probably have to send the input only after the prompts appear. If you send the input too early, it gets ignored.
A lame solution would be like:
shellStream.WriteLine("passwd fadwa");
Thread.Sleep(100);
shellStream.WriteLine("fadwa");
Thread.Sleep(100);
shellStream.WriteLine("fadwa");
Better solution would be to wait for the prompt, before sending the password – expect
-like:
shellStream.WriteLine("passwd fadwa");
shellStream.Expect("Enter new password:");
shellStream.WriteLine("fadwa");
shellStream.Expect("Retype new password:");
shellStream.WriteLine("fadwa");
In general, automating a shell is always error-prone and should be avoided.