Executing a script |
A TelnetScript will begin execution as soon as a connection is established with the telnet server and option negotiation has completed. Therefore, it is necessary in most cases that your TelnetScript be created and all tasks added before the Telnet.Connect method is invoked.
Example
This example demonstrates how to automatically login to a telnet server, execute a command and logout. Some assumptions have been made about the start and end prompts in the example below. Your system prompts will likely differ although the fundamental process would be the same.
[C#]
// Create telnet instance
Telnet telnet = new Telnet("10.0.0.1");
// Create a TelnetScript
TelnetScript script = new TelnetScript(telnet);
// Create script tasks
TelnetTask login = new TelnetTask("login:", "username", "Password:");
TelnetTask password = new TelnetTask("Password:", "password", "$");
TelnetTask dir = new TelnetTask("$", "ls -al", "$");
// Subscribe to task started event
script.TaskStartedEvent += new TelnetScript.TaskStartedEventHandler(OnTaskStarted);
// Subscribe to task ended event
script.TaskEndedEvent += new TelnetScript.TaskEndedEventHandler(OnTaskEnded);
// Subscribe to task failed event
script.TaskFailedEvent += new TelnetScript.TaskFailedEventHandler(OnTaskFailed);
// Add tasks to script instance
script.AddTask(login);
script.AddTask(password);
script.AddTask(dir);
// Connect to telnet server, automatically executing the script
telnet.Connect();
[Visual Basic]
Private WithEvents myTelnet As Telnet
Private user As String
Private pass As String
' Create telnet instance
myTelnet = New Telnet("10.0.0.1")
' Create TelnetScript script instance by passing in telnet instance
Dim script As TelnetScript = New TelnetScript(myTelnet)
Dim login As TelnetTask = New TelnetTask("login:", user, "Password:")
Dim pwd As TelnetTask = New TelnetTask("Password:", pass, "$")
Dim dir As TelnetTask = New TelnetTask("$", "ls -al", "$")
script.AddTask(login)
script.AddTask(pwd)
script.AddTask(dir)
' Connect to telnet server, automatically executing the script
myTelnet.Connect()
See also