singho has asked for the wisdom of the Perl Monks concerning the following question:

Below is a script in perl what i want to do it to login to a host, run a few commands, but don't want to use mutilple ssh session, i want it to be done in one ssh session itself, it should check the OS (Linux/Solaris) and then run the commands appropriately and print the output in below format. hostname:domainname:OS Release version Right now, i am able to login to the box but am not able to collect the output, i get the output but the output comes line by line.
#!/usr/bin/perl #use strict; use warnings; # Checking details of the host. Domainname and the OS version will be +checked. my $SSH = '/usr/bin/ssh -o StrictHostKeyChecking=no' ; my $DOMAIN = '/bin/domainname'; my $LINUXOS = 'cat /etc/redhat-release'; my $UNIXOS = '/bin/uname -sr'; print "Enter the filename: "; chomp($HOSTLIST = <STDIN>); open HOSTS, $HOSTLIST or die "can't open the file: $!\n" ; foreach my $host (<HOSTS>) { chop($host); # if i do not use chop, ? comes in the ssh command. @details = qx($SSH $host $DOMAIN; $LINUXOS); print @details; }

1. Please help me to run the commands in one ssh session only, i know other way to do it by creating another script and calling it from the ssh command, but don't want like that.

2. How can i put checks while logged into the system and runnign the command, for particular system(in my case Linux/Solaris).

3. How the formatting of the output can be done, instead of it coming line by line.

Replies are listed 'Best First'.
Re: Check host
by sauoq (Abbot) on May 11, 2012 at 19:44 UTC
    @details = qx($SSH $host $DOMAIN; $LINUXOS);

    You want to pass multiple commands to the server separated by that semicolon. In your case, shell interpretation is going on locally. consider the difference between these two command lines:

    $ ssh foo@bar.com /bin/domainname; cat /etc/redhat-release $ ssh foo@bar.com '/bin/domainname; cat /etc/redhat release'
    Your code is doing the first. Add some quotes.

    -sauoq
    "My two cents aren't worth a dime.";
Re: Check host
by pklausner (Scribe) on May 11, 2012 at 15:17 UTC
    Have you considered the ControlMaster option? This would allow you to have multiple ssh calls which you then can format per command. But under the hood you still have only one ssh session.
Re: Check host
by bulk88 (Priest) on May 12, 2012 at 16:12 UTC
    You need to use IPC::Open3 and the "-t" flag to openssh. You can then get file handles to a ssh session and you can read and write from perl as if you were a human typing on the keyboard on the local console to and from ssh and to and from the remote shell. The biggest nightmare will be deadlocking since there is no way to do non-blocking or "peek()" or timeout reads on the handles to SSH. Do any monks have a solution to deadlocking on Open3 handles?