TheMehrdad
asked on
Program Cisco switches by C#
Hi
I want to use System.Net.Sockets.TcpClie nt class in .Net framework to configure a Cisco switch or router. Does anyone has any samples or how to?
I already have written the below code. When I run it, I don't get what I expect.
I want to use System.Net.Sockets.TcpClie
I already have written the below code. When I run it, I don't get what I expect.
public class Cisco
{
private TcpClient _client;
//private event EventHandler<
private TcpClient Client
{
get
{
if (_client == null)
_client = new TcpClient();
return _client;
}
}
public Cisco(IPEndPoint endPoint)
{
Client.Connect(endPoint);
var s = Read();
}
public string RunCommand(string command)
{
if (!command.EndsWith("\r\n"))
command = string.Format("{0}\r\n", command);
var buffer = ASCIIEncoding.ASCII.GetBytes(command);
Client.GetStream().Write(buffer, 0, buffer.Length);
var s = Read();
return s;
}
private string Read()
{
var buffer = new Byte[Client.ReceiveBufferSize];
var read = new List<string>();
while (Client.GetStream().DataAvailable)
{
var state = new object[] { Client.GetStream(), buffer, null };
var ia = Client.GetStream().BeginRead(buffer, 0, buffer.Length, new AsyncCallback(Read), state);
ia.AsyncWaitHandle.WaitOne();
read.Add(ASCIIEncoding.ASCII.GetString(buffer.Take((int)((object[])ia.AsyncState)[2]).ToArray()));
}
return string.Concat(read.ToArray());
}
private void Read(IAsyncResult ar)
{
var state = ar.AsyncState as object[];
var stream = state[0] as NetworkStream;
var buffer = state[1] as byte[];
var br = stream.EndRead(ar);
state[2] = br;
}
}
static void Main(string[] args)
{
Cisco c = new Cisco(new IPEndPoint(IPAddress.Parse("172.16.1.147"), 23));
Console.Write(c.RunCommand("PASSWORD"));
Console.Write(c.RunCommand("enable"));
Console.Write(c.RunCommand("ENABLE PASSWORD"));
Console.Write(c.RunCommand("show run"));
Console.Write(c.RunCommand("exit"));
Console.Read();
}
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
AFAIK there is no other way.
ASKER
Thanks for your comment. Is there any other way to configure a Cisco Switch/Router programatically? If Telnet is the only solution, so I will deal with this netcat.