0 votes
by (250 points)

I am trying to login to the cisco router detect its prompt and pass the password to get higher privileges. can you provide the sample code. I have been struggling with that for some time.

Connect to the remote device
command: enable
detect prompt: Password:
type password: XYZ
detect prompt: #

1 Answer

0 votes
by (70.2k points)

The naive approach can look like this:

// connect and login to an SSH server
var ssh = new Ssh();
ssh.Connect("example.com");
ssh.Login("username", "password");

// start scripting using established SSH connection
Scripting s = ssh.StartScripting();

// at first, detect prompt
s.DetectPrompt();

// send command
s.SendCommand("enable");

// wait for "Password:" prompt
s.WaitFor(ScriptEvent.FromRegex("[Pp]assword[:] *$"));

// send password
s.SendCommand("XYZ");

// detect new prompt
s.DetectPrompt();

More robust approach with error handling would look like this:

// connect and login to an SSH server
var ssh = new Ssh();
ssh.Connect("example.com");
ssh.Login("username", "password");

// record VERBOSE logging,
// it will record raw data received from the server,
// which is very useful when writing automated scripts
ssh.LogWriter = new ConsoleLogWriter(LogLevel.Verbose);

// helper variables
ScriptMatch m;
var loginPrompt = ScriptEvent.FromRegex("[Ll]ogin[:] *$");
var passwordPrompt = ScriptEvent.FromRegex("[Pp]assword[:] *$");
var generalPrompt = ScriptEvent.FromRegex("[#$>] *$") & ScriptEvent.Delay(50);

// start scripting using established SSH connection
Scripting s = ssh.StartScripting();

// at first, detect prompt
s.DetectPrompt();

// send a command, which asks for username
s.SendCommand("telnet localhost");
m = s.WaitFor(ScriptEvent.Prompt, loginPrompt);
if (m.IsPrompt)
{
    // we received prompt => something went wrong
    throw new InvalidOperationException("Unexpected response: " + s.ReceivedData);
}

// send username, wait for password prompt
s.SendCommand("username");
m = s.WaitFor(ScriptEvent.Prompt, passwordPrompt);
if (m.IsPrompt)
{
    // we received prompt => something went wrong
    throw new InvalidOperationException("Unexpected response: " + s.ReceivedData);
}

// send password, wait for old-prompt or new-prompt or login/pwd-prompt
s.SendCommand("XYZ");
m = s.WaitFor(ScriptEvent.Prompt, generalPrompt, loginPrompt.SetTag(0), passwordPrompt.SetTag(0));
if (m.IsPrompt)
{
    // we received prompt => something went wrong
    throw new InvalidOperationException("Unexpected response: " + s.ReceivedData);
}
if (m.GetMatchInfoByTag(0) != null)
{
    // we received login/pwd prompt again => wrong password or username
    throw new InvalidOperationException("Wrong password or username - response: " + s.ReceivedData);
}

// detect new prompt
s.DetectPrompt();
...