我有一台机器,我通过传递ip地址和端口号在cmd.exe中使用TELNET命令连接。连接成功后,我传递了一些命令来完成任务。但每次都打开命令提示符做上面提到的任务不是客户想要的。他们希望这个过程是自动化的。有了c#中Socket程序的一些经验,我尝试通过套接字程序使用ip地址和端口号连接并传递命令来获取任务完成但是套接字编程没有完成任务。
所以我的问题是,是否可以使用c#中的Socket编程在cmd.exe中通过telnet命令完成相同的任务,如果是,如何?
请帮帮我。 提前谢谢。
这是我在c#中连接到机器的代码,但它无法执行所需的任务。它无法执行cmd.exe中TELNET命令正在执行的任务..
int intport;
int.TryParse(port1, out intport);
TcpClient client = new TcpClient();
textfileSaveLocation = "some location";
try
{
using (StreamWriter writer = new StreamWriter(textfileSaveLocation, true))
{
writer.WriteLine("Before Connection !");
}
client.Connect(new IPEndPoint(IPAddress.Parse(ip), intport));
Thread.Sleep(5000);
using (StreamWriter writer = new StreamWriter(textfileSaveLocation, true))
{
writer.WriteLine("Connected To Machine !");
}
}
catch (Exception ex)
{
// Log the error here.
client.Close();
using (StreamWriter writer = new StreamWriter(textfileSaveLocation, true))
{
writer.WriteLine("Connection Error !");
}
continue;
}
try
{
using (NetworkStream stream = client.GetStream())
{
byte[] username = Encoding.ASCII.GetBytes(user + "\r\n");
stream.Write(username, 0, username.Length);
Thread.Sleep(5000);
using (StreamWriter writer = new StreamWriter(textfileSaveLocation, true))
{
writer.WriteLine("UserName Enetered !");
}
byte[] password = Encoding.ASCII.GetBytes(pass + "\r\n");
stream.Write(password, 0, password.Length);
Thread.Sleep(5000);
using (StreamWriter writer = new StreamWriter(textfileSaveLocation, true))
{
writer.WriteLine("Password Passed !");
}
byte[] terminal = Encoding.ASCII.GetBytes(port2 + "\r\n");
stream.Write(terminal, 0, terminal.Length);
Thread.Sleep(5000);
using (StreamWriter writer = new StreamWriter(textfileSaveLocation, true))
{
writer.WriteLine("Terminal Value Entered !");
}
client.Close();
答案 0 :(得分:1)
是的,这是可能的。
Google搜索关键字:C#Telnet CLient
第一个结果:http://www.codeproject.com/Articles/19071/Quick-tool-A-minimalistic-Telnet-library
答案 1 :(得分:1)
可以使用TcpClient:
编写简单的客户端var client = new TcpClient("localhost", 25);
const string crlf = "\r\n";
var networkStream = client.GetStream();
var streamReader = new StreamReader(client.GetStream());
// Receive data from server
var serverResponse = streamReader.ReadLine();
Console.WriteLine("Server: " + serverResponse);
// Send data to server
const string data = "Command to server " + crlf;
byte[] buffer = System.Text.Encoding.ASCII.GetBytes(data);
networkStream.Write(buffer, 0, buffer.Length);
networkStream.Close();
client.Close();
答案 2 :(得分:0)
让我们重温死老(问题)。
我恰恰相反,正在寻找一种使用SuperSocket进行套接字编程的方法。我试过了,它适用于cmd的telnet。