Cisco Telnet C-Sharp
From Teknologisk videncenter
Class HOTelnet.cs
using System;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Collections.Generic;
using System.Text.RegularExpressions;
namespace Telnet
{
public class TelnetConnection : IDisposable
{
public string hostname;
private TcpClient tcpSocket;
private int TimeoutMs = 100;
public bool IsConnected
{
get
{
try {
return tcpSocket.Connected;
}
catch
{
return false;
}
}
}
public TelnetConnection(string hostname, int port)
{
try
{
tcpSocket = new TcpClient(hostname, port);
}
catch
{
}
}
~TelnetConnection()
{
Dispose(false);
}
public string CiscoLogin(string username, string password)
{
string s = ReadUntil("Username:");
WriteLine(username);
s = ReadUntil("Password:");
WriteLine(password);
s = ReadUntil("[>|#]");
string[] s2 = s.Split('\r', '\n');
s = s2[s2.Length - 1];
Match match = Regex.Match(s, @"(.*)[>|#]$");
if (match.Success)
{
hostname = match.Groups[1].Value;
}
else
{
Console.WriteLine("ERROR: User prompt not returned as expected - Is it a Cisco router?");
}
WriteLine("terminal length 0"); // Disable multipage outputs
s = ReadUntil(hostname + "#");
return s;
}
public string CiscoLogin(string password)
{
string s = ReadUntil("Password:");
WriteLine(password);
s = ReadUntil(">");
string[] s2 = s.Split('\r', '\n');
s = s2[s2.Length - 1];
Match match = Regex.Match(s, @"(.*)>$");
if (match.Success)
{
hostname = match.Groups[1].Value;
}
else
{
Console.WriteLine("ERROR: User prompt not returned as expected - Is it a Cisco router?");
}
return s;
}
public void CiscoEnable(string password)
{
WriteLine("enable");
Console.WriteLine("Sent enable");
string s = ReadUntil("Password:");
WriteLine(password);
s = ReadUntil(hostname + "#");
WriteLine("terminal length 0"); // Disable multipage outputs
s = ReadUntil(hostname + "#");
}
public List<String> CiscoCommand(string Command)
{
String Result;
List<String> ResultList = new List<String>();
WriteLine(Command);
Result = ReadUntil("(" + hostname + "#|" + hostname + "\\(config.*\\)#)");
String[] ResultArray = Result.Split('\r');
//Remove newline and replace tabs with space
for (int i = 0; i < ResultArray.Length; i++)
{
ResultArray[i] = Regex.Replace(ResultArray[i], @"\n|\r", ""); // Remove \r and \n
ResultArray[i] = Regex.Replace(ResultArray[i], @"\t+", " "); // Replace one or more tabs with one space
ResultList.Add(ResultArray[i]);
}
return ResultList;
}
public void WriteLine(string cmd)
{
Write(cmd + "\n");
}
public void Write(string cmd)
{
if (!tcpSocket.Connected)
{
return;
}
byte[] buf = ASCIIEncoding.ASCII.GetBytes(cmd.Replace("\0xFF", "\0xFF\0xFF"));
tcpSocket.GetStream().Write(buf, 0, buf.Length);
}
public string ReadUntil(string Delimiter)
{
var sb = new StringBuilder();
string s;
do
{
int input = tcpSocket.GetStream().ReadByte();
switch (input)
{
case -1:
break;
case (int)Verbs.Iac:
// interpret as command
int inputVerb = tcpSocket.GetStream().ReadByte();
if (inputVerb == -1)
{
break;
}
switch (inputVerb)
{
case (int)Verbs.Iac:
// literal IAC = 255 escaped, so append char 255 to string
sb.Append(inputVerb);
break;
case (int)Verbs.Do:
case (int)Verbs.Dont:
case (int)Verbs.Will:
case (int)Verbs.Wont:
// reply to all commands with "WONT", unless it is SGA (suppres go ahead)
int inputoption = tcpSocket.GetStream().ReadByte();
if (inputoption == -1)
{
break;
}
tcpSocket.GetStream().WriteByte((byte)Verbs.Iac);
if (inputoption == (int)Options.Sga)
{
tcpSocket.GetStream().WriteByte(inputVerb == (int)Verbs.Do ? (byte)Verbs.Will : (byte)Verbs.Do);
}
else
{
tcpSocket.GetStream().WriteByte(inputVerb == (int)Verbs.Do ? (byte)Verbs.Wont : (byte)Verbs.Dont);
}
tcpSocket.GetStream().WriteByte((byte)inputoption);
break;
}
break;
default:
sb.Append((char)input);
break;
}
s = sb.ToString();
} while (!Regex.IsMatch(s, Delimiter + "$"));
//} while ( !s.EndsWith(Delimiter)) ;
return (s);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
if (tcpSocket != null)
{
((IDisposable)tcpSocket).Dispose();
tcpSocket = null;
}
}
}
#region Private Enums
enum Verbs
{
Will = 251,
Wont = 252,
Do = 253,
Dont = 254,
Iac = 255
}
enum Options
{
Sga = 3
}
#endregion
}
}
Eksempel på anvendelse 1
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Telnet
{
class Program
{
static void Main(string[] args)
{
TelnetConnection T1;
List<String> Result = new List<String>();
int lineCounter = 1;
T1 = new TelnetConnection("192.168.22.1", 23);
T1.CiscoLogin("Password1");
T1.CiscoEnable("Password2");
Result = T1.CiscoCommand("Show running");
Result.ForEach(delegate (String line)
{
Console.WriteLine("{0}: {1}",lineCounter, line);
lineCounter++;
});
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
}
}
Eksempel på anvendelse 2
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text.RegularExpressions;
namespace Telnet
{
public partial class Default : System.Web.UI.Page
{
Dictionary<String, String> CiscoDevice = new Dictionary<String, String>();
public static List<string> mylist = new List<string>();
public static List<String> Result = new List<String>();
public static HOTelnet.TelnetConnection T1;
public static string IP;
protected void Page_Load(object sender, EventArgs e)
{
}
//Connect knap
protected void button1_Click(object sender, EventArgs e)
{
//Giver fejl hvis IP ikke er udfyldt
if (string.IsNullOrWhiteSpace(TextBox1.Text))
{
//Giver fejl hvis Password ikke er udfyldt
if (string.IsNullOrWhiteSpace(TextBox2.Text))
{
Label4.Text = "Please enter password";
}
Label2.Text = "Please enter an IP adress";
}
//Giver fejl hvis Password ikke er udfyldt
else if (string.IsNullOrWhiteSpace(TextBox2.Text))
{
Label4.Text = "Please enter password";
Label2.Text = "";
}
//Hvis begge ting er udfyldt prøver vi at kontakte switchen eller routeren og få adgang via telnet
else if ((!(string.IsNullOrWhiteSpace(TextBox1.Text))) && (!(string.IsNullOrWhiteSpace(TextBox2.Text))))
{
IP = TextBox1.Text;
CiscoDevice.Add("IP", IP);
T1 = new Cisco_Configuration_1.TelnetConnection(CiscoDevice["IP"], 23);
Label2.Text = "";
//Hvis det lykkedes at få forbindelse
if (T1.IsConnected == true)
{
string s = T1.CiscoLogin(TextBox2.Text);
TextBox1.Text = "";
TextBox2.Text = "";
T1.CiscoEnable("cisco");
//skifter til ChooseMenu.aspx
Server.Transfer("ChooseMenu.aspx", true);
}
//Giver fejl hvis det ikke lykkedes at kontakte IPén
else if (T1.IsConnected == false)
{
Label2.Text = "Wrong IP, try again";
TextBox1.Text = "";
TextBox2.Text = "";
}
}
}
//Switch config
public void SWConf ()
{
T1.CiscoCommand("configure terminal");
T1.CiscoCommand("line vty 0 4");
T1.CiscoCommand("password cisco");
T1.CiscoCommand("exit");
T1.CiscoCommand("enable secret cisco");
T1.CiscoCommand("banner motd !2502!");
T1.CiscoCommand("interface vlan1");
T1.CiscoCommand("ip address 192.168.138.220 255.255.255.0");
T1.CiscoCommand("exit");
T1.CiscoCommand("interface fa0/1");
T1.CiscoCommand("switchport mode trunk");
T1.CiscoCommand("exit");
T1.CiscoCommand("interface range fa0/20 - 24");
T1.CiscoCommand("switchport mode access");
T1.CiscoCommand("switchport access vlan 5");
T1.CiscoCommand("exit");
T1.CiscoCommand("exit");
}
//Router config
public void RouterConf()
{
T1.CiscoCommand("configure terminal");
T1.CiscoCommand("line vty 0 4");
T1.CiscoCommand("password cisco");
T1.CiscoCommand("exit");
T1.CiscoCommand("enable secret cisco");
T1.CiscoCommand("banner motd !authorized access only!");
T1.CiscoCommand("Interface fa0/1");
T1.CiscoCommand("ip address 192.168.138.230 255.255.255.0");
T1.CiscoCommand("no shutdown");
T1.CiscoCommand("exit");
T1.CiscoCommand("interface fa0/1.10");
T1.CiscoCommand("encapsulation dot1Q 5");
T1.CiscoCommand("ip address 192.168.139.1 255.255.255.0");
T1.CiscoCommand("ip helper-address SKOLENS NETVÆRK");
T1.CiscoCommand("exit");
T1.CiscoCommand("ip dhcp pool vlandhcp");
T1.CiscoCommand("network 192.168.139.0 255.255.255.0");
T1.CiscoCommand("default-router 192.168.139.1");
T1.CiscoCommand("exit");
T1.CiscoCommand("exit");
}
//Show equipment specs
public List<string> ShowInfo()
{
Result = T1.CiscoCommand("Show version");
mylist.Add("Der er " + Result.Count + " members");
Result.ForEach(delegate (String line)
{
// System image file is "flash:/c3560-ipservicesk9-mz.122-58.SE2.bin"
Match match = Regex.Match(line, "System image file is \"(.*)\"$");
if (match.Success)
{
mylist.Add("IOS: " + match.Groups[1].Value);
}
//cisco WS-C3560-24TS (PowerPC405) processor (revision D0) with 131072K bytes of memory.
match = Regex.Match(line, @"(\S+\s+\S+).*of memory.$");
if (match.Success)
{
mylist.Add("Model: " + match.Groups[1].Value);
}
//Processor board ID.
match = Regex.Match(line, "Processor board ID\\W+(.*)");
if (match.Success)
{
mylist.Add("CPUID: " + match.Groups[1].Value);
}
//Ports available
match = Regex.Match(line, @"(\d+)\s+(\S+).*IEEE.*");
if (match.Success)
{
mylist.Add((String)match.Groups[2].Value + ": " + match.Groups[1].Value);
}
});
mylist.Add("IP: " + IP);
return mylist;
}
}
}