Click here to Skip to main content
6,295,667 members and growing! (14,821 online)
Email Password   helpLost your password?
General Programming » Internet / Network » Network     Intermediate License: The Code Project Open License (CPOL)

Quick tool : A minimalistic Telnet library

By Tom Janssens

Send commands to your servers from your programs using the Telnet protocol
C# 2.0, Windows, Win Mobile, .NET 2.0, .NET 3.0, WinForms, VS2005, Dev
Posted:6 Jun 2007
Views:32,117
Bookmarked:40 times
Announcements
Loading...
 
Search    
Advanced Search
printPrint   Broken Article?Report       add Share
  Discuss Discuss   Recommend Article Email
24 votes for this article.
Popularity: 6.38 Rating: 4.62 out of 5
2 votes, 8.3%
1

2

3
4 votes, 16.7%
4
18 votes, 75.0%
5

Introduction

This article provides a minimalistic Telnet interface. Possible applications of this class include :

  • A Telnet console
  • A Windows GUI around some UNIX commands that need to be executed on a server
  • A program that executes scripts (scripted telnet)
This example offers both a minimal console, and a possibility to use a script, using file piping.

Background

A little while ago one of my clients had the problem that a person who was managing a system using UNIX scripts (HP-UX) was leaving the company. This person was not to be replaced by a new employee, so his functions would have to be done by several other persons.

When estimating the cost of teaching the other people how to use UNIX, we made some calculations, and found a much cheaper solution: we built a simple Windows program that contained a GUI for every script used.

The user simply has to press some buttons, select some values and press the "Start" button. When the user presses the start button the UNIX commands are built using the parameters from the GUI, and sent to the server using Telnet.

Since I remember spending quite a few hours figuring out the minimal implementation of the Telnet protocol, I decided to do a simple rewrite for the users of codeproject.

Using the code

The class is actually quite simple to use. Please take a look at the example code :

//create a new telnet connection to hostname "gobelijn" on port "23"

TelnetConnection tc = new TelnetConnection("gobelijn", 23);

//login with user "root",password "rootpassword", using a timeout of 100ms, 

//and show server output

string s = tc.Login("root", "rootpassword",100);
Console.Write(s);

// server output should end with "$" or ">", otherwise the connection failed

string prompt = s.TrimEnd();
prompt = s.Substring(prompt.Length -1,1);
if (prompt != "$" && prompt != ">" )
    throw new Exception("Connection failed");

prompt = "";

// while connected

while (tc.IsConnected && prompt.Trim() != "exit" )
{
    // display server output

    Console.Write(tc.Read());

    // send client input to server

    prompt = Console.ReadLine();
    tc.WriteLine(prompt);

    // display server output

    Console.Write(tc.Read());
}

Console.WriteLine("***DISCONNECTED");
Console.ReadLine();

I suppose this is self-explanatory, isn't it ? Create the Telnet connection, login, send the login output to the screen, and while connected send serveroutput to the screen, read a command from the commandline, and again, send the serveroutput to the screen.
If the command is "exit" then the loop needs to finish.

Instead of reading the input from the console, the input can also be piped from a script: if the script was named telnetstuff.txt then execute the script as follows :

MinimalisticTelnet < telnetstuff.txt > output.txt

The result will be inside the file output.txt. Currently the servername, port, username and password is hardcoded, but it should be a piece of cake to change this into command line parameters.

How does it work

The TelnetConnection parses every byte received from the TcpClient, and if a byte series is a Telnet option request (DO, DONT, WILL, WONT), the client simply responds that the option is not available by sending (DONT, WONT) in return.

The only exception to these responses is the command SGA: suppress go ahead, since this command allows async traffic.

Points of Interest

The TelnetConnection.Read function assumes that if there is no data available for more then TimeOutMs milliseconds, the output is complete.

The login works by parsing the server output after the initial connection. It will look for a colon ":" in the screen output, and will send username and password after the colon.

To check if the connection succeeded, I look for whether the serveroutput ends with a "$" or a ">". If your Telnet server has another prompt, please replace this.

Votes & Comments

The votes & comments on my previous article gave me the motivation to publish a new article, so please keep your votes & comments coming !!

History

  • 2007-06-06: First version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Tom Janssens


Member
Tom Janssens, owner of Core, a software and consultancy company.
Father of two sons named Quinten & Matisse, and married to a beautiful woman named Liesbeth.

My LinkedIn profile
Occupation: Founder
Company: Core bvba
Location: Belgium Belgium

Other popular Internet / Network articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 25 of 32 (Total in Forum: 32) (Refresh)FirstPrevNext
QuestionProblem with SendTelnetData [modified] Pinmemberjeanosorio6:46 21 Apr '09  
AnswerRe: Problem with SendTelnetData PinmemberTom Janssens22:43 21 Apr '09  
GeneralThanks Pinmemberalex_t9:04 14 Apr '09  
GeneralRe: Thanks PinmemberTom Janssens10:15 14 Apr '09  
GeneralFailed to connect:no login prompt Pinmemberkrsk4u23:22 6 Oct '08  
AnswerRe: Failed to connect:no login prompt PinmemberTom Janssens0:39 23 Oct '08  
GeneralYour telnet client rejected our request to use char-at-a-time mode [modified] PinmemberJ1MPIC3:13 18 Jun '08  
GeneralRe: Your telnet client rejected our request to use char-at-a-time mode PinmemberJ1MPIC9:55 24 Jun '08  
AnswerRe: Your telnet client rejected our request to use char-at-a-time mode PinmemberTom Janssens21:27 18 Aug '08  
GeneralError with the server output PinmemberAmer Azzaz1:23 9 May '08  
AnswerRe: Error with the server output PinmemberTom Janssens4:36 9 Jun '08  
GeneralParseTelnet function generates malformed packet PinmemberHStidsen1:07 20 Sep '07  
GeneralRe: ParseTelnet function generates malformed packet PinmemberTom Janssens5:28 7 Dec '07  
GeneralRe: ParseTelnet function generates malformed packet PinmemberDarked23:13 9 Apr '08  
AnswerRe: ParseTelnet function generates malformed packet PinmemberHStidsen2:45 10 Apr '08  
GeneralRe: ParseTelnet function generates malformed packet PinmemberDarked2:58 10 Apr '08  
AnswerRe: ParseTelnet function generates malformed packet PinmemberMember 30373263:15 1 Nov '08  
Question"Failed to connect : no password prompt" Pinmemberpraveenkumar palla21:25 18 Sep '07  
GeneralRe: "Failed to connect : no password prompt" PinmemberTom Janssens5:26 7 Dec '07  
AnswerRe: "Failed to connect : no password prompt" [modified] PinmemberAndreas Schoeneck0:39 30 Apr '08  
GeneralThanks Pinmemberzitun5:18 18 Sep '07  
GeneralRe: Thanks PinmemberTom Janssens5:25 7 Dec '07  
GeneralUsing your telnet thing Pinmemberflaminidavid21:33 6 Sep '07  
GeneralRe: Using your telnet thing PinmemberTom Janssens5:24 7 Dec '07  
QuestionClosing the connection Pinmemberjpvolkmann0:39 1 Aug '07  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 6 Jun 2007
Editor: Chris Maunder
Copyright 2007 by Tom Janssens
Everything else Copyright © CodeProject, 1999-2009
Web10 | Advertise on the Code Project