in reply to Telnet list of IP and get information stored to a file

What you get is a warning about an undefined $_.

If you look closely you see that it complains about the errormode-sub.

This is triggered because you fail to remove the newlines from the ips you read from the file (after <IPS> $_ contains not "1.2.3.4" but "1.2.3.4\n" - get rid of that with a chomp), so the ip you pass to Net::Telnet is not valid and so the errormode-sub is triggered.

In this sub $_ is no longer the value you read from the file, probably because Net::Telnet localized $_.

If you would use a lexical variable (rather than $_), e.g.

while (my $ip = <IPS>) { chomp $ip; ...

You could then refer to this $ip variable in your errmode-sub (which would then be a closure).

Replies are listed 'Best First'.
Re^2: Telnet list of IP and get information stored to a file
by sanju7 (Acolyte) on Jul 26, 2010 at 23:22 UTC

    Morgon:

    Your advice was good, it helped the code to run without error, that is good. Now since its running i can see the next issue --the successful output isn't going to "telnet.log" . I am still looking at the documentation to check what went wrong and where i need to change.

    Here is the changes i made

    #! /usr/bin/perl -w # run telnet to port xxx # read data use strict; use diagnostics; use Net::Telnet; my $file = 'iplist1.txt' ; #my $command = `/bin/ping` ; open (OUT,'>', "telnet.log"); open (IPS, '<', $file) or die('unable to open the file', $file ); while (my $ip = <IPS>) { chomp $ip; #ping($_) ; #print "$_ " ; my $telnet = Net::Telnet->new(Host=>"$ip", Port=>'xxx', timeout=>4, er +rmode=> (sub { open(OUT, ">>telnet.log"); print "Bad connection - Unable to connect to IP $ip at \r\n" ; print "-------------------\r\n"; next;})); } close OUT ; close IPS ;

      sanju7:

      To make the output go to the "telnet.log" file handle, you need to tell the print statement to use the file handle! For instance, change:

      print "Bad connection.\n";

      to

      print OUT "Bad connection.\n";

      ...roboticus

        Roboticus:

        Thanks for reply, i think i am just overwhelmed of the obstacles to achieve the task. I have some success in the form of basic structure of the script and logic --however few more steps to go. Here is the code doing the job.

        Success: The code iterates through a text file (list of ip addresses) and telnets to the specific port and logs the error

        Issues: (a) The code for some reason doesn't logs the message when its success. When tested with a single IP its logging successfully though. (b) I am not getting how to expand an ip address which is a network (eg:10.3.3.0/24). This would make the code successfully iterate through most of the org servers if not all (assuming some of them have different network setup, firewall etc)

        The below code is the basic structure working fine but not picking the success when run on a list

        use strict; use Net::Telnet; # definitions my $testfilename = "iplist1.txt"; my $dumplog = "dumplog.txt"; my $outputlog = "outputlog.txt"; my $optionlog = "optionlog.txt"; my $inputlog ="inputlog.txt"; our $recordlog ="recordlog.txt"; my $string0 = 'Connected' ; my $string1 = "\015\012" ; my $string2 = '\\CR \\LF' ; # #open (OUT,'>>', "$recordlog"); # iterating file open (IPS, '<', $testfilename) or die('unable to open the file', $testfilename ); while (my $ip = <IPS>) { chomp $ip; my $telnett = Net::Telnet->new(Host => "$ip" +, Port => 'xxxx', Dump_log => "$dumplog", input_log => "$inputlog", o +ption_log => "$optionlog", output_log => "$outputlog", timeout => 10, + errmode => (sub { open(OUT, '>>', "$recordlog"); print OUT "Bad connection - Unable to connec +t to IP $ip at \r\n" ; print OUT "-------------------\r\n"; next;})); $telnett->open("$ip") or die "hai $telnett->errmsg "; # add Errmode + and output handle print "connected \n"; $telnett->waitfor('//'); print "carriage return: sending \\CR \\LF \n"; print "carriage return: waiting ...\n"; my $output = $telnett->put(String => $string2, Errmode => 'die', Ti +meout => '4',); print "The server returned: $output \n"; # Error handling # my $etc0 # expanding IP Networks # my $etc1 # Logging everything # my $etc2 }

        The file iplist1.txt as below

        10.xx.yy.zzz 127.0.0.1 127.0.0.1 10.aa.bb.cc 10.aaa.bb.cc

        This populates recordlog.txt only as below

        ad connection - Unable to connect to IP 10.xx.yy.zz at ------------------- Bad connection - Unable to connect to IP 10.xx.yy.zz at ------------------- Bad connection - Unable to connect to IP 10.xx.yy.zz at -------------------

        When i tested with single ip the code seems to populate dumplog file giving me some idea as to what return values i am dealing with even though I am still looking why it doesn't log to the outputlog or inputlog or optionslog. The following test code i used to populate the dumplog

        # simple telnet_test use strict; use Net::Telnet; ### #my $testfilename = "telnet-tests.txt"; my $testfilename = "iplist1.txt"; my $dumplog = "dumplog.txt"; my $outputlog = "outputlog.txt"; my $inputlog="inputlog.txt"; my $logfilename = "./log/telnetlog${t}.txt"; our $testcount = 0; our $debug = 1; ### # instantiate a new telnet object my $telnet = Net::Telnet->new(Port => 'xxxx', Timeout => 10, Telnetmod +e => '0', Errmode => 'die', Prompt => '//', Dump_log => "$dumplog", output_log = +> "$outputlog", input_log => "$inputlog" ); my $string = "\015\012" ; #my $string = '\CR \LF' ; $telnet->open("10.aaa.bb.cc") or die "hai $telnet->errmsg "; print "connected \n"; $telnet->waitfor('//'); print "about to execute carriage return \n"; print "sending \\cr waiting ...\n"; my $output = $telnet->put(String => $string, Errmode => 'die', Timeout + => '4',); print " $output \n";

        This is the screendump as below

        root@xxxxx scripts]# perl test_telnet1.pl connected about to execute carriage return sending \cr waiting ... 1

        This is how the dumpfile looks as below

        root@xxxxx scripts]# cat dumplog.txt > 0x00000: 0d 0d 0a ...

        Using telnet and interacting with it even with its very basic form needs understanding of how the application is responding to the telnet request etc. The application i am querying is kind of like SMTP service. It doesn't has a prompt or so ..thats how i deviced my code on both the scripts above matching with ('//') and trying to "put" a carriage return to the main "$telnet" object. If you have any suggestion here please let me know. I am dumping the app behavior for your understanding as below

        [root@xxxxx scripts]# telnet 10.aaa.bb.cc xxxx Trying 10.aaa.bb.cc... Connected to nodecc.dom.org.local (10.aaa.bb.cc). Escape character is '^]'. dds_pc: _ms=nodecc.dom.org.localþ_si=Process controllerþ_mid=9016þ_sev +=0þ_dt=2010/07/29þ_tm=01:12:02þ_pkg=þ Connection closed by foreign host.

        Usually on success within 30 second the telnet connection disconnects dumping the nodename and that is what i need. From the many servers around the spread out internal network this seems easiest to spot the server with that particular app, app only responds to telnet and won't otherwise (tried nmap not sure if i did correct enough switch etc though). Your expert suggestion to complete script /resolve both the issue will help me a lot.

      A few more things:

      Use lexial filehandles, the 3 argument form of open and check for success, so rather than

      open(OUT, ">>telnet.log");
      Do it like this:

      open my $out, ">>", "telnet.log" or die $!;

      Then "$ip" is a useless interpolation - just use $ip.

      Your "next" in the error-sub is not needed.

      You open OUT both in the main-script as well as in the error-sub which won't hurt but does not achieve anything.
      Depending on what you want you could either open it once and re-use the filehandle for every error, or open it for every error. If you use lexial filehandles you can open it once in the main script and reference it in the error-sub (get rid of the open there and just do "print $out "Bad connection...".)

      On a more general note you should not hard-code filenames into your script as you loose a lot of flexibility (e.g. every time you run your script you overwrite the previous error-log - maybe you want to see how that changes over time).
      A better approach would be to pass in the input-filename on the commandline (using "iplist1.txt" as a default) and print the errors not to a file but to STDOUT.
      In this way the user of your script can decide where the error-log goes to (he could simply redirect the script-output to a file of his choosing).

      Lastly use better variable-names (e.g. $error_log rather than "OUT") - you'll be glad later.