Overview
This article will demonstrate how to script telnet sessions in .NET using Telnet Factory for .NET.
Code Example
Download TelnetLicense.txt
| Download TScript.cs
| Download TScript.vb
1: using System;
2: using System.Collections.Generic;
3: using System.Text;
4: using Jscape.Telnet;
5: using Jscape.Telnet.Options;
6:
7: namespace TelnetScriptNET
8: {
9: class TScript
10: {
11: Telnet t = null;
12: TelnetScript s = null;
13: public TScript(string hostname)
14: {
15: s = new TelnetScript(t = new Telnet(hostname));
16: s.TaskStartedEvent +=
17: new TelnetScript.TaskStartedEventHandler(s_TaskStartedEvent);
18: s.TaskEndedEvent +=
19: new TelnetScript.TaskEndedEventHandler(s_TaskEndedEvent);
20: }
21:
22: private void s_TaskEndedEvent(object sender, TelnetTaskEndedEventArgs e)
23: {
24: Console.WriteLine(e.Task.Name + " ...finished");
25: }
26:
27: private void s_TaskStartedEvent(object sender, TelnetTaskStartedEventArgs e)
28: {
29: Console.WriteLine(e.Task.Name + " ...started");
30: }
31:
32: public void addTask(TelnetTask task)
33: {
34: s.AddTask(task);
35: }
36:
37: public void openConnection()
38: {
39: t.Connect();
40: }
41:
42: public void closeConnection()
43: {
44: t.Disconnect();
45: }
46:
47: static void Main(string[] args)
48: {
49: try
50: {
51: TScript ts = new TScript("hostname");
52: TelnetTask loginTask = new TelnetTask("[Ll]ogin:", "jsmith", "[Pp]assword:");
53: loginTask.StartPromptRegex = true;
54: loginTask.EndPromptRegex = true;
55: ts.addTask(loginTask);
56: loginTask.Cancel();
57: TelnetTask cd = new TelnetTask("$", "cd /", "$");
58: ts.addTask(cd);
59: ts.openConnection();
60: while (!cd.IsComplete());
61: Console.WriteLine("Response : " + cd.GetResponse());
62: ts.closeConnection();
63: }
64: catch (Exception e)
65: {
66: Console.WriteLine(e.Message);
67: }
68:
69: Console.WriteLine("Press any key to exit ... ");
70: Console.Read();
71: }
72: }
73: }
Lines 1-5 : Necessary import statements.
Lines 11-20 : Initialize TelnetScript instance and connect event handlers.
Lines 22-30 : Event handlers for start and end task events.
Lines 32-35 : Add task to script.
Lines 37-45 : Methods to open and close connections to the server.
Line 51 : Initialize TScript instance.
Line 52 : Create a login task
Line 55 : add login task to script.
Line 56 : Cancel login task.
Line 57 : Create a directory listing task.
Line 58 : Add task to script.
Line 59 : Open connection to the server.
Line 60 : Wait for directory listing task to complete.
Lines 61-62 : Get response from directory listing task and close connection to the
server.
Comments