see METHODS or EXAMPLES sections below
Other reasons to use this module than strictly with a TELNET port are:
Here's an example that prints who's logged-on to a remote host. In addition to a username and password, you must also know the user's shell prompt, which for this example is "bash$ "
use Net::Telnet (); $t = new Net::Telnet (Timeout => 10, Prompt => '/bash\$ $/'); $t->open($host); $t->login($username, $passwd); @lines = $t->cmd("who"); print @lines;
See the EXAMPLES section below for more examples.
Usage questions should be directed to the perlmonks.org discussion group. Bugs can be viewed or reported at cpan.org on the Net::Telnet page.
Of course don't forget about regexp metacharacters like ".", "[", or "$". You'll only need a single backslash to quote them. The anchor metacharacters "^" and "$" refer to positions in the input buffer. To avoid matching characters read that look like a prompt, it's a good idea to end your prompt pattern with the "$" anchor. That way the prompt will only match if it's the last thing read.
If you have the IO:: libraries installed (they come standard with perl5.004 and later) then IO::Socket::INET is used as a base class, otherwise FileHandle is used.
"dump_log()" allows you to see the data being sent from the remote side before any translation is done, while "input_log()" shows you the results after translation. The translation includes converting end of line characters, removing and responding to TELNET protocol commands in the data stream.
Net::Telnet->new(Timeout => 20);
however the dash-option style is also allowed:
Net::Telnet->new(-timeout => 20);
When a TELNET server first accepts a connection, it must use the ASCII control characters carriage-return and line-feed to start a new line (see RFC854). A server like the ``Microsoft Telnet Server'' that doesn't do this, isn't a TELNET server. These servers send ANSI terminal escape sequences to position to a column on a subsequent line and to even position while writing characters that are adjacent to each other. Worse, when sending output these servers resend previously sent command output in a misguided attempt to display an entire terminal screen.
Connecting Net::Telnet to one of these false TELNET servers makes your job of parsing command output very difficult. It's better to replace a false TELNET server with a real TELNET server. The better TELNET servers for MS-Windows allow you to avoid the ANSI escapes by turning off something some of them call console mode.
$obj = new Net::Telnet ([$host]); $obj = new Net::Telnet ([Binmode => $mode,] [Cmd_remove_mode => $mode,] [Dump_Log => $filename,] [Errmode => $errmode,] [Family => $family,] [Fhopen => $filehandle,] [Host => $host,] [Input_log => $file,] [Input_record_separator => $chars,] [Localfamily => $family,] [Localhost => $host,] [Max_buffer_length => $len,] [Ofs => $chars,] [Option_log => $file,] [Ors => $chars,] [Output_field_separator => $chars,] [Output_log => $file,] [Output_record_separator => $chars,] [Port => $port,] [Prompt => $matchop,] [Rs => $chars,] [Telnetmode => $mode,] [Timeout => $secs,]);
This is the constructor for Net::Telnet objects. A new object is returned on success, the error mode action is performed on failure - see "errmode()". The optional arguments are short-cuts to methods of the same name.
If the $host argument is given then the object is opened by connecting to TCP $port on $host. Also see "open()". The new object returned is given the following defaults in the absence of corresponding named parameters:
$mode = $obj->binmode; $prev = $obj->binmode($mode);
This method controls whether or not sequences of carriage returns and line feeds (CR LF or more specifically "\015\012") are translated. By default they are translated (i.e. binmode is 0).
If no argument is given, the current mode is returned.
If $mode is 1 then binmode is on and newline translation is not done.
If $mode is 0 then binmode is off and newline translation is done. In the input stream, each sequence of CR LF is converted to "\n" and in the output stream, each occurrence of "\n" is converted to a sequence of CR LF.
Note that input is always buffered. Changing binmode doesn't effect what's already been read into the buffer. Output is not buffered and changing binmode will have an immediate effect.
$ok = $obj->break;
This method sends the TELNET break character. This character is provided because it's a signal outside the ASCII character set which is currently given local meaning within many systems. It's intended to indicate that the Break Key or the Attention Key was hit.
This method returns 1 on success, or performs the error mode action on failure.
$ref = $obj->buffer;
This method returns a scalar reference to the input buffer for $obj. Data in the input buffer is data that has been read from the remote side but has yet to be read by the user. Modifications to the input buffer are returned by a subsequent read.
$obj->buffer_empty;
This method removes all data in the input buffer for $obj.
$ok = $obj->close;
This method closes the socket, file, or pipe associated with the object. It always returns a value of 1.
$ok = $obj->cmd($string); $ok = $obj->cmd(String => $string, [Output => $ref,] [Cmd_remove_mode => $mode,] [Errmode => $mode,] [Input_record_separator => $chars,] [Ors => $chars,] [Output_record_separator => $chars,] [Prompt => $match,] [Rs => $chars,] [Timeout => $secs,]); @output = $obj->cmd($string); @output = $obj->cmd(String => $string, [Output => $ref,] [Cmd_remove_mode => $mode,] [Errmode => $mode,] [Input_record_separator => $chars,] [Ors => $chars,] [Output_record_separator => $chars,] [Prompt => $match,] [Rs => $chars,] [Timeout => $secs,]);
This method sends the command $string, and reads the characters sent back by the command up until and including the matching prompt. It's assumed that the program to which you're sending is some kind of command prompting interpreter such as a shell.
The command $string is automatically appended with the output_record_separator, by default it is "\n". This is similar to someone typing a command and hitting the return key. Set the output_record_separator to change this behavior.
In a scalar context, the characters read from the remote side are discarded and 1 is returned on success. On time-out, eof, or other failures, the error mode action is performed. See "errmode()".
In a list context, just the output generated by the command is returned, one line per element. In other words, all the characters in between the echoed back command string and the prompt are returned. If the command happens to return no output, a list containing one element, the empty string is returned. This is so the list will indicate true in a boolean context. On time-out, eof, or other failures, the error mode action is performed. See "errmode()".
The characters that matched the prompt may be retrieved using "last_prompt()".
Many command interpreters echo back the command sent. In most situations, this method removes the first line returned from the remote side (i.e. the echoed back command). See "cmd_remove_mode()" for more control over this feature.
Use "dump_log()" to debug when this method keeps timing-out and you don't think it should.
Consider using a combination of "print()" and "waitfor()" as an alternative to this method when it doesn't do what you want, e.g. the command you send prompts for input.
The Output named parameter provides an alternative method of receiving command output. If you pass a scalar reference, all the output (even if it contains multiple lines) is returned in the referenced scalar. If you pass an array or hash reference, the lines of output are returned in the referenced array or hash. You can use "input_record_separator()" to change the notion of what separates a line.
Optional named parameters are provided to override the current settings of cmd_remove_mode, errmode, input_record_separator, ors, output_record_separator, prompt, rs, and timeout. Rs is synonymous with input_record_separator and ors is synonymous with output_record_separator.
$mode = $obj->cmd_remove_mode; $prev = $obj->cmd_remove_mode($mode);
This method controls how to deal with echoed back commands in the output returned by cmd(). Typically, when you send a command to the remote side, the first line of output returned is the command echoed back. Use this mode to remove the first line of output normally returned by cmd().
If no argument is given, the current mode is returned.
If $mode is 0 then the command output returned from cmd() has no lines removed. If $mode is a positive integer, then the first $mode lines of command output are stripped.
By default, $mode is set to "auto". Auto means that whether or not the first line of command output is stripped, depends on whether or not the remote side offered to echo. By default, Net::Telnet always accepts an offer to echo by the remote side. You can change the default to reject such an offer using "option_accept()".
A warning is printed to STDERR when attempting to set this attribute to something that is not "auto" or a non-negative integer.
$fh = $obj->dump_log; $fh = $obj->dump_log($fh); $fh = $obj->dump_log($filename);
This method starts or stops dump format logging of all the object's input and output. The dump format shows the blocks read and written in a hexadecimal and printable character format. This method is useful when debugging, however you might want to first try "input_log()" as it's more readable.
If no argument is given, the log filehandle is returned. A returned empty string indicates logging is off.
To stop logging, use an empty string as an argument. The stopped filehandle is not closed.
If an open filehandle is given, it is used for logging and returned. Otherwise, the argument is assumed to be the name of a file, the filename is opened for logging and a filehandle to it is returned. If the filehandle is not already opened or the filename can't be opened for writing, the error mode action is performed.
$eof = $obj->eof;
This method returns 1 if end of file has been read, otherwise it returns an empty string. Because the input is buffered this isn't the same thing as $obj has closed. In other words $obj can be closed but there still can be stuff in the buffer to be read. Under this condition you can still read but you won't be able to write.
$mode = $obj->errmode; $prev = $obj->errmode($mode);
This method gets or sets the action used when errors are encountered using the object. The first calling sequence returns the current error mode. The second calling sequence sets it to $mode and returns the previous mode. Valid values for $mode are "die" (the default), "return", a coderef, or an arrayref.
When mode is "die" and an error is encountered using the object, then an error message is printed to standard error and the program dies.
When mode is "return" then the method generating the error places an error message in the object and returns an undefined value in a scalar context and an empty list in list context. The error message may be obtained using "errmsg()".
When mode is a coderef, then when an error is encountered coderef is called with the error message as its first argument. Using this mode you may have your own subroutine handle errors. If coderef itself returns then the method generating the error returns undefined or an empty list depending on context.
When mode is an arrayref, the first element of the array must be a coderef. Any elements that follow are the arguments to coderef. When an error is encountered, the coderef is called with its arguments. Using this mode you may have your own subroutine handle errors. If the coderef itself returns then the method generating the error returns undefined or an empty list depending on context.
A warning is printed to STDERR when attempting to set this attribute to something that is not "die", "return", a coderef, or an arrayref whose first element isn't a coderef.
$msg = $obj->errmsg; $prev = $obj->errmsg(@msgs);
The first calling sequence returns the error message associated with the object. The empty string is returned if no error has been encountered yet. The second calling sequence sets the error message for the object to the concatenation of @msgs and returns the previous error message. Normally, error messages are set internally by a method when an error is encountered.
$obj->error(@msgs);
This method concatenates @msgs into a string and places it in the object as the error message. Also see "errmsg()". It then performs the error mode action. Also see "errmode()".
If the error mode doesn't cause the program to die, then an undefined value or an empty list is returned depending on the context.
This method is primarily used by this class or a sub-class to perform the user requested action when an error is encountered.
$family = $obj->family; $prev = $obj->family($family);
This method designates which IP address family "host()" refers to, i.e. IPv4 or IPv6. IPv6 support is available when using perl 5.14 or later. With no argument it returns the current value set in the object. With an argument it sets the current address family to $family and returns the previous address family. Valid values are "ipv4", "ipv6", or "any". When "any", the "host()" can be a hostname or IP address for either IPv4 or IPv6. After connecting, you can use "sockfamily()" to determine which IP address family was used.
The default value is "ipv4".
The error mode action is performed when attempting to set this attribute to something that isn't "ipv4", "ipv6", or "any". It is also performed when attempting to set it to "ipv6" when the Socket module is less than version 1.94 or IPv6 is not supported in the OS as indicated by Socket::AF_INET6 not being defined.
$ok = $obj->fhopen($fh);
This method associates the open filehandle $fh with $obj for further I/O. Filehandle $fh must already be opened.
Suppose you want to use the features of this module to do I/O to something other than a TCP port, for example STDIN or a filehandle opened to read from a process. Instead of opening the object for I/O to a TCP port by using "open()" or "new()", call this method instead.
The value 1 is returned success, the error mode action is performed on failure.
$data = $obj->get([Binmode => $mode,] [Errmode => $errmode,] [Telnetmode => $mode,] [Timeout => $secs,]);
This method reads a block of data from the object and returns it along with any buffered data. If no buffered data is available to return, it will wait for data to read using the timeout specified in the object. You can override that timeout using $secs. Also see "timeout()". If buffered data is available to return, it also checks for a block of data that can be immediately read.
On eof an undefined value is returned. On time-out or other failures, the error mode action is performed. To distinguish between eof or an error occurring when the error mode is not set to "die", use "eof()".
Optional named parameters are provided to override the current settings of binmode, errmode, telnetmode, and timeout.
$line = $obj->getline([Binmode => $mode,] [Errmode => $errmode,] [Input_record_separator => $chars,] [Rs => $chars,] [Telnetmode => $mode,] [Timeout => $secs,]);
This method reads and returns the next line of data from the object. You can use "input_record_separator()" to change the notion of what separates a line. The default is "\n". If a line isn't immediately available, this method blocks waiting for a line or a time-out.
On eof an undefined value is returned. On time-out or other failures, the error mode action is performed. To distinguish between eof or an error occurring when the error mode is not set to "die", use "eof()".
Optional named parameters are provided to override the current settings of binmode, errmode, input_record_separator, rs, telnetmode, and timeout. Rs is synonymous with input_record_separator.
@lines = $obj->getlines([Binmode => $mode,] [Errmode => $errmode,] [Input_record_separator => $chars,] [Rs => $chars,] [Telnetmode => $mode,] [Timeout => $secs,] [All => $boolean,]);
This method reads and returns all the lines of data from the object until end of file is read. You can use "input_record_separator()" to change the notion of what separates a line. The default is "\n". A time-out error occurs if all the lines can't be read within the time-out interval. See "timeout()".
The behavior of this method was changed in version 3.03. Prior to version 3.03 this method returned just the lines available from the next read. To get that old behavior, use the optional named parameter All and set $boolean to "" or 0.
If only eof is read then an empty list is returned. On time-out or other failures, the error mode action is performed. Use "eof()" to distinguish between reading only eof or an error occurring when the error mode is not set to "die".
Optional named parameters are provided to override the current settings of binmode, errmode, input_record_separator, rs, telnetmode, and timeout. Rs is synonymous with input_record_separator.
$host = $obj->host; $prev = $obj->host($host);
This method designates the remote host for "open()". It is either a hostname or an IP address. With no argument it returns the current value set in the object. With an argument it sets the current host name to $host and returns the previous value. Use "family()" to control which IP address family, IPv4 or IPv6, host refers to.
The default value is "localhost". It may also be set by "open()" or "new()".
$fh = $obj->input_log; $fh = $obj->input_log($fh); $fh = $obj->input_log($filename);
This method starts or stops logging of input. This is useful when debugging. Also see "dump_log()". Because most command interpreters echo back commands received, it's likely all your output will also be in this log. Note that input logging occurs after newline translation. See "binmode()" for details on newline translation.
If no argument is given, the log filehandle is returned. A returned empty string indicates logging is off.
To stop logging, use an empty string as an argument. The stopped filehandle is not closed.
If an open filehandle is given, it is used for logging and returned. Otherwise, the argument is assumed to be the name of a file, the filename is opened for logging and a filehandle to it is returned. If the filehandle is not already opened or the filename can't be opened for writing, the error mode action is performed.
$chars = $obj->input_record_separator; $prev = $obj->input_record_separator($chars);
This method designates the line delimiter for input. It's used with "getline()", "getlines()", and "cmd()" to determine lines in the input.
With no argument this method returns the current input record separator set in the object. With an argument it sets the input record separator to $chars and returns the previous value. Note that $chars must have length.
A warning is printed to STDERR when attempting to set this attribute to a string with no length.
$string = $obj->last_prompt; $prev = $obj->last_prompt($string);
With no argument this method returns the last prompt read by cmd() or login(). See "prompt()". With an argument it sets the last prompt read to $string and returns the previous value. Normally, only internal methods set the last prompt.
$line = $obj->lastline; $prev = $obj->lastline($line);
This method retrieves the last line read from the object. This may be a useful error message when the remote side abnormally closes the connection. Typically the remote side will print an error message before closing.
With no argument this method returns the last line read from the object. With an argument it sets the last line read to $line and returns the previous value. Normally, only internal methods set the last line.
$localfamily = $obj->localfamily; $prev = $obj->localfamily($family);
This method designates which IP address family "localhost()" refers to, i.e. IPv4 or IPv6. IPv6 support is available when using perl 5.14 or later. With no argument it returns the current value set in the object. With an argument it sets the current local address family to $family and returns the previous address family. Valid values are "ipv4", "ipv6", or "any". When "any", the "localhost()" can be a hostname or IP address for either IPv4 or IPv6.
The default value is "ipv4".
The error mode action is performed when attempting to set this attribute to something that isn't "ipv4", "ipv6", or "any". It is also performed when attempting to set it to "ipv6" when the Socket module is less than version 1.94 or IPv6 is not supported in the OS as indicated by Socket::AF_INET6 not being defined.
$localhost = $obj->localhost; $prev = $obj->localhost($host);
This method designates the local socket IP address for "open()". It is either a hostname, an IP address, or a null string (i.e. ""). A null string disables this feature.
Normally the OS picks which local network interface to use. This method is useful when the local machine has more than one network interface and you want to bind to a specific one. With no argument it returns the current value set in the object. With an argument it sets the current local host name to $host and returns the previous value. Use "localfamily()" to control which IP address family, IPv4 or IPv6, local host refers to.
The default value is "".
$ok = $obj->login($username, $password); $ok = $obj->login(Name => $username, Password => $password, [Errmode => $mode,] [Prompt => $match,] [Timeout => $secs,]);
This method performs a standard login by waiting for a login prompt and responding with $username, then waiting for the password prompt and responding with $password, and then waiting for the command interpreter prompt. If any of those prompts sent by the remote side don't match what's expected, this method will time-out, unless timeout is turned off.
Login prompt must match either of these case insensitive patterns:
/login[: ]*$/i /username[: ]*$/i
Password prompt must match this case insensitive pattern:
/password[: ]*$/i
The command interpreter prompt must match the current setting of prompt. See "prompt()".
Use "dump_log()" to debug when this method keeps timing-out and you don't think it should.
Consider using a combination of "print()" and "waitfor()" as an alternative to this method when it doesn't do what you want, e.g. the remote host doesn't prompt for a username.
On success, 1 is returned. On time out, eof, or other failures, the error mode action is performed. See "errmode()".
Optional named parameters are provided to override the current settings of errmode, prompt, and timeout.
$len = $obj->max_buffer_length; $prev = $obj->max_buffer_length($len);
This method designates the maximum size of the input buffer. An error is generated when a read causes the buffer to exceed this limit. The default value is 1,048,576 bytes (1 MiB). The input buffer can grow much larger than the block size when you continuously read using "getline()" or "waitfor()" and the data stream contains no newlines or matching waitfor patterns.
With no argument, this method returns the current maximum buffer length set in the object. With an argument it sets the maximum buffer length to $len and returns the previous value. Values of $len smaller than 512 will be adjusted to 512.
A warning is printed to STDERR when attempting to set this attribute to something that isn't a positive integer.
$chars = $obj->ofs $prev = $obj->ofs($chars);
This method is synonymous with "output_field_separator()".
$ok = $obj->open($host); $ok = $obj->open([Host => $host,] [Port => $port,] [Family => $family,] [Errmode => $mode,] [Timeout => $secs,] [Localhost => $host,] [Localfamily => $family,]);
This method opens a TCP connection to $port on $host for the IP address $family. If any of those arguments are missing then the current attribute value for the object is used. Specifing Host sets that attribute for the object. Specifing any of the other optional named parameters overrides the current setting.
The default IP address family is "ipv4". $family may be set to "ipv4", "ipv6", or "any". See "family()" for more details.
Localhost is used to bind to a specific local network interface.
If the object is already open, it is closed before attempting a connection.
On success 1 is returned. On time-out or other connection failures, the error mode action is performed. See "errmode()".
Time-outs don't work for this method on machines that don't implement SIGALRM - most notably MS-Windows machines. For those machines, an error is returned when the system reaches its own time-out while trying to connect.
A side effect of this method is to reset the alarm interval associated with SIGALRM.
$fh = $obj->option_accept([Do => $telopt,] [Dont => $telopt,] [Will => $telopt,] [Wont => $telopt,]);
This method is used to indicate whether to accept or reject an offer to enable a TELNET option made by the remote side. If you're using Do or Will to indicate a willingness to enable, then a notification callback must have already been defined by a prior call to "option_callback()". See "option_callback()" for details on receiving enable/disable notification of a TELNET option.
You can give multiple Do, Dont, Will, or Wont arguments for different TELNET options in the same call to this method.
The following example describes the meaning of the named parameters. A TELNET option, such as "TELOPT_ECHO" used below, is an integer constant that you can import from Net::Telnet. See the source in file Telnet.pm for the complete list.
$coderef = $obj->option_callback; $prev = $obj->option_callback($coderef);
This method defines the callback subroutine that is called when a TELNET option is enabled or disabled. Once defined, the option_callback may not be undefined. However, calling this method with a different $coderef changes it.
A warning is printed to STDERR when attempting to set this attribute to something that isn't a coderef.
Here are the circumstances that invoke $coderef:
&$coderef($obj, $option, $is_remote, $is_enabled, $was_enabled, $buf_position);
$fh = $obj->option_log; $fh = $obj->option_log($fh); $fh = $obj->option_log($filename);
This method starts or stops logging of all TELNET options being sent or received. This is useful for debugging when you send options via "option_send()" or you arrange to accept option requests from the remote side via "option_accept()". Also see "dump_log()".
If no argument is given, the log filehandle is returned. An empty string indicates logging is off.
To stop logging, use an empty string as an argument. The stopped filehandle is not closed.
If an open filehandle is given, it is used for logging and returned. Otherwise, the argument is assumed to be the name of a file, the filename is opened for logging and a filehandle to it is returned. If the filehandle is not already opened or the filename can't be opened for writing, the error mode action is performed.
$ok = $obj->option_send([Do => $telopt,] [Dont => $telopt,] [Will => $telopt,] [Wont => $telopt,] [Async => $boolean,]);
This method is not yet implemented. Look for it in a future version.
$hashref = $obj->option_state($telopt);
This method returns a hashref containing a copy of the current state of TELNET option $telopt.
Here are the values returned in the hash:
$chars = $obj->ors; $prev = $obj->ors($chars);
This method is synonymous with "output_record_separator()".
$chars = $obj->output_field_separator; $prev = $obj->output_field_separator($chars);
This method designates the output field separator for "print()". Ordinarily the print method simply prints out the comma separated fields you specify. Set this to specify what's printed between fields.
With no argument this method returns the current output field separator set in the object. With an argument it sets the output field separator to $chars and returns the previous value.
By default it's set to an empty string.
$fh = $obj->output_log; $fh = $obj->output_log($fh); $fh = $obj->output_log($filename);
This method starts or stops logging of output. This is useful when debugging. Also see "dump_log()". Because most command interpreters echo back commands received, it's likely all your output would also be in an input log. See "input_log()". Note that output logging occurs before newline translation. See "binmode()" for details on newline translation.
If no argument is given, the log filehandle is returned. A returned empty string indicates logging is off.
To stop logging, use an empty string as an argument. The stopped filehandle is not closed.
If an open filehandle is given, it is used for logging and returned. Otherwise, the argument is assumed to be the name of a file, the filename is opened for logging and a filehandle to it is returned. If the filehandle is not already opened or the filename can't be opened for writing, the error mode action is performed.
$chars = $obj->output_record_separator; $prev = $obj->output_record_separator($chars);
This method designates the output line delimiter for "print()" and "cmd()". Set this to specify what's printed at the end of "print()" and "cmd()".
The output record separator is set to "\n" by default, so there's no need to append all your commands with a newline. To avoid printing the output_record_separator use "put()" or set the output_record_separator to an empty string.
With no argument this method returns the current output record separator set in the object. With an argument it sets the output record separator to $chars and returns the previous value.
$ipaddr = $obj->peerhost;
This method returns a string which is the IPv4 or IPv6 address the remote socket is bound to (i.e. it is the IP address of "host()"). It returns "" when not connected.
$port = $obj->peerport;
This method returns the port number which the remote socket is bound to. It is the same as the "port()" number when connected. It returns "" when not connected.
$port = $obj->port; $prev = $obj->port($port);
This method designates the remote TCP port for "open()". With no argument this method returns the current port number. With an argument it sets the current port number to $port and returns the previous port. If $port is a TCP service name, then it's first converted to a port number using the perl function "getservbyname()".
The default value is 23.
The error mode action is performed when attempting to set this attribute to something that is not a positive integer or a valid TCP service name.
$ok = $obj->print(@list);
This method writes @list followed by the output_record_separator to the open object and returns 1 if all data was successfully written. On time-out or other failures, the error mode action is performed. See "errmode()".
By default, the "output_record_separator()" is set to "\n" so all your commands automatically end with a newline. In most cases your output is being read by a command interpreter which won't accept a command until newline is read. This is similar to someone typing a command and hitting the return key. To avoid printing a trailing "\n" use "put()" instead or set the output_record_separator to an empty string.
On failure, it's possible that some data was written. If you choose to try and recover from a print timing-out, use "print_length()" to determine how much was written before the error occurred.
You may also use the output field separator to print a string between the list elements. See "output_field_separator()".
$num = $obj->print_length;
This returns the number of bytes successfully written by the most recent "print()" or "put()".
$matchop = $obj->prompt; $prev = $obj->prompt($matchop);
This method sets the pattern used to find a prompt in the input stream. It must be a string representing a valid perl pattern match operator. The methods "login()" and "cmd()" try to read until matching the prompt. They will fail with a time-out error if the pattern you've chosen doesn't match what the remote side sends.
With no argument this method returns the prompt set in the object. With an argument it sets the prompt to $matchop and returns the previous value.
The default prompt is '/[\$%#>] $/'
Always use single quotes, instead of double quotes, to construct $matchop (e.g. '/bash\$ $/'). If you're constructing a DOS like file path, you'll need to use four backslashes to represent one (e.g. '/c:\\\\users\\\\bill>$/i').
Of course don't forget about regexp metacharacters like ".", "[", or "$". You'll only need a single backslash to quote them. The anchor metacharacters "^" and "$" refer to positions in the input buffer.
The error mode action is performed when attempting to set this attribute with a match operator missing its opening delimiter.
$ok = $obj->put($string); $ok = $obj->put(String => $string, [Binmode => $mode,] [Errmode => $errmode,] [Telnetmode => $mode,] [Timeout => $secs,]);
This method writes $string to the opened object and returns 1 if all data was successfully written. This method is like "print()" except that it doesn't write the trailing output_record_separator (``\n'' by default). On time-out or other failures, the error mode action is performed. See "errmode()".
On failure, it's possible that some data was written. If you choose to try and recover from a put timing-out, use "print_length()" to determine how much was written before the error occurred.
Optional named parameters are provided to override the current settings of binmode, errmode, telnetmode, and timeout.
$chars = $obj->rs; $prev = $obj->rs($chars);
This method is synonymous with "input_record_separator()".
$sockfamily = $obj->sockfamily;
This method returns which IP address family "open()" used to successfully connect. It is most useful when the requested address "family()" for "open()" was "any". Values returned may be "ipv4", "ipv6", or "" (when not connected).
$ipaddr = $obj->sockhost;
This method returns a string which is the IPv4 or IPv6 address the local socket is bound to. It returns "" when not connected.
$port = $obj->sockport;
This method returns the port number which the local socket is bound to. It returns "" when not connected.
$mode = $obj->telnetmode; $prev = $obj->telnetmode($mode);
This method controls whether or not TELNET commands in the data stream are recognized and handled. The TELNET protocol uses certain character sequences sent in the data stream to control the session. If the port you're connecting to isn't using the TELNET protocol, then you should turn this mode off. The default is on.
If no argument is given, the current mode is returned.
If $mode is 0 then telnet mode is off. If $mode is 1 then telnet mode is on.
$boolean = $obj->timed_out; $prev = $obj->timed_out($boolean);
This method indicates if a previous read, write, or open method timed-out. Remember that timing-out is itself an error. To be able to invoke "timed_out()" after a time-out error, you'd have to change the default error mode to something other than "die". See "errmode()".
With no argument this method returns 1 if the previous method timed-out. With an argument it sets the indicator. Normally, only internal methods set this indicator.
$secs = $obj->timeout; $prev = $obj->timeout($secs);
This method sets the timeout interval used when performing I/O or connecting to a port. When a method doesn't complete within the timeout interval then it's an error and the error mode action is performed.
A timeout may be expressed as a relative or absolute value. If $secs is greater than or equal to the time the program started, as determined by $^T, then it's an absolute time value for when time-out occurs. The perl function "time()" may be used to obtain an absolute time value. For a relative time-out value less than $^T, time-out happens $secs from when the method begins.
If $secs is 0 then time-out occurs if the data cannot be immediately read or written. Use the undefined value to turn off timing-out completely.
With no argument this method returns the timeout set in the object. With an argument it sets the timeout to $secs and returns the previous value. The default timeout value is 10 seconds.
A warning is printed to STDERR when attempting to set this attribute to something that is not an "undef" or a non-negative integer.
$ok = $obj->waitfor($matchop); $ok = $obj->waitfor([Match => $matchop,] [String => $string,] [Binmode => $mode,] [Errmode => $errmode,] [Telnetmode => $mode,] [Timeout => $secs,]); ($prematch, $match) = $obj->waitfor($matchop); ($prematch, $match) = $obj->waitfor([Match => $matchop,] [String => $string,] [Binmode => $mode,] [Errmode => $errmode,] [Telnetmode => $mode,] [Timeout => $secs,]);
This method reads until a pattern match or string is found in the input stream. All the characters before and including the match are removed from the input stream.
In a list context the characters before the match and the matched characters are returned in $prematch and $match. In a scalar context, the matched characters and all characters before it are discarded and 1 is returned on success. On time-out, eof, or other failures, for both list and scalar context, the error mode action is performed. See "errmode()".
You can specify more than one pattern or string by simply providing multiple Match and/or String named parameters. A $matchop must be a string representing a valid Perl pattern match operator. The $string is just a substring to find in the input stream.
Use "dump_log()" to debug when this method keeps timing-out and you don't think it should.
An optional named parameter is provided to override the current setting of timeout.
To avoid unexpected backslash interpretation, always use single quotes instead of double quotes to construct a match operator argument for "prompt()" and "waitfor()" (e.g. '/bash\$ $/'). If you're constructing a DOS like file path, you'll need to use four backslashes to represent one (e.g. '/c:\\\\users\\\\bill>$/i').
Of course don't forget about regexp metacharacters like ".", "[", or "$". You'll only need a single backslash to quote them. The anchor metacharacters "^" and "$" refer to positions in the input buffer.
Optional named parameters are provided to override the current settings of binmode, errmode, telnetmode, and timeout.
my $host = 'your_destination_host_here'; my $user = 'your_username_here'; my $passwd = 'your_password_here'; my ($t, @output); ## Create a Net::Telnet object. use Net::Telnet (); $t = new Net::Telnet (Timeout => 10); ## Connect and login. $t->open($host); $t->waitfor('/login: ?$/i'); $t->print($user); $t->waitfor('/password: ?$/i'); $t->print($passwd); ## Switch to a known shell, using a known prompt. $t->prompt('/<xPROMPTx> $/'); $t->errmode("return"); $t->cmd("exec /usr/bin/env 'PS1=<xPROMPTx> ' /bin/sh -i") or die "login failed to remote host $host"; $t->errmode("die"); ## Now you can do cmd() to your heart's content. @output = $t->cmd("uname -a"); print @output; exit;
Usually you want the remote TERM environment variable to be set to something like ``dumb'' so you don't read escape sequences meant to be interpreted by a display terminal. It is best to set it via "cmd()", or via "waitfor()" and "print()". It is also possible to negotiate the terminal type via telnet. Here is how to do that.
## Module import. use Net::Telnet qw(TELNET_IAC TELNET_SB TELNET_SE TELOPT_TTYPE); ## Global variables. my $Term; ## Main program. { my $host = "your_destination_host_here"; my $user = "your_username_here"; my $passwd = "your_password_here"; my $prompt = '/bash\$ $/'; # your regexp for shell prompt here my $t; $t = new Net::Telnet (Prompt => $prompt); ## Set up callbacks to negotiate terminal type. $t->option_callback(sub {}); $t->suboption_callback(\&subopt_callback); $t->option_accept(Do => TELOPT_TTYPE); ## Login and print value of TERM. $Term = "dumb"; $t->open($host); $t->login($user, $passwd); print $t->cmd('hostname'); print "TERM=", $t->cmd('echo $TERM'); $t->close; exit; } # end main program sub subopt_callback { my ($t, $option, $parameters) = @_; my $telcmd; if ($option == TELOPT_TTYPE) { $telcmd = pack("C4 A* C2", TELNET_IAC, TELNET_SB, TELOPT_TTYPE, 0, $Term, TELNET_IAC, TELNET_SE); $t->put(String => $telcmd, Telnetmode => 0); } 1; } # end sub subopt_callback
You can also use Net::Telnet to interact with local programs. This example changes a user's login password. It introduces the "spawn()" subroutine to start a program and associate a filehandle with its standard I/O. Because the passwd program always prompts for passwords on its controlling terminal, the IO::Pty module is used to create a new pseudo terminal for use by passwd. The Net::Telnet object reads and writes to that pseudo terminal. To use the code below, substitute ``changeme'' with the actual old and new passwords.
## Main program.
{
my ($pty, $passwd);
my $oldpw = ``changeme'';
my $newpw = ``changeme'';
## Start passwd program. $pty = spawn("passwd"); ## Create a Net::Telnet object to perform I/O on passwd's tty. use Net::Telnet; $passwd = new Net::Telnet (-fhopen => $pty, -timeout => 2, -output_record_separator => "\r", -telnetmode => 0, -cmd_remove_mode => 1); $passwd->errmode("return"); ## Send existing password. $passwd->waitfor('/password: ?$/i') or die "no old password prompt: ", $passwd->lastline; $passwd->print($oldpw); ## Send new password. $passwd->waitfor('/new (\w+\s)?password: ?$/i') or die "bad old password: ", $passwd->lastline; $passwd->print($newpw); ## Send new password verification. $passwd->waitfor('/new (\w+\s)?password: ?$/i') or die "bad new password: ", $passwd->lastline; $passwd->print($newpw); ## Display success or failure. $passwd->waitfor('/(changed|updated)/') or die "bad new password: ", $passwd->lastline; print $passwd->lastline; $passwd->close; exit; } # end main program
sub spawn {
my (@cmd) = @_;
my ($pid, $pty, $tty, $tty_fd);
## Create a new pseudo terminal. use IO::Pty (); $pty = new IO::Pty or die $!; ## Execute the program in another process. unless ($pid = fork) { # child process die "problem spawning program: $!\n" unless defined $pid; ## Disassociate process from its controlling terminal. use POSIX (); POSIX::setsid() or die "setsid failed: $!"; ## Associate process with a new controlling terminal. $pty->make_slave_controlling_terminal; $tty = $pty->slave; $tty_fd = $tty->fileno; close $pty; ## Make standard I/O use the new controlling terminal. open STDIN, "<&$tty_fd" or die $!; open STDOUT, ">&$tty_fd" or die $!; open STDERR, ">&STDOUT" or die $!; close $tty; ## Execute requested program. exec @cmd or die "problem executing $cmd[0]\n"; } # end child process $pty; } # end sub spawn
Here is an example that uses the openssh program to connect to a remote host. It uses the "spawn()" subroutine, from the password changing example above, to start the ssh program and then read and write to it via a Net::Telnet object. This example turns off ssh host key checking, which reduces your ability to know when someone on the network is impersonating the remote host. To use the code below, substitute ``changeme'' with the actual host, user, password, and command prompt.
## Main program. { my $host = "changeme"; my $user = "changeme"; my $passwd = "changeme"; my $prompt = '/changeme\$ $/'; my ($buf, $match, $pty, $ssh, @lines); ## Start ssh program. $pty = spawn("ssh", "-l", $user, "-e", "none", "-F", "/dev/null", "-o", "PreferredAuthentications=password", "-o", "NumberOfPasswordPrompts=1", "-o", "StrictHostKeyChecking=no", "-o", "UserKnownHostsFile=/dev/null", $host); ## Create a Net::Telnet object to perform I/O on ssh's tty. use Net::Telnet; $ssh = new Net::Telnet (-fhopen => $pty, -prompt => $prompt, -telnetmode => 0, -output_record_separator => "\r", -cmd_remove_mode => 1); ## Wait for the password prompt and send password. $ssh->waitfor(-match => '/password: ?$/i', -errmode => "return") or die "problem connecting to \"$host\": ", $ssh->lastline; $ssh->print($passwd); ## Wait for the shell prompt. (undef, $match) = $ssh->waitfor(-match => $ssh->prompt, -match => '/^Permission denied/m', -errmode => "return") or return $ssh->error("login failed: expected shell prompt ", "doesn't match actual\n"); return $ssh->error("login failed: bad login-name or password\n") if $match =~ /^Permission denied/m; ## Run commands on remote host. print $ssh->cmd("hostname"); print $ssh->cmd("uptime"); $ssh->close; exit; } # end main program
Some shells have a rather restrictive 255 character line limit. If you run into this problem, here is an example for sending lines longer than 254 as a sequence of shorter lines.
## Main program. { my $host = "changeme"; my $user = "changeme"; my $passwd = "changeme"; my $prompt = '/changeme\$ $/'; my $cmd = join("", "echo ", "11111111112222222222333333333344444444445555555555", "66666666667777777777888888888899999999990000000000", "11111111112222222222333333333344444444445555555555", "66666666667777777777888888888899999999990000000000", "11111111112222222222333333333344444444445555555555", "66666666667777777777888888888899999999990000000000"); use Net::Telnet (); my $t = new Net::Telnet (-prompt => $prompt); $t->open($host); $t->login($user, $passwd); my @output = cmd_unixlong($t, $cmd); print @output; exit; } # end main program sub cmd_unixlong { my ($obj, $cmd) = @_; my ($line, $pos); my $max_tty_line = 254; ## Start a Bourne shell. $obj->cmd(-string => "/usr/bin/env " . "'PS1=<xPROMPTx> ' 'PS2=<xPROMPTx> ' /bin/sh -i", -prompt => '/<xPROMPTx> $/') or return; ## Break-up the one large command line and send as shorter lines. $pos = 0; while (1) { $line = substr $cmd, $pos, $max_tty_line; $pos += length $line; last unless $pos < length $cmd; ## Send the line with continuation char. $obj->cmd(-string => "$line\\", -prompt => '/<xPROMPTx> $/') or return; } ## Send the last line and return the output. $obj->cmd("$line ; exit"); } # end sub cmd_unixlong