Solved

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
6
1,811 Views
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 vb.net 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.

0
Comment
Question by:linuxrox
  • 3
  • 2
6 Comments
 
LVL 33

Accepted Solution

by:
paulmacd 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 (http://www.weonlydo.com/TelnetDLX/telnet-ssh-component.asp) and it works well for us.  It may be overkill for you, but it's worth looking at.
0
 

Author Comment

by:linuxrox
ID: 36574620
paulmacd:
     Can it not be done using sockets and vb.net?  or maybe C#?  that does look like a nifty control there though.  
0
 
LVL 33

Expert Comment

by:paulmacd
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.
0
What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

 

Author Comment

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

Assisted Solution

by:x77
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
    'COMMAND_NOT_IMPLEMENTED : 202
    'CONNECTED : 220
    'AUTHENTICATED : 230
    'NEED_PASSWORD : 331
    'AUTHENTICATION_FAILED : 530

    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
        Cmd(Sb.ToString)
     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)
           ClientStream.Close()
           clientSocket.Close()
           If DataSocket IsNot Nothing Then DataSocket.Close()
     End Sub

     Private Function ClientRead(ByVal Query As String) As String
        Lines.Clear()
        Dim s As String
        Do
           s = ClientStream.ReadLine
           Lines.Add(s)
           If s IsNot Nothing AndAlso s.StartsWith("5") Then
              Dim msg = String.Join(ControlChars.CrLf, Lines.ToArray)
              Close()
              Throw (New Exception(msg))
           End If
        Loop Until s.StartsWith(Query)
        PendingResponse = Nothing
        Lines.Clear()
        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
           Next
           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)
           Next
           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))
               Do
                   Dim s = Ns.ReadLine
                   If s Is Nothing Then Exit Do
                   Lines.Add(s)
                   Cmd("SIZE " & s & LineFeed & "MDTM " & s & LineFeed) 'Response: 213 Size / Date, 5xx when not found
               Loop
           End Using
           DataSocket.Close()
           DataSocket = Nothing
           Dim files = Lines.ToArray
           Lines.Clear()

           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
           Next
           Return Lista
        Else
           Return Nothing
        End If
    End Function

Open in new window

0
 
LVL 33

Expert Comment

by:paulmacd
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.
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

If you’re thinking to yourself “That description sounds a lot like two people doing the work that one could accomplish,” you’re not alone.
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.
Viewers will learn how to properly install and use Secure Shell (SSH) to work on projects or homework remotely. Download Secure Shell: Follow basic installation instructions: Open Secure Shell and use "Quick Connect" to enter credentials includi…
In this fourth video of the Xpdf series, we discuss and demonstrate the PDFinfo utility, which retrieves the contents of a PDF's Info Dictionary, as well as some other information, including the page count. We show how to isolate the page count in a…

757 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

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now