我試圖自動執行一些需要通過VB.NET在遠程unix服務器上執行的unix命令。目前我會打開命令提示符,連接到主機用telnet,發出我的命令並退出會話。作爲一個更大的項目的一部分,我想自動化這個。我一直在研究不同的方法來設置與VB的網絡連接幾天,現在我沒有接近解決方案。我已經嘗試使用第三方dll庫(如在這裏建議:executing commands on unix server via visual basic application)作爲我的項目的參考,但我得到一個超時錯誤,我試圖簡單地獲取目錄列表作爲測試後無法解決。如何使用VB.NET設置TCP連接到unix服務器
我試着用TcpClient自己編碼,但是我的代碼在第一個響應之後掛起(請參閱下面的代碼&輸出)。除了過去幾天我讀過的內容,我沒有網絡,端口或套接字的使用經驗。我沒有關於連接的安全問題,我在公司的內部網上。任何幫助解決這個問題將不勝感激。
代碼:主要來自MSDN VB例如剪切和粘貼的TcpClient
Dim message As String
'Connect to Server
Dim port As Int32 = 23
Dim client As New TcpClient(unixServer, port)
'Send username to login to server
message = userName & " \n"
Dim data As [Byte]() = System.Text.Encoding.ASCII.GetBytes(message)
Dim stream As NetworkStream = client.GetStream
stream.Write(data, 0, data.Length)
TextBox2.AppendText("Sent: {0} " & message & vbCrLf)
data = New [Byte](256) {}
Dim responseData As [String] = String.Empty
Dim bytes As Int32 = stream.Read(data, 0, data.Length)
responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes)
TextBox2.AppendText("Recieved: {0} " & responseData & vbCrLf)
'Send password to login to server
message = passWord & " \n"
data = New [Byte](256) {}
data = System.Text.Encoding.ASCII.GetBytes(message)
stream.Write(data, 0, data.Length)
TextBox2.AppendText("Sent: {0} " & message & vbCrLf)
data = New [Byte](256) {}
bytes = stream.Read(data, 0, data.Length)
responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes)
TextBox2.AppendText("Recieved: {0} " & responseData & vbCrLf)
'Send return key to start new line
message = "\n"
data = New [Byte](256) {}
data = System.Text.Encoding.ASCII.GetBytes(message)
stream.Write(data, 0, data.Length)
TextBox2.AppendText("Sent: {0} " & message & vbCrLf)
data = New [Byte](256) {}
bytes = stream.Read(data, 0, data.Length)
responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes)
TextBox2.AppendText("Recieved: {0} " & responseData & vbCrLf)
'Get directory listing
message = "ls -lrt"
data = New [Byte](256) {}
data = System.Text.Encoding.ASCII.GetBytes(message)
stream.Write(data, 0, data.Length)
TextBox2.AppendText("Sent: {0} " & message & vbCrLf)
data = New [Byte](256) {}
bytes = stream.Read(data, 0, data.Length)
responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes)
TextBox2.AppendText("Recieved: {0} " & responseData & vbCrLf)
stream.Close()
client.Close()
輸出到文本框:
發送:{0}的用戶名\ n
收到:{0}? ?? ??#$ ??
發送:{0}密碼\ n
你不發送「\ n」,你發送vbcrlf或chr(10)作爲回車 – user2930100