|
|
|
|
Ruby provides a set of classes to facilitate writing clients for:
- File Transfer Protocol (FTP)
- HyperText Transfer Protocol (HTTP)
- Post Office Protocol (POP)
- Simple Mail Transfer Protocol (SMTP)
- Telnet
HTTP, POP, and SMTP are layered on top of a helper class,
lib/net/protocol . Although we don't document the Protocol
class here, you should probably study it if you are considering
writing your own network client.
class Net::FTP
|
Parent:
|
Object
|
Version:
|
1.6
|
|
Index:
new
open
Server commands
close
closed?
connect
debug_mode
debug_mode=
dir
getbinaryfile
gettextfile
lastresp
list
login
ls
mtime
passive
passive=
putbinaryfile
puttextfile
resume
resume=
retrbinary
retrlines
return_code
storbinary
storlines
welcome
require 'net/ftp'
ftp = Net::FTP.new('ftp.netlab.co.jp')
ftp.login
files = ftp.chdir('pub/lang/ruby/contrib')
files = ftp.list('n*')
ftp.getbinaryfile('nif.rb-0.91.gz', 'nif.gz', 1024)
ftp.close
|
The net/ftp library implements a File Transfer Protocol (FTP)
client.
|
FTP_PORT
|
|
Default port for FTP connections (21). |
class methods
|
new
|
FTP.new( host=nil ,
user=nil ,
passwd=nil ,
acct=nil ) -> aSession
|
|
Creates and returns a new FTP object. If the host parameter is
not nil , a connection is made to that
host. Additionally, if the user parameter is not nil , the
given user name, password, and (optionally) account are
used to log in. See the description of FTP#login
on page 484.
|
open
|
FTP.open( host,
user=nil ,
passwd=nil ,
acct=nil ) -> aSession
|
|
A synonym for FTP.new , but with a mandatory host
parameter.
|
instance methods
|
Server commands
|
aSession.acct( account )
aSession.chdir( dir )
aSession.delete( remoteFile )
aSession.mdtm( remoteFile ) -> aString
aSession.mkdir( dir )
aSession.nlst( dir=nil ) -> anArray
aSession.rename( fromname, toname )
aSession.rmdir( dir )
aSession.pwd -> aString
aSession.size( remoteFile ) -> anInteger
aSession.status -> aString
aSession.system -> aString
|
|
Issues the corresponding server command and returns the result.
|
close
|
aSession.close
|
|
Closes the current connection.
|
closed?
|
aSession.closed? -> true or false
|
|
Returns true if the current connection is closed.
|
connect
|
aSession.connect( host,
port=FTP_PORT )
|
|
Establishes an FTP connection to host, optionally overriding
the default port. If the environment variable
SOCKS_SERVER
is set, sets up the connection through
a SOCKS proxy. Raises an exception (typically
Errno::ECONNREFUSED ) if the connection
cannot be established.
|
debug_mode
|
aSession.debug_mode -> true or false
|
|
Returns the current debug mode.
|
debug_mode=
|
aSession.debug_mode = true or false
|
|
If the debug mode is true , all traffic to and from the
server is written to $stdout .
|
dir
|
aSession.dir( [pattern]*
) -> anArray
aSession.dir( [pattern]*
) {| line | block }
|
|
Synonym for FTP#list .
|
getbinaryfile
|
aSession.getbinaryfile(
remotefile, localfile, blocksize,
callback=nil )
aSession.getbinaryfile(
remotefile, localfile, blocksize )
{| data | block }
|
|
Retrieves remotefile in binary mode, storing the result in
localfile. If callback or an associated block is
supplied, calls it, passing in the retrieved data in
blocksize chunks.
|
gettextfile
|
aSession.gettextfile(
remotefile, localfile,
callback=nil )
aSession.gettextfile(
remotefile, localfile )
{| data | block }
|
|
Retrieves remotefile in ASCII (text) mode, storing the result in
localfile. If callback or an associated block is
supplied, calls it, passing in the retrieved data one line at a time.
|
lastresp
|
aSession.lastresp -> aString
|
|
Returns the host's last response.
|
list
|
aSession.list( [pattern]*
) -> anArray
aSession.list( [pattern]*
) {| line | block }
|
|
Fetches a directory listing of files matching the given
pattern(s). If a block is associated with the call, invokes it
with each line of the result. Otherwise, returns the result as an
array of strings.
|
login
|
aSession.login( user="anonymous",
passwd=nil , acct=nil ) -> aString
|
|
Logs into
the remote host. aSession must have been previously
connected. If user is the string ``anonymous'' and the
password is nil , a password of user@host is
synthesized. If the acct parameter is not nil , an FTP
ACCT command is sent following the successful
login. Raises an exception on error (typically
Net::FTPPermError ).
|
ls
|
aSession.ls( [pattern]*
) -> anArray
aSession.ls( [pattern]*
) {| line | block }
|
|
Synonym for FTP#list .
|
mtime
|
aSession.mtime( remoteFile,
local=false ) -> aTime
|
|
Returns the last-modified time of remoteFile, interpreting
the server's response as a GMT time if local is
false , or as a local time otherwise.
|
passive
|
aSession.passive -> true or false
|
|
Returns the state of the passive flag.
|
passive=
|
aSession.passive = true or false
|
|
Puts the connection into passive mode if true .
|
putbinaryfile
|
aSession.putbinaryfile(
localfile, remotefile, blocksize,
callback=nil )
aSession.putbinaryfile(
localfile, remotefile, blocksize )
{| data | block }
|
|
Transfers localfile to the server in binary mode, storing
the result in
remotefile. If callback or an associated block is
supplied, calls it, passing in the transmitted data in
blocksize chunks.
|
puttextfile
|
aSession.puttextfile(
localfile, remotefile,
callback=nil )
aSession.puttextfile(
localfile, remotefile, blocksize )
{| data | block }
|
|
Transfers localfile to the server in ASCII (text) mode,
storing the result in remotefile. If callback or an
associated block is supplied, calls it, passing in the
transmitted data one line at a time.
|
resume
|
aSession.resume -> true or false
|
|
Returns the status of the resume flag (see
FTP#resume= ). Default is false .
|
resume=
|
aSession.resume=aBoolean
|
|
Sets the status of the resume flag. When resume is
true , partially received files will resume where they
left off, instead of starting from the beginning again. This is
done by sending a REST command (REST art incomplete
transfer) to the server.
|
retrbinary
|
aSession.retrbinary(
cmd, blocksize ) {| data | block }
|
|
Puts the connection into binary (image) mode, issues the given
command, and fetches the data returned, passing it to the associated
block in chunks of blocksize characters. Note that
cmd is a server command (such as ``RETR myfile'').
|
retrlines
|
aSession.retrlines(cmd) {| line | block }
|
|
Puts the connection into ASCII (text) mode, issues the given
command, and passes the resulting data, one line at a time, to the
associated block. If no block is given, prints the lines. Note that
cmd is a server command (such as ``RETR myfile'').
|
return_code
|
aSession.return_code -> aFixnum
|
|
Returns the return code from the last operation.
|
storbinary
|
aSession.storbinary( cmd, fileName, blocksize,
callback=nil )
aSession.storbinary( cmd, fileName, blocksize )
{| data | block }
|
|
Puts the connection into binary (image) mode, issues the given
server-side command (such as ``STOR myfile''), and sends the
contents of the file named fileName to the server. If the optional
block is given, or if the callBack parameter is a Proc ,
also passes it the data, in chunks of blocksize characters.
|
storlines
|
aSession.storlines( cmd, fileName,
callback=nil )
aSession.storlines( cmd, fileName )
{| data | block }
|
|
Puts the connection into ASCII (text) mode, issues the given
server-side command (such as ``STOR myfile''), and sends the
contents of the file named fileName to the server, one line at a
time. If the optional
block is given, or if the callBack parameter is a Proc ,
also passes it the lines.
|
welcome
|
aSession.welcome -> aString
|
|
Returns the host's welcome message.
|
|
class Net::HTTP
|
Parent:
|
Net::Protocol
|
Version:
|
1.6
|
|
Index:
new
port
start
get
head
post
start
require 'net/http'
h = Net::HTTP.new('www.pragmaticprogrammer.com', 80)
resp, data = h.get('/index.html', nil )
puts "Code = #{resp.code}"
puts "Message = #{resp.message}"
resp.each {|key, val| printf "%-14s = %-40.40s\n", key, val }
p data[0..55]
|
produces:
Code = 200
Message = OK
last-modified = Wed, 29 May 2002 11:08:01 GMT
connection = close
content-type = text/html
etag = "804d98-255c-3cf4b691"
date = Sun, 09 Jun 2002 05:15:10 GMT
server = Rapidsite/Apa/1.3.20 (Unix) FrontPage/4.
content-length = 9564
accept-ranges = bytes
"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional"
|
The net/http library provides a simple client to fetch headers
and Web page contents using the HTTP protocol.
The get , post , and head requests raise
exceptions on any error, including some HTTP status responses that
would normally be considered recoverable. There are two ways of
handling these.
- Each method has a corresponding version
get2 ,
post2 , or head2 that does not raise an
exception. These versions are documented in the source.
- Recoverable errors raise a
Net::ProtoRetriableError exception. This exception contains a
data attribute containing the response returned by the
server.
The code below illustrates the handling of an HTTP status 301, a redirect.
It uses Tomoyuki Kosimizu's URI
package, available in the RAA.
h = Net::HTTP.new(ARGV[0] || 'www.ruby-lang.org', 80)
url = ARGV[1] || '/'
begin
resp, data = h.get(url, nil) { |a| }
rescue Net::ProtoRetriableError => detail
head = detail.data
if head.code == "301"
uri = URI.create(head['location'])
host = uri['host']
url = uri['path']
port = uri['port']
h.finish
h = Net::HTTP.new(host, port)
retry
end
end
|
class methods
|
new
|
Net::HTTP.new( host='localhost',
port=80,
proxy=nil , proxy_port=nil )
-> aSession
|
|
Creates and returns a new HTTP object. No connection is
made until HTTP#start is called.
|
port
|
Net::HTTP.port -> aFixnum
|
|
Returns the default HTTP port (80).
|
start
|
Net::HTTP.start( host=nil , port=80 ) Net::HTTP.start( host=nil , port=80 )
{| aSession | block }
|
|
Equivalent to Net::HTTP.new(host, port).start .
|
instance methods
|
get
|
aSession.get( path, headers=nil , dest="" )
-> anArray
aSession.get( path, headers=nil ) {| result | block }
-> anArray
|
|
Retrieves headers and content from the specified path on
the host specified when aSession was created. If specified, the
headers parameter is a Hash containing additional
header names and values to be sent with the request. The method
returns a two-element array. The first element is an
HTTPResponse object (documented in the next section).
The second element is the page's content.
The page's content is also passed to the << method of
the dest parameter, or to the block if specified. This
result is built network block by network block, not line by line.
An exception is raised
if an error is encountered. Multiple get calls may be
made on aSession. Unless Protocol#finish is explicitly
called, the connection will use the HTTP/1.1 keep-alive
protocol, and will not close between requests.
|
head
|
aSession.head( path, headers=nil )
-> aHash
|
|
Retrieves headers from the specified path on the host
specified when aSession was created. If specified, the
headers parameter is a hash containing additional
header names and values to be sent with the request. The method
returns a hash of received headers. An exception is raised if
an error is encountered. Multiple head calls may be
made on aSession.
|
post
|
aSession.post( path, data, headers=nil ,
dest="" ) -> anArray
aSession.post( path, data, headers=nil )
{| result | block }
-> anArray
|
|
Sends data to path using an HTTP POST
request. headers is a hash containing additional
headers. Assigns the result to data or to the block, as
for Net_HTTP#get . Returns a two-element array containing
an HTTPResponse object and the reply body.
|
start
|
aSession.start
aSession.start {| aSession | block }
|
|
Establishes a connection to the host associated with
aSession. (start is actually a method in
Net::Protocol , but its use is required in HTTP objects.) In
the block form, closes the session at the end of the block.
|
|
Index:
[ ]
[ ]=
code
each
key?
message
Represents an HTTP response to a GET or POST request.
instance methods
|
[ ]
|
aSession[ aKey ]
-> aString
|
|
Returns the header corresponding to the case-insensitive
key. For example, a key of ``Content-type'' might return
``text/html''.
|
[ ]=
|
aSession[ aKey ] = aString
|
|
Sets the header corresponding to the case-insensitive
key.
|
code
|
aSession.code -> aString
|
|
Returns the result code from the request (for example, ``404'').
|
each
|
aSession.each {| key, val | block }
|
|
Iterates over all the header key-value pairs.
|
key?
|
aSession.key?( aKey ) -> true or false
|
|
Returns true only if a header with the given key exists.
|
message
|
aSession.message -> aString
|
|
Returns the result message from the request (for example, ``Not found'').
|
class Net::POP
|
Parent:
|
Net::Protocol
|
Version:
|
1.6
|
|
Index:
new
each
finish
mails
start
require 'net/pop'
pop = Net::POP3.new('server.ruby-stuff.com')
pop.start('user', 'secret') do |pop|
msg = pop.mails[0]
# Print the 'From:' header line
puts msg.header.split("\r\n").grep(/^From: /)
# Put message to $stdout (by calling <<)
puts "\nFull message:\n"
msg.all($stdout)
end
|
produces:
From: dummy msg for Andy
Full message:
From: dummy msg for Andy
looks-better: on dave's box
That's all folks!
|
The net/pop library provides a simple client to fetch and
delete mail on a Post Office Protocol (POP) server.
The class Net::POP3 is used to access a POP server, returning
a list of Net::POPMail objects, one per message stored on the
server. These POPMail objects are then used to fetch and/or
delete individual messages.
The library also provides an alternative to the POP3 class that
performs APOP authentication.
class methods
|
new
|
HTTP.new( host='localhost', port=110 )
-> aSession
|
|
Creates and returns a new POP3 object. No connection is
made until POP3#start is called.
|
instance methods
|
each
|
aSession.each {| popmail | block }
|
|
Calls the associated block once for each e-mail stored on the
server, passing in the corresponding POPMail object.
|
finish
|
aSession.finish -> true or false
|
|
Closes the pop connection. Some servers require that a
connection is closed before they honor actions such as deleting
mail. Returns false if the connection was never used.
|
mails
|
aSession.mails -> anArray
|
|
Returns an array of POPMail objects, where each object
corresponds to an e-mail message stored on the server.
|
start
|
aSession.start( user, password )
aSession.start( user, password ) {| pop | block }
|
|
Establishes a connection to the pop server, using the supplied
username and password. Fetches a list of mail held on the server,
which may be accessed using the POP3#mails and
POP3#each methods. In block form, passes aSession to the
block, and closes the connection using finish when the
block terminates.
|
class Net::APOP
|
Parent:
|
Net::POP3
|
Version:
|
1.6
|
|
Index:
start
instance methods
|
start
|
aSession.start( user, password
)
|
|
Establishes a connection to the APOP server.
|
class Net::POPMail
|
Parent:
|
Object
|
Version:
|
1.6
|
|
Index:
all
delete
delete!
header
size
top
uidl
instance methods
|
all
|
aSession.all -> aString
aSession.all( dest )
aSession.all {| aString | block }
|
|
Fetches the corresponding e-mail from the server. With no argument
or associated block, returns the e-mail as a string. With an
argument but no block, appends the e-mail to dest by
invoking dest
<< for each line in the e-mail. With
an associated block, invokes the block once for each line in the e-mail.
|
delete
|
aSession.delete
|
|
Deletes the e-mail from the server.
|
delete!
|
aSession.delete!
|
|
Synonym for POPMail#delete .
|
header
|
aSession.header -> aString
|
|
Returns the header lines for the corresponding e-mail message.
|
size
|
aSession.size -> aFixnum
|
|
Returns the size in bytes of the corresponding e-mail.
|
top
|
aSession.top( lines ) -> aString
|
|
Returns the header lines, plus lines message lines for the
corresponding e-mail message.
|
uidl
|
aSession.uidl -> aString
|
|
Returns the server-specific unique identifier for the
corresponding e-mail.
|
class Net::SMTP
|
Parent:
|
Net::Protocol
|
Version:
|
1.6
|
|
Index:
new
start
ready
sendmail
start
require 'net/smtp'
# --- Send using class methods
msg = [ "Subject: Test\n", "\n", "Now is the time\n" ]
Net::SMTP.start do |smtp|
smtp.sendmail( msg, 'dave@localhost', ['dave'] )
end
# --- Send using SMTP object and an adaptor
smtp = Net::SMTP.new
smtp.start('pragprog.com')
smtp.ready('dave@localhost', 'dave') do |a|
a.write "Subject: Test1\r\n"
a.write "\r\n"
a.write "And so is this"
end
|
The net/smtp library provides a simple client to send
electronic mail using the Simple Mail Transfer Protocol (SMTP).
class methods
|
new
|
Net::SMTP.new( server='localhost',
port=25 ) -> aSession
|
|
Returns a new SMTP object connected to the given server and
port.
|
start
|
Net::SMTP.start( server='localhost', port=25,
domain=ENV['HOSTNAME'], acct=nil ,
passwd=nil , authtype=:cram_md5 ) -> aSession
Net::SMTP.start( server='localhost', port=25,
domain=ENV['HOSTNAME'], acct=nil ,
passwd=nil , authtype=:cram_md5 )
{| smtp | block }
|
|
Equivalent to Net::SMTP.new(server,
port).start(...) . For an explanation of the remainder
of the parameters, see the instance method Net_SMTP#start .
Creates a new SMTP object. The domain parameter will be
used in the initial HELO or EHLO transaction with the
SMTP server. In the block form, the smtp object is passed
into the block. When the block terminates, the session is closed.
|
instance methods
|
ready
|
aSession.ready( from, to )
{| anAdaptor | block }
|
|
Equivalent to sendmail(from, to) { ...} .
Sends header and body lines to the sendmail server. The
from parameter is used as the sender's name in the
MAIL FROM: command, and the to is either a string or
an array of strings containing the recipients
for the RCPT TO: command.
The block is passed an adaptor object. Lines are
sent to the server by calling the adaptor's write method. The
terminating '.' and QUIT are sent automatically.
|
sendmail
|
aSession.sendmail( src, from, to )
|
|
Sends header and body lines to the sendmail server. The
from parameter is used as the sender's name in the
MAIL FROM: command, and to is either a string or an
array of strings containing the
recipients for the RCPT TO: command.
Lines to be sent are fetched by invoking src
.each . The
terminating '.' and QUIT are sent automatically.
|
start
|
aSession.start( domain=ENV['HOSTNAME'], acct=nil ,
passwd=nil , authtype=:cram_md5 ) -> true or false
aSession.start( domain=ENV['HOSTNAME'], acct=nil ,
passwd=nil , authtype=:cram_md5 )
{| smtp | block }
-> true or false
|
|
Starts an SMTP session by connecting to the given domain
(host). If acct and passwd are given,
authentication will be attempted using the given
authentication type (:plain or :cram_md5 ). If a
block is supplied, it will be invoked with aSession as a
parameter. The connection will be closed when the block terminates.
|
|
class Net::Telnet
|
Parent:
|
[Socket]
|
Version:
|
1.6
|
|
Index:
new
binmode
binmode=
cmd
login
print
telnetmode
telnetmode=
waitfor
write
Connect to a localhost , run the ``date'' command, and disconnect.
require 'net/telnet'
|
|
tn = Net::Telnet.new({})
|
tn.login "guest", "secret"
|
tn.cmd "date"
|
� |
"date\r\nSun Jun 9 00:15:20 CDT 2002\n\r> "
|
Monitor output as it occurs. We associate a block with each of the
library calls; this block is called whenever data becomes
available from the host.
require 'net/telnet'
tn = Net::Telnet.new({}) { |str| print str }
tn.login("guest", "secret") { |str| print str }
tn.cmd("date") { |str| print str }
|
produces:
Trying localhost...
Connected to localhost.
Welcome to SuSE Linux 7.1 (i386) - Kernel 2.4.0-64GB-SMP (8).
zip login: guest
Password:
Last login: Sun Jun 9 00:15:19 from localhost
/etc/zshrc: setopt: no such option: histexpiredupsfirst [31]
> date
Sun Jun 9 00:15:20 CDT 2002
>
|
Get the time from an NTP server.
require 'net/telnet'
tn = Net::Telnet.new('Host' => 'time.nonexistent.org',
'Port' => 'time',
'Timeout' => 60,
'Telnetmode' => false)
atomicTime = tn.recv(4).unpack('N')[0]
puts "Atomic time: " + Time.at(atomicTime - 2208988800).to_s
puts "Local time: " + Time.now.to_s
|
produces:
Atomic time: Sun Jun 09 00:15:12 CDT 2002
Local time: Sun Jun 09 00:15:20 CDT 2002
|
The net/telnet library provides a complete implementation of a
telnet client and includes features that make it a convenient
mechanism for interacting with non-telnet services.
Although the class description that follows indicates that
Net::Telnet is a subclass of class Socket , this is a lie.
In reality, the class delegates to Socket . The net effect is the
same: the methods of Socket and its parent, class IO , are
available through Net::Telnet objects.
The methods new , cmd , login , and
waitfor take an optional block. If present, the block is
passed output from the server as it is received by the routine.
This can be used to provide realtime output, rather than waiting for
(for example) a login to complete before displaying the server's
response.
class methods
|
new
|
Net::Telnet.new( options ) -> aSession
Net::Telnet.new( options ) {| str | block }
-> aSession
|
|
Connects to a server. options is a
Hash with zero or more of the following:
Option
|
Default
|
Meaning
|
Binmode
|
false
|
If true, no end-of-line
processing will be performed. |
Host
|
localhost |
Name or address of server's host. |
Port
|
23 |
Name or number of service to call. |
Prompt
|
/[$%#>]/
|
Pattern that matches the host's
prompt. |
Telnetmode
|
true
|
If false , ignore the
majority of telnet embedded escape sequences. Used when
talking with a non-telnet server. |
Timeout
|
10 |
Time in seconds to wait for a server
response (both during connection and during regular data
transmission). |
Waittime
|
0 |
Time to wait for prompt to appear in
received data stream. |
|
|
instance methods
|
binmode
|
aSession.binmode -> true or false
|
|
Returns the current value of the Binmode flag.
|
binmode=
|
aSession.binmode = true or false
|
|
Sets the Binmode flag, returning the new value.
|
cmd
|
aSession.cmd( options ) -> aString
aSession.cmd( options ) {| str | block }
-> aString
|
|
Sends a string to the server and waits (using a timeout) for a
string that matches a pattern to be returned by the server. If
the parameter is not a Hash , it is sent as a string to the server, and
the pattern to match and the timeout are the Prompt and
Timeout options given when aSession was created.
If options is a Hash , then options['String'] is
sent to the server. options['Match'] may be used to
override the class Prompt parameter, and options['Timeout']
the timeout. The method returns the complete server response.
|
login
|
aSession.login( options,
password=nil ) -> aString
aSession.login( options,
password=nil ) {| str | block }
-> aString
|
|
If options is a Hash , a username is taken from
options['Name'] and a password from
options['Password']; otherwise, options is assumed to
be the username, and password the password. The method
waits for the server to send the string matching the pattern
/login[:]*\z/ and sends the username. If a
password is given, it then waits for the server to send
/Password[:]*\z/ and sends the password. The
method returns the full server response.
|
print
|
aSession.print( aString )
|
|
Sends aString to the server, honoring Telnetmode ,
Binarymode , and any additional modes negotiated with the
server.
|
telnetmode
|
aSession.telnetmode -> true or false
|
|
Returns the current value of the Telnetmode flag.
|
telnetmode=
|
aSession.telnetmode= true or false
|
|
Sets the Telnetmode
flag, returning the new value.
|
waitfor
|
aSession.waitfor( options ) -> aString
aSession.waitfor( options ) {| str | block }
-> aString
|
|
Waits for the server to respond with a string that matches a
string or pattern. If options is not a Hash , it
is compared against the cumulative server output as that output
is received using options.
=== . It is likely that you will
want to use a regular expression in this case.
If options is a Hash , then options['Match'],
options['Prompt'], or options['String'] provides the
match. In the latter case, the string will be converted to a
regular expression before being used. options may also
include the keys ``Timeout'' and ``Waittime'' to override the
class options of the same names.
|
write
|
aSession.write( aString )
|
|
Writes aString to the server with no translation.
|
|
|
|