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

Posted on 2011-09-21
Last Modified: 2012-05-12
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.

Question by:linuxrox
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 2
LVL 34

Accepted Solution

Paul MacDonald earned 250 total points
ID: 36574563
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.

Author Comment

ID: 36574620
     Can it not be done using sockets and  or maybe C#?  that does look like a nifty control there though.  
LVL 34

Expert Comment

by:Paul MacDonald
ID: 36574745
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.
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!


Author Comment

ID: 36575106
thx paulmacd.  does that control work in vb .net 2010 express?  
LVL 15

Assisted Solution

x77 earned 250 total points
ID: 36575314
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

LVL 34

Expert Comment

by:Paul MacDonald
ID: 36575772
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.

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Displaying an arrayList in a listView using the default adapter is rarely the best solution. To get full control of your display data, and to be able to refresh it after editing, requires the use of a custom adapter.
When it comes to security, there are always trade-offs between security and convenience/ease of administration. This article examines some of the main pros and cons of using key authentication vs password authentication for hosting an SFTP server.
With the power of JIRA, there's an unlimited number of ways you can customize it, use it and benefit from it. With that in mind, there's bound to be things that I wasn't able to cover in this course. With this summary we'll look at some places to go…
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…

756 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question