2012-02-02 91 views
0

我有一箇中央服務器,我需要寫一點vb.net,看看我是否可以telnet到指定端口上的指定服務器。使用VB.net在遠程計算機上測試telnet通信?

是否有無論如何這可以在VB.net中完成?我曾考慮過發送命令提示符到遠程服務器來執行telnet,然後輸出netsh的日誌並讀取這些日誌,並將這些信息發送回中央服務器進行審查。

它做起來,所以如果有我只是想知道一個簡單的方法

回答

1

你應該只建立與目標服務器和端口(通常是23遠程登錄的IP地址的TcpClient對象的一個​​非常混亂的方式)。然後調用Connect!

這裏看到更多的信息:

http://msdn.microsoft.com/en-us/library/system.net.sockets.tcpclient.aspx

像這樣的東西(可能不準確):

Try 

    Dim telnetServerIp As String = "192.168.100.55" 
    Dim telnetPort As Integer = 23 
    Dim client As New TcpClient(telnetServerIp, telnetPort) 
    MessageBox.Show("Server is reachable") 
Catch ex As Exception 
    MessageBox.Show("Could not reach server") 
End Try 

被告知這是示例代碼。當你完成後,你想要清理(關閉/處理)連接(TcpClient)對象等,但它應該讓你開始。

+0

