redapplesonly has asked for the wisdom of the Perl Monks concerning the following question:
Hello Monks, first-time poster, and Perl newbie here. (I'm a Java & C coder.) Thank you for reading my question.
So I am struggling to write a Perl script that uses telnet to see if a remote host is responsive. This script needn't be complex; basically, this is a "Are you alive?" test done on the remote machine. (I would normally use ICMP/ping, but my network traffic must pass through my company's firewall.) A bit of a spoiler; this question leans a lot on how to interpret the Net::Telnet module documentation. (https://metacpan.org/pod/Net::Telnet)
First, here's the behavior I'm hoping to emulate. If I manually telnet to a remote host from the command line, it looks like this:
me@ubuntu01$ telnet 10.0.0.1 1234 Trying 10.0.0.1... Connected to 10.0.0.1. Escape character is '^]'. SSH-2.0-OpenSSH_7.4
That "SSH-2.0-OpenSSH_7.4" message tells me that the telnet session is successful, and the remote server opened a valid TCP/IP connection for me. I will have to manually issue a ^C character to break out of the session.
Okay, here's an example of an trying to contact a server which is unavailable:
me@ubuntu01$ telnet 10.0.0.2 1235 Trying 10.0.0.2...
Here, I get nothing back, because the remote host is down. The telnet session will ultimately fail.
So now, I contimplate how to automate these actions in Perl. Ultimately, I'd like to have a subroutine that could take a remote host by IP address (expressed as a string) and then try my telnet test:
#!/usr/bin/perl use warnings; use strict; use Net::Telnet; sub attemptTelnetCheck { # host is a string, expressing an IPv4 address: my ($host) = @_; # Create a telnet object to use TCP port 1234, timeout 3 seconds: my $telnetObj = new Net::Telnet( Port => '1234', Timeout => 3 ); # Set errormode to "return error message upon failure", not die im +mediately: # (I'm not sure this works) my $telnetMode = $telnetObj->errmode("return"); # Try to open telnet session to host: $telnetObj->open($host); # How do I check to see if $telnetObj is valid??? if(exists($telnetObj)) # Line 22 { # Close telnet session: $telnetObj->print('exit'); # Return TRUE: return 1; } else { # Failure! Return FALSE: return 0; } } if(attemptTelnetCheck('10.0.0.1') { print "SUCCESS!"; } else { print "failure."; }
So right away, you can prob tell that I really don't know what I'm doing. I've made my best attempt. Right now, the code fails with the error message:
exists argument is not a HASH or ARRAY element or a subroutine at ./te +lnetTest.perl line 22.
Line 22 is:
if(exists($telnetObj))
I've been reading and rereading the Net::Telnet module documentation over and over, and I'm getting no-where. Does anyone have any practical advice? I'll take whatever I can get. Thank you.
|
---|