How can I use VB.NET to automatically telnet into my switch and run a command and capture the output?

Ok, so what I need to do is have a program telnet into my switch and simply run the command "show arp" which echo's out two columns, IP ADDR  and MAC ADDR.  there are many ips and macs that will be shown from this command and normally when i just telnet in via command prompt in windows it will display the first 19 and i have to hit the enter key to display the next set of results until the last results are displayed and i'm back to a #: prompt.

what I'm needing is a way to "auto telnet" in sending the username/password and have the show arp command issued along with the enter key until it's done echoing out the list of mac / ip addresses, then save that output as a file or parse the mac/ip list so i can enter that data into a database.

is this possible to achieve in VB.NET?  the best result for me would be that could telnet in and get the data then i could write code to connect to an sql db for entering the data.

I need for my program to either stay logged in and issue the commands every 30 seconds or so, or close the connection and telnet in again every 30 seconds to repeat the process.

anyone have any code that can be used to telnet in and issue commands i need then capture the output?

thanks for your help.

Who is Participating?
Paul MacDonaldDirector, Information SystemsCommented:
VB.Net doesn't come with a telnet control.  You can try to do something from the command prompt and screen scrape, but that's almost certain not going to work well.  

We use a product from WoD ( and it works well for us.  It may be overkill for you, but it's worth looking at.
linuxroxAuthor Commented:
     Can it not be done using sockets and  or maybe C#?  that does look like a nifty control there though.  
Paul MacDonaldDirector, Information SystemsCommented:
We weren't able to come up with another solution we could rely on.  Your situation may be different, and I encourage you to wait and see if anyone else posts, but we did a fair amount of research and that's the solution we settled on.
Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

linuxroxAuthor Commented:
thx paulmacd.  does that control work in vb .net 2010 express?  
Telnet, as Ftp is a protocol based on TcpIp.

Vb.Net supports Sockets. It is easy to work with it.

I Develop my own class to custom Ftp.

It connect, then send ftp commands and receive Ftp Responses.
The list of commands is brief and easy to understand.
Note that you can send too many commands before begin read responses.

You can code sockets on Async mode and also on Block mode.
Block mode is easy to program, but as you need know server responses that finalize message and also error messages.

Some Interest Things:

     ClientStream = New StreamReader(New NetworkStream(clientSocket))

This reduces complexity as I use ReadLine on a stream.

     PendingResponse = "250 "

I Save On PendingResponse the code for I want read.
ClientRead  method store on a  list(of String) all lines read until I found required response.

Note that on Ftp I discard Client Read Responses (Lines) as I need only DataSocket responses.
But I dump It when some exception occurs, then I Know what fails.

Public Class Ftp
    'SENDING_DATA_PORT_20 : 150
    'CONNECTED : 220
    'NEED_PASSWORD : 331

    Private clientSocket, DataSocket As Socket, ClientStream As StreamReader
    Public Lines As New List(Of String)(128)
    Private Const LineFeed As String = ControlChars.Lf
    Private PendingResponse As String

    Public Sub New(ByVal remoteHost As String, ByVal remotePath As String, _
                   ByVal remoteUser As String, ByVal remotePassword As String, _
                   ByVal remotePort As Integer)

        clientSocket = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
        clientSocket.ReceiveTimeout = 5000
        clientSocket.SendTimeout = 5000
        clientSocket.Connect(Dns.GetHostEntry(remoteHost).AddressList(0), remotePort)
        ClientStream = New StreamReader(New NetworkStream(clientSocket))
        If remoteUser Is Nothing Then remoteUser = "Anonymous"

        Dim Sb As New StringBuilder(128)
        Sb.Append("USER ").Append(remoteUser).Append(ControlChars.Lf)
        PendingResponse = "220 "
        If remotePassword IsNot Nothing Then
            Sb.Append("PASS ").Append(remotePassword).Append(ControlChars.Lf)
            PendingResponse = "230 "
        End If
        If remotePath IsNot Nothing Then
             Sb.Append("CWD ").Append(remotePath).Append(ControlChars.Lf)
             PendingResponse = "250 "
        End If
     End Sub

    Public Sub Cmd(ByVal command As String)
        Dim commandBytes() As Byte = ASCII.GetBytes(command)
        clientSocket.Send(commandBytes, commandBytes.Length, 0)
    End Sub

     Public Sub Close()
           Cmd("QUIT" & LineFeed)
           If DataSocket IsNot Nothing Then DataSocket.Close()
     End Sub

     Private Function ClientRead(ByVal Query As String) As String
        Dim s As String
           s = ClientStream.ReadLine
           If s IsNot Nothing AndAlso s.StartsWith("5") Then
              Dim msg = String.Join(ControlChars.CrLf, Lines.ToArray)
              Throw (New Exception(msg))
           End If
        Loop Until s.StartsWith(Query)
        PendingResponse = Nothing
        Return s
     End Function

Open in new window

Here one sample to use DataSocket.
I Get list files on a Directory (only Names) - DataSocket
DataSocket don´t block as server closes socket when finish.

Then I send a command for each file to get Date and size, but I don´t wait for each.
When I has send all commands, then I retrieve all information on a list of FtpFile structure (name,Date,Size).
Note that it do´nt block as I know how many lines I want.

I set timeout to 5 seconds.
This solution is very fast.
To do it with FtpRequest for 20 files, it takes about 10 seconds, but this method takes less 1 second.
Private Function GetDataSocket() As Boolean
        'Entering Passive Mode (...)
        Dim IpData = ClientRead("227 "), p = IpData.IndexOf("("c) + 1, i As Integer
        If p > 0 Then
           Dim Low = 0, n = 0, V = 0, Host As String = Nothing
           For i = p To IpData.Length - 1
               If IpData(i) = ","c Then
                  n += 1
                  If n = 4 Then Host = IpData.Substring(p, i - p).Replace(","c, ".") : Exit For
               End If
           For i = i + 1 To IpData.Length - 1
               Dim ch = IpData(i)
               If ch = ")"c Then Exit For
               If ch = ","c Then Low = V : V = 0 Else V = V * 10 + CharUnicodeInfo.GetDigitValue(ch)
           DataSocket = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
           DataSocket.Connect(IPAddress.Parse(Host), (Low << 8) + V)
           PendingResponse = "150 " 'Opening data connection for ..
           Return True
        End If
        Return False
     End Function

     Public Function ListFiles() As List(Of FtpFile)
        Cmd("PASV" & LineFeed & "NLST" & LineFeed)
        If GetDataSocket() Then
           Using Ns As New StreamReader(New NetworkStream(DataSocket, True))
                   Dim s = Ns.ReadLine
                   If s Is Nothing Then Exit Do
                   Cmd("SIZE " & s & LineFeed & "MDTM " & s & LineFeed) 'Response: 213 Size / Date, 5xx when not found
           End Using
           DataSocket = Nothing
           Dim files = Lines.ToArray

           ClientRead("226 ") 'Transfer Complete
           Dim Lista As New List(Of FtpFile)(Lines.Count)
           For n = 0 To files.Length - 1
              Dim S = ClientStream.ReadLine, SZ = -1L, F = Date.MinValue
              If S.StartsWith("213 ") Then SZ = Long.Parse(S.Substring(4))
              S = ClientStream.ReadLine
              If SZ >= 0 AndAlso S.StartsWith("213 ") Then
                  F = Date.ParseExact(S.Substring(4), "yyyyMMddHHmmss", Nothing).ToLocalTime
                  Lista.Add(New FtpFile With {.Name = files(n), .size = SZ, .Fecha = F})
              End If
           Return Lista
           Return Nothing
        End If
    End Function

Open in new window

Paul MacDonaldDirector, Information SystemsCommented:
I don't think the problem would be in connecting, but dealing with whatever interface came up once the connection was established.  That's why I mentioned the problem of screen scraping in my initial post.  I can't say the control will be of any particular use in that regard, but it would save some coding time.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.