Hi guys!
I need to execute some sudo commands on a VM running ubuntu.
I started with a CheckSudoContact() method that should return true if it can echo a text. But I can't get it to work.
CheckSudoContact looks like this:
I need to execute some sudo commands on a VM running ubuntu.
I started with a CheckSudoContact() method that should return true if it can echo a text. But I can't get it to work.
CheckSudoContact looks like this:
public static bool CheckSudoContact(string sshIp, int sshPort, string userName, string userPwd, string prompt, string passwordPrompt) {
try {
using (var client = new SshClient(sshIp, sshPort, userName, userPwd)) {
client.Connect();
var testValue = Guid.NewGuid().ToString();
var command = string.Format("sudo echo {0}", testValue);
var result = "";
var dbgPasswordPrompt = "";
var dbgPrompt = "";
var sshConnected = false;
using (var stream = client.CreateShellStream("dumb", 80, 24, 800, 600, 4096)) {
stream.WriteLine(command);
stream.Expect(command); // Ensure that command has been processed by the shell
stream.Expect(
new ExpectAction(passwordPrompt, (s) => {
Console.Write(s);
dbgPasswordPrompt = s; // Debug
stream.WriteLine(userPwd);
}),
new ExpectAction(prompt, (s) => {
Console.Write(s);
dbgPrompt = s; // Debug
})
);
Debug.WriteLine("CheckSudoContact dbgPasswordPrompt=" +
dbgPasswordPrompt); // Debug
Debug.WriteLine("CheckSudoContact dbgPrompt=" +
dbgPrompt); // Debug
result = stream.ReadLine(TimeSpan.FromMilliseconds(500));
var line = 1;
while (result != null) {
Debug.WriteLine("CheckSudoContact stream.ReadLine" + line++ + "=" +
result); // Debug
if (result.Length > 1) {
result = result.Substring(0, result.Length - 1);
}
if (result.Equals(testValue)) {
sshConnected = true;
break;
}
result = stream.ReadLine(TimeSpan.FromMilliseconds(500));
}
}
client.Disconnect();
return sshConnected;
}
}
catch {
// An error must mean we do not have SSH contact
return false;
}
}
I call it like this:if (SshHelper.CheckSudoContact("10.0.0.20", 22,
"myUsername", "myPwd",
":~$", "[sudo] password for")) {
Debug.WriteLine("SshHelper.CheckSudoContact = contact!");
}
else {
Debug.WriteLine("SshHelper.CheckSudoContact says no contact!");
}
The above gives debug output that indicates the ExpectActions for prompt and passwordPrompt are never executed and the testValue is never echoed, so I suspect the command isn't executed at all:CheckSudoContact dbgPasswordPrompt=
CheckSudoContact dbgPrompt=
CheckSudoContact stream.ReadLine1=
CheckSudoContact stream.ReadLine2=
CheckSudoContact stream.ReadLine3=myuser@myputer:~$ sudo echo f72cdd2e-949a-449d-a526-dd9efae82340
SshHelper.CheckSudoContact says no contact!