O'Reilly logo

Ruby Cookbook by Leonard Richardson, Lucas Carlson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

14.9. Being a Telnet Client

Problem

You want to connect to a telnet service or use telnet to get low-level access to some other kind of server.

Solution

Use the Net::Telnet module in the Ruby standard library.

The following code uses a Telnet object to simulate an HTTP client. It sends a raw HTTP request to the web server at http://www.oreilly.com. Every chunk of data received from the web server is passed into a code block, and its size is added to a tally. Eventually the web server stops sending data, and the telnet session times out.

	require 'net/telnet'

	webserver = Net::Telnet::new('Host' => 'www.oreilly.com',
	                             'Port' => 80,
	                             'Telnetmode' => false)

	size = 0
	webserver.cmd("GET / HTTP/1.1\nHost: www.oreilly.com\n") do |c|
	  size += c.size
	  puts "Read #{c.size} bytes; total #{size}"
	end
	# Read 1431 bytes; total 1431
	# Read 1434 bytes; total 2865
	# Read 1441 bytes; total 4306
	# Read 1436 bytes; total 5742
	# …
	# Read 1430 bytes; total 39901
	# Read 2856 bytes; total 42757
	# /usr/lib/ruby/1.8/net/telnet.rb:551:in 'waitfor':
	#   timed out while waiting for more data (Timeout::Error)

Discussion

Telnet is a lightweight protocol devised for connecting to a generic service running on another computer. For a long time, the most commonly exposed service was a Unix shell: you would "telnet in" to a machine on the network, log in, and run shell commands on the other machine as though it were local.

Because telnet is an insecure protocol, it's very rare now to use it for remote login. Everyone uses SSH ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required