2013年4月12日 星期五

Telnet C# - 簡單好用的 C# Telnet lib

Telnet C# 是一款 C# 語言上用來模擬執行 Telnet 的 Open Source Library,可以設定對指定的 IP、Port連線,並可在成功連線後,等待指定的訊息出現以及送出相對應的訊息,可以說是一款相當簡單好用的 Lib。程式最後一次更新的日期是 2011 年 7 月,算是不會太舊的 Lib,目前使用上沒有什麼問題。

Lib 放置於 CodePlex 網站上,官方網站 Telnet C#


使用範例如下 (節錄自 Telnet C# > Documentation > Example)

Terminal tn = new Terminal("giga", 23, 10, 80, 40); // hostname, port, timeout [s], width, height

tn.Connect(); // physical connection
do 
{
    f = tn.WaitForString("Login");
    if (f==null) 
        break; // this little clumsy line is better to watch in the debugger
    Console.WriteLine(tn.VirtualScreen.Hardcopy().TrimEnd());
    tn.SendResponse("telnet", true); // send username
    f = tn.WaitForString("Password");
    if (f==null) 
        break;
    Console.WriteLine(tn.VirtualScreen.Hardcopy().TrimEnd());
    tn.SendResponse("telnet", true); // send password 
    f = tn.WaitForString(">");
        break;
    tn.SendResponse("df", true); // send Shell command
    if (tn.WaitForChangedScreen())
        Console.WriteLine(tn.VirtualScreen.Hardcopy().TrimEnd());
} while (false);
tn.Close(); // physically close on TcpClient

使用 Terminal 建構子參數來設定 Hostname 或 IP,以及 Port 、 Timeout …等等。

Terminal.WariForString(string) 用於等待指定的 string 出現,會一直等待直至 Timeout,若沒出現指定的 string 則會回傳 null。

Terminal.SendResponse(string, bool) 用於送出 string,並可設定是否要送出換行(Enter)訊息。

沒有留言:

張貼留言