我仍然在這裏損失:(試圖讓我身邊的事情 – K20GH 2012-02-02 14:33:01

+0

頭@GregHesp我將修改添加細節,但只是爲了確認......所有你想知道是否某個服務器可以通過Telnet訪問嗎? – tcarvin 2012-02-02 14:34:52

+0

謝謝。我的要求是能夠找出Server1是否可以在PortX上與ServerX通信。我曾經通過登錄Server1並輸入「telnet ServerX PortX「 – K20GH 2012-02-02 14:38:02

0

你應該嘗試一些實現這一點。使用.net的Telnet communication有很多幫助。從這些規定的鏈接
採取的想法,並在vb.net實現..

How can I open a telnet connection and run a few commands in C#
Telnet connection using .net

您可以使用System.Net.Sockets.TcpClient對象,而不是一個 插座對象,它已經配置插座參數到 使用ProtocolType.Tcp

1.創建一個新的TcpClient對象,它需要服務器名稱和端口(不需要IPEndPoint,很好)。
2.Pull一個的NetworkStream出的TcpClient通過調用GetStream()
3.Convert您的訊息使用Encoding.ASCII.GetBytes(串)
4.Now可以使用stream.Write發送和接收數據字節和stream.Read方法,分別。順便說一下,stream.Read方法返回寫入您的接收數組的字節數。
5.使用Encoding.ASCII.GetString(字節數組)將數據恢復爲人類可讀的格式。
6.通過調用stream.Close()和client.Close(),清除網絡管理員生氣之前的混亂。

編號:C# 2.0* and Telnet - Not As Painful As It Sounds

// Create a TcpClient. 
    // Note, for this client to work you need to have a TcpServer 
    // connected to the same address as specified by the server, port 
    // combination. 
    Int32 port = 13000; 
    TcpClient client = new TcpClient(server, port); 

    // Translate the passed message into ASCII and store it as a Byte array. 
    Byte[] data = System.Text.Encoding.ASCII.GetBytes(message);   

    // Get a client stream for reading and writing. 
    // Stream stream = client.GetStream(); 

    NetworkStream stream = client.GetStream(); 

    // Send the message to the connected TcpServer. 
    stream.Write(data, 0, data.Length); 

    Console.WriteLine("Sent: {0}", message); 
+0

我剛剛嘗試過,但是它失敗了:Dim client as TcpClient = New TcpClient(ServerMod,port),因爲它表示目標計算機拒絕連接。即使當我做一個telnet它的工作 – K20GH 2012-02-02 14:58:42

+0

檢查目標機防火牆拒絕端口的連接..添加端口在防火牆例外列表.. – 2012-02-02 15:42:26

0

我做了這個在工作中的一個項目。 我認爲這是一個針對大多數人需求的完整的通用解決方案 但是,這是我第一個真正的.net項目,所以請隨時批評它。

仿照http://www.codeproject.com/Articles/63201/TelnetSocket

Imports System.Threading 
Imports System.IO 
Imports System.IO.Pipes 

Public Class TelnetClient 
    Private Server As String 
    Private NetWorkProtocolClient As System.Net.Sockets.TcpClient 
    Private ServerStream As System.Net.Sockets.NetworkStream 
    Private DoReader As Boolean 
    Private ReaderThread As Thread 
    Private OutputPipe As AnonymousPipeServerStream 
    Private WaitForString As String 
    Private WaitForStringEvent As New AutoResetEvent(False) 

    ReadOnly Property IsConnected() As Boolean 
    Get 
     Return (Not (IsNothing(NetWorkProtocolClient)) AndAlso (NetWorkProtocolClient.Connected)) 
    End Get 
    End Property 

    ReadOnly Property ConnectedTo() As String 
    Get 
     If (Not (IsNothing(NetWorkProtocolClient)) AndAlso (NetWorkProtocolClient.Connected)) Then 
     Return NetWorkProtocolClient.Client.RemoteEndPoint.ToString() 
     Else 
     Return "Nothing" 
     End If 
    End Get 
    End Property 

    'Set the Server string to connect to. 
    Public Sub SetServer(ByVal new_server As String) 
    'double check this later 
    Server = new_server 
    End Sub 
    'Connects if possilbe. If already conneced to some thing it Disconnects from old Telnet and connects to new Telnet. 
    Public Sub Connect() 
    Try 
     If (Not (IsNothing(NetWorkProtocolClient))) AndAlso NetWorkProtocolClient.Connected Then 
     Disconnect() 
     End If 
     If Not IsNothing(Server) Then 
     NetWorkProtocolClient = New System.Net.Sockets.TcpClient(Server, 23) 
     If NetWorkProtocolClient.Connected Then 
      'clear on a new client 
      WaitForString = Nothing 
      WaitForStringEvent.Reset() 

      NetWorkProtocolClient.NoDelay = True 
      ServerStream = NetWorkProtocolClient.GetStream() 
      ServerStream.ReadTimeout = 1000 
      DoReader = True 
      ReaderThread = New Thread(AddressOf ReaderTask) 
      ReaderThread.IsBackground = True 
      ReaderThread.Priority = ThreadPriority.AboveNormal 
      ReaderThread.Start() 
     End If 
     End If 
    Catch ex As System.Net.Sockets.SocketException 
     Console.WriteLine("SocketException Connect: {0}", ex) 
    End Try 
    End Sub 

    'Disconnects if connected, otherwise does nothing. 
    Public Sub Disconnect() 
    Try 
     If ReaderThread.IsAlive Then 
     DoReader = False 
     ReaderThread.Join(1000) 
     End If 
     If (Not (IsNothing(NetWorkProtocolClient))) Then 
     ServerStream.Close() 
     NetWorkProtocolClient.Close() 
     End If 
    Catch ex As System.Net.Sockets.SocketException 
     Console.WriteLine("SocketException Disconnect: {0}", ex) 
    End Try 
    End Sub 

    'Returns true if found before timeout milliseconds. Use -1 to have infinite wait time. 
    'Returns false if timeout occured. 
    Public Function WaitFor(ByVal command As String, ByVal timeout As Integer) As Boolean 
    WaitForString = New String(command) 
    WaitForStringEvent.Reset() 
    Dim was_signaled As Boolean = False 
    'Block until a the right value from reader or user defined timeout 
    was_signaled = WaitForStringEvent.WaitOne(timeout) 
    WaitForString = Nothing 
    Return was_signaled 
    End Function 

    Public Sub Write(ByVal command As String) 
    Try 
     If (Not (IsNothing(NetWorkProtocolClient))) Then 
     If NetWorkProtocolClient.Connected Then 
      'Write the value to the Stream 
      Dim bytes() As Byte = System.Text.Encoding.ASCII.GetBytes(command) 
      SyncLock ServerStream 
      ServerStream.Write(bytes, 0, bytes.Length) 
      End SyncLock 
     End If 
     End If 
    Catch ex As System.Net.Sockets.SocketException 
     Console.WriteLine("SocketException Write: {0}", ex) 
    End Try 
    End Sub 

    'appends CrLf for the caller 
    Public Sub WriteLine(ByVal command As String) 
    Try 
     If (Not (IsNothing(NetWorkProtocolClient))) Then 
     If NetWorkProtocolClient.Connected Then 
      'Write the value to the Stream 
      Dim bytes() As Byte = System.Text.Encoding.ASCII.GetBytes(command & vbCrLf) 
      SyncLock ServerStream 
      ServerStream.Write(bytes, 0, bytes.Length) 
      End SyncLock 
     End If 
     End If 
    Catch ex As System.Net.Sockets.SocketException 
     Console.WriteLine("SocketException Write: {0}", ex) 
    End Try 
    End Sub 

    'Get a pipe to read output. Note: anything written by WriteLine may be echoed back if the other Telnet offers to do it. 
    Public Function GetPipeHandle() As String 
    If Not IsNothing(ReaderThread) AndAlso ReaderThread.IsAlive AndAlso Not IsNothing(OutputPipe) Then 
     Return OutputPipe.GetClientHandleAsString 
    Else 
     Return Nothing 
    End If 
    End Function 

    'Task that watches the tcp stream, passes info to the negotiation function and signals the WaitFor task. 
    Private Sub ReaderTask() 
    Try 
     OutputPipe = New AnonymousPipeServerStream(PipeDirection.Out) 
     Dim prevData As New String("") 
     While (DoReader) 
     If (Not (IsNothing(NetWorkProtocolClient))) Then 

      If ServerStream.DataAvailable Then 

      'Grab Data 
      Dim data As [Byte]() = New [Byte](NetWorkProtocolClient.ReceiveBufferSize) {} 
      Dim bytes As Integer = ServerStream.Read(data, 0, data.Length) 

      'Negotiate anything that came in 
      bytes = Negotiate(data, bytes) 

      If (bytes > 0) Then 
       'append previous to the search sting incase messages were fragmented 
       Dim s As New String(prevData & System.Text.ASCIIEncoding.ASCII.GetChars(data)) 

       'If Pipe is connected send it remaining real data 
       If OutputPipe.IsConnected Then 
       OutputPipe.Write(data, 0, bytes) 
       End If 

       'Check remaining against WaitForString 
       If Not IsNothing(WaitForString) Then 
       If s.Contains(WaitForString) Then 
        WaitForStringEvent.Set() 
        'clear prevData buffer because the WaitForString was found 
        prevData = New String("") 
       Else 
        'Nothing found make the current string part of the next string. 
        prevData = New String(s) 
       End If 
       Else 
       prevData = New String("") 
       End If 
      End If 

      Else 
      Thread.Sleep(100) 
      End If 
     End If 
     End While 
     OutputPipe.Close() 
     OutputPipe.Dispose() 
    Catch ex As System.IO.IOException 
     Console.WriteLine("IO Error: {0}", ex) 
    Catch ex As System.Net.Sockets.SocketException 
     Console.WriteLine("SocketException Reader: {0}", ex) 
    End Try 
    End Sub 

    'Shamelessly adapted from http://www.codeproject.com/Articles/63201/TelnetSocket 
    'The basic algorithm used here is: 
    ' Iterate across the incoming bytes 
    ' Assume that an IAC (byte 255) is the first of a two- or three-byte Telnet command and handle it: 
    ' If two IACs are together, they represent one data byte 255 
    ' Ignore the Go-Ahead command 
    ' Respond WONT to all DOs and DONTs 
    ' Respond DONT to all WONTs 
    ' Respond DO to WILL ECHO and WILL SUPPRESS GO-AHEAD 
    ' Respond DONT to all other WILLs 
    ' Any other bytes are data; ignore nulls, and shift the rest as necessary 
    ' Return the number of bytes that remain after removing the Telnet command and ignoring nulls 
    Private Function Negotiate(ByVal data As Byte(), ByVal length As Int32) As Int32 
    Dim index As Int32 = 0 
    Dim remaining As Int32 = 0 

    While (index < length) 
     If (data(index) = TelnetBytes.IAC) Then 
     Try 
      Select Case data(index + 1) 
      Case TelnetBytes.IAC 
       data(remaining) = data(index) 
       remaining += 1 
       index += 2 

      Case TelnetBytes.GA 
       index += 2 

      Case TelnetBytes.WDO 
       data(index + 1) = TelnetBytes.WONT 
       SyncLock ServerStream 
       ServerStream.Write(data, index, 3) 
       End SyncLock 
       index += 3 

      Case TelnetBytes.DONT 
       data(index + 1) = TelnetBytes.WONT 
       SyncLock ServerStream 
       ServerStream.Write(data, index, 3) 
       End SyncLock 
       index += 3 

      Case TelnetBytes.WONT 
       data(index + 1) = TelnetBytes.DONT 
       SyncLock ServerStream 
       ServerStream.Write(data, index, 3) 
       End SyncLock 
       index += 3 

      Case TelnetBytes.WILL 
       Dim action As Byte = TelnetBytes.DONT 

       Select Case data(index + 2) 

       Case TelnetBytes.ECHO 
        action = TelnetBytes.WDO 

       Case TelnetBytes.SUPP 
        action = TelnetBytes.WDO 

       End Select 
       data(index + 1) = action 
       SyncLock ServerStream 
       ServerStream.Write(data, index, 3) 
       End SyncLock 
       index += 3 

      End Select 

     Catch ex As System.IndexOutOfRangeException 
      index = length 
     End Try 
     Else 
     If (data(index) <> 0) Then 
      data(remaining) = data(index) 
      remaining += 1 
     End If 
     index += 1 
     End If 
    End While 

    Return remaining 
    End Function 

    Private Structure TelnetBytes 

    'Commands 
    Public Const GA As Byte = 249 
    Public Const WILL As Byte = 251 
    Public Const WONT As Byte = 252 
    Public Const WDO As Byte = 253 'Actually just DO but is protected word in vb.net 
    Public Const DONT As Byte = 254 
    Public Const IAC As Byte = 255 

    'Options 
    Public Const ECHO As Byte = 1 
    Public Const SUPP As Byte = 3 
    End Structure 
End Class 
+1

編輯陳述我的意圖,這應該適用於大多數,但不是寫無論如何都是「專業」。 – 2015-10-02 19:52:54

相關問題