Very new to perl and have been stuck for quite awhile on this.
If I change the variable from READSTDIN to google.com, it says google.com is online as it should. If I use the STDIN and input google.com and print $host it prints google.com, however in the ping it doesn't work.
Sample output:
perl perl.pl
What is the website that is offline or displaying an error?google.com
Warning: google.com
appears to be down or icmp packets are blocked by their server
Code:
use strict;
use warnings;
use Net::Ping;
#optionally specify a timeout in seconds (Defaults to 5 if not set)
my $timeout = 10;
# Create a new ping object
my $p = Net::Ping->new("icmp");
#Domain variable
print "What is the website that is offline or displaying an error?";
my $host = readline STDIN;
# perform the ping
if ( $p->ping( $host, $timeout ) ) {
print "Host $host is alive\n";
} else {
print "Warning: $host appears to be down or icmp packets are blocked by their server\n";
}
# close our ping handle
$p->close();
If I change the variable from READSTDIN to google.com, it says google.com is online as it should. If I use the STDIN and input google.com and print $host it prints google.com, however in the ping it doesn't work. I appreciate anyone who can help me at all!
Note the newline in your input:
perl perl.pl
What is the website that is offline or displaying an error?google.com
Warning: google.com <--- newline after google.com puts the rest of the output on the next line...
appears to be down or icmp packets are blocked by their server
You should be using chomp to remove the newline from your input:
chomp( my $host = readline STDIN );
Or more simply:
chomp( my $host = <STDIN> ); # same thing as above
Related
I am trying to test a specific server is up and running on a certain port so I am using
$result = `echo exit | telnet 127.0.0.1 9443`; print $result;
Here I am using localhost for privacy issues
The expected behavior is that it should print "...Could not open connection to the host, on port 9443: Connect failed", this way I know that the server is not running. but it prints an empty string
Any help on this
The failure message is printed to STDERR, while backticks return only what goes to STDOUT.
You can redirect the STDERR stream to the STDOUT stream
$result = `echo exit | telnet 127.0.0.1 9443 2>&1`;
See I/O redirection.
There are more rounded ways to do this, using various forms of open. See it in perlfaq8. There are also various modules for this. The Capture::Tiny makes it rather easy.
use warnings 'all';
use strict;
use Capture::Tiny qw(capture);
my $cmd = 'echo exit | telnet 127.0.0.1 9443';
my ($stdout, $stderr) = capture {
system ( $cmd );
};
print "STDOUT: $stdout";
print "STDERR: $stderr";
This prints for me
STDOUT: Trying 127.0.0.1...
STDERR: telnet: connect to address 127.0.0.1: Connection refused
The module has many more capabilities. From the docs
Capture::Tiny provides a simple, portable way to capture almost anything sent to STDOUT or STDERR, regardless of whether it comes from Perl, from XS code or from an external program.
I have a perl script to telnet to particular IP and port number. However, if i print the result after establishing connection, the port number is 23 (default). As a result, at commands triggered from script are not encouraged by modem.
Below is my script. Please advise.
Script:
#!/usr/bin/perl -w
use lib ("/u/dclement/lib/perl");
use Net::Telnet ();
$HOSTNAME = "192.168.xx.xx";
$HOSTPORT = "9998";
$conn = new Net::Telnet (Timeout => "1");
$conn->binmode(1); # don't translate CRLF
$conn->errmode("return"); # enable error trapping
$conn->telnetmode(0); # turn off telnet mode
$conn->dump_log("LOGFILE"); # output log file filehandle
$conn->output_record_separator("");
print "CONNECTING TO $HOSTNAME and $HOSTPORT\n";
# open connection to host $HOSTNAME and port $HOSTPORT
# and die if there is a problem
unless ($conn->open(Host => $HOSTNAME, Port => $HOSTPORT))
{
die "Error opening socket:: ".$conn->errmsg();
}
print "CONNECTED TO ".$conn->host().", PORT ".$conn->port()."\n";
OUTPUT
CONNECTING TO 192.168.xx.xx and 9998
CONNECTED TO 192.168.xx.xx, PORT 23
Can you try below code and see if any connectivity issue 9998 port:
$telnetOutput =telnet 192.168.xx.xx 9998;
print "\n telnet command output1: $telnetOutput \n";
$telnetOutput =telnet 192.168.xx.xx 23;
print "\n telnet command output2: $telnetOutput \n";
I am relatively new to Perl. I am trying to store a URL in a variable. Here's my code:
my $port = qx{/usr/bin/perl get_port.pl};
print $port;
my $url = "http://localhost:$port/cds/ws/CDS";
print "\n$url\n";
This gives me the below output:
4578
/cds/ws/CDS
So the get_port.pl script is giving me the port correctly but the URL isn't getting stored properly. I believe there's some issue with the slash / but I am not sure how to get around it. I have tried escaping it with backslash and I have also tried qq{} but it keeps giving the same output.
Please advise.
Output for perl get_port.pl | od -a
0000000 nl 4 5 7 8 nl
0000006
There is noithing wrong with your $url string. The problem is almost certainly that the $port string contains carriage-return characters. Presumably you are working on Windows?
Try this code instead, which extracts the first string of digits it finds in the value returned by get_port.pl and discards everything else.
my ($port) = qx{/usr/bin/perl get_port.pl} =~ /(\d+)/;
print $port, "\n";
my $url = "http://localhost:$port/cds/ws/CDS";
print $url, "\n";
As #Сухой27 I think was trying to point out, you can use other character besides '/' with qx, to simplify syntax and then you don't have to escape the slashes.
I also added a default port 8080 in case get_port.pl does not exist.
This seems to work properly.
#!/usr/bin/perl -w
# make 8080 the default port
my $port = qx{/usr/bin/perl get_port.pl} || 8080;
print $port;
my $url = "http://localhost:$port/cds/ws/CDS";
print "\n$url\n";
output
paul#ki6cq:~/SO$ ./so1.pl
Can't open perl script "get_port.pl": No such file or directory
8080
http://localhost:8080/cds/ws/CDS
I don't know if I managed to install Net::SSH::Perl module successfully but I can't seem to be able to run the following code:
my $ssh = Net::SSH::Perl->new($remote_host);
$ssh->login($username, $password);
print "login done", "\n";
my ($out, $err, $exit) = $ssh->cmd($cmd);
print "$out", "\n";
I am able to login but cannot print the $out. I keep getting this error:
Use of uninitialized value $out in string at test_ssh.pl line 28.
Line 28 refers to print "$out", "\n";.
I am running this code on Cygwin. What should I do now?
EDIT:
I got the following error msg when I ran my $ssh = Net::SSH::Perl->new($remote_host, options => ["Debug yes"]);:
Use of uninitialized value $out in string at test_ssh.pl line 29 (#1)
(W uninitialized) An undefined value was used as if it were already
defined. It was interpreted as a "" or a 0, but maybe it was a mistake.
To suppress this warning assign a defined value to your variables.
To help you figure out what was undefined, perl will try to tell you the
name of the variable (if any) that was undefined. In some cases it cannot
do this, so it also tells you what operation you used the undefined value
in. Note, however, that perl optimizes your program and the operation
displayed in the warning may not necessarily appear literally in your
program. For example, "that $foo" is usually optimized into "that "
. $foo, and the warning will refer to the concatenation (.) operator,
even though there is no . in your program.
EDIT2:
Here's my full code
use strict;
use warnings;
use Net::SSH::Perl;
my $remote_host = '<host ip address>';
my $password = 'pass';
my $username = 'user';
my $cmd = 'copy run tftp:<my own ip address>';
warn "Starting SSH Services:...";
my $ssh = Net::SSH::Perl->new($remote_host, debug => 1);
print "done", "\n";
warn "Starting Login:...";
$ssh->login($username, $password);
print "login done", "\n";
warn "Starting command:...";
#$ssh->cmd($cmd);
#my($stdout, $stderr, $exit) = $ssh->cmd($cmd);
my ($out, $err, $exit) = $ssh->cmd($cmd);
print "$out", "\n";
The error message on "print "$out","\n";" line:
<Computername>: channel 1: new [client-session]
<Computername>: Requesting channel_open for channel 1.
<Computername>: Entering interactive session.
<Computername>: Channel open failure: 1: reason 4:
Use of uninitialized value $out in string at test_ssh.pl line 29.
LAST EDIT: I decided to use Net::Appliance::Session to login via SSH to the network devices instead. it's a lot easier to use than Net::SSH::Perl.
Please show more of your code. What is the value of $cmd?
Note that the login method doesn't perform a login: it merely stores the username and password to be used when the connection is set up for each cmd call.
The correct way of enabling debugging messages is
my $ssh = Net::SSH::Perl->new($remote_host, debug => 1);
This will give you trace information from the cmd method which should say, amongst other things
Sending command: xxx
Entering interactive session.
and should give you some clues about what is going wrong.
Your debug output shows the problem. Looking at SSH2.h, open failure reason 4 is SSH2_DISCONNECT_HOST_AUTHENTICATION_FAILED. Your username and password are incorrect.
Net::SSH::Perl does support login via username/password, I have a working example, I just got this to work. I used the code from above and took out the Double Quotes (" ") and used single quotes (' ') instead. And "debug => 1" works for debugging the code when having issues. It will display info to you when you try to login if the debug option is set.
I am connecting to a Win32-OpenSSH SSHD server based on Windows Powershell very similar to BSDLinux SSHD server with SFTP support. Supports same Linux style based connection.
I have been trying all other SSH modules all day. Hopefully someone can use this code to just run a command and get the output if required.
You can install Net::SSH::Perl with "cpan -i module-name"
use Net::SSH::Perl;
my $host = 'testmachine.acme.local'; #Or just IP Address
my $user = 'domain\username'; #Or just username
my $pass = 'Password#123';
my $cmd = 'dir C:\\Windows\\';
use Net::SSH::Perl;
my $ssh = Net::SSH::Perl->new($host, debug => 1);
$ssh->login($user, $pass);
my ($out, $err, $exit) = $ssh->cmd($cmd);
print "$out", "\n";
Net::SSH::Perl does not support login via username/password only via interactive password entry or public key. See this post for more information.
http://www.perlmonks.org/?node_id=590452
I have currently a DNS Reverse lookup script which works however there is a small little issue of the script being able to output the DNS system errors.
The problems goes like this:
User keys in false/wrong internet address name etc. "www.whyisthednsnothappening.com"
The script would then clear the screen using system(clear)
The script would then print "can't resolve DNS. The error is due to: various System error"
The script re directs the user back to the same menu/script to type in the name address again.
So the main problem is now step 3 which the script only shows me "Can't resolve DNS. The error is due to: BLANK " Which BLANK is suppose to show errors like "Bad arg length for Socket::inet_ntoa, length is 0, should be 4 at ./showdns.pl line 28, <> line 1." and the menu of the DNS script is located below of the error print.
The Codes:
#!/usr/bin/perl
use IO::Socket;
use warnings;
use strict;
use Term::ANSIColor;
use Socket;
use Sys::Hostname;
print "\nYou are now in Show DNS IP Address!\n\n";
print "*************\n";
print "|DNS Address|\n";
print "*************\n";
print "\nPlease enter a hostname that you wish to view\n\n";
print "\n\nEnter the hostname of Choice Here: ";
my $userchoice = <>;
chomp ($userchoice);
my $hostname = $userchoice;
my $i_addr = scalar(gethostbyname($hostname || 'localhost'));
if ( ! defined $i_addr ) {
my $err = $!;
my $herr = int herror(const char *s);
system('clear');
print("Can't resolve $hostname: $herr, try again");
exec("/root/Desktop/showdns.pl");
exit();
}
my $name = inet_ntoa($i_addr);
my $coloredText = colored($name, 'bold underline blue');
print "\n\nThe hostname IP address is: $coloredText\n\n";
print "Press enter to go back to the main menu\n\n";
my $userinput2 = <>;
chomp ($userinput2);
system("clear");
system("/root/Desktop/simpleip.pl");
Can someone please give advice on the codes? Thanks!
Ah, I see what you mean. The system("clear") call is clearing the $! variable before you have a chance to print the error from gethostbyname.
my $i_addr = scalar(gethostbyname($hostname || 'localhost'));
if ( ! defined $i_addr ) {
my $err = $!;
system("clear");
print("Can't resolve $hostname: $err, try again");
system("/root/Desktop/showdns.pl");
exit();
}
Though as far as I can tell, the particular error gethostbyname returns isn't very meaningful.
You may want to look into putting a loop in your script instead of having it start over using system(). You certainly don't want to continue on to inet_ntoa if there was a failure. Note that inet_ntoa doesn't have anything to do with a DNS lookup; that's done by gethostbyname. inet_ntoa just changes a 4-byte string into the normal 123.123.123.123
printable form of an ipaddress. sprintf("%vd", $i_addr) does the same thing.
Two additional questions:
If you remove the call to
system('clear') Does the error
from gethostbyname get displayed
then?
Why do you use
system('/root/Desktop/showdns.pl')
To call the same script recursively?
Wouldn't it be better to use exec
instead of system? exec terminates
the current process. while system
forks of an entire new process and
waits for that process to exit. So
if your users enter, for example, 20
invalid hostnames, you'll end up
with 20 processes just waiting for
the one that was most recently
created.
Gr,
ldx
Please check the following to resolve the above "dns" issues in perl script.
As DNS server is not running, perl will not resolve the address. so it returns an empty string and inet_ntoa will throw error for that empty string.
If you are using a linux system please verify the following:
a) Check the internet address in the file /etc/resolv.conf
nameserver 172.19.1.11 (IP address of your internet or survice provider)
b) Add "dns" in the /etc/nsswitch.conf file as follows:
hosts: files dns