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

Hi, I am a newbie to the perl world. kindly help me with solution to solve my issue. Scenario: I am trying to login into localhost and want to print "pwd" command which is not working. Note/FYI: I have used "/bin/pwd" instead of "pwd" also. I am not able to get the output. Kindly help on this. Script is as below.
#!/usr/bin/perl use Expect; $user = "root"; $pass = "redhat"; $hostname = "localhost"; $comm = "pwd"; $Expect::Log_Stdout = 1; $match = '# '; $session=Expect->spawn("ssh $user\@$hostname") or die "Error calling external program: $!\n"; $session->log_file( 'output.txt' ); unless($session->expect(1,"password: ")) {}; $session->send("$pass\n"); unless ($session->expect(1,'-re', $match)){print "\nNOT FOUND...\n"}; $session->send("$comm\r"); $session->log_file( 'output.txt' );

Replies are listed 'Best First'.
Re: perl expect moudule to interact with Linux terminal
by ww (Archbishop) on Mar 29, 2015 at 18:23 UTC

    Please format data and code using code tags (e.g. <c> & </c>) around data or code which will then format as you see in this sentence. Make it easy for us to help you!

Re: perl expect moudule to interact with Linux terminal
by pme (Monsignor) on Mar 30, 2015 at 06:38 UTC
    Hi kkbka,

    If you have 'expect' installed on your system you can use 'autoexpect -c ssh root@localhost' to create working native expect solution (script.exp). That may give ideas what is wrong with your perl script.

      Thanks for your reply. I tried with autoexpect also but no luck.

      Kindly let me know, how to escape the "#" in perl. I tried like "\#", but its not escaping, instead of that it assumes the following character are commented

        This little piece of code works for me. Beside replacing '???' at $user and $pass you should also replace '\$' with '#' in all three cases.
        use strict; use Expect; my $user = "???"; my $pass = "???"; my $hostname = "localhost"; my $comm1 = "pwd"; my $comm2 = "date"; my $comm3 = "exit"; $Expect::Log_Stdout = 1; my $session = Expect->spawn("ssh $user\@$hostname") or die "Error call +ing external program: $!\n"; $session->expect(5,"password: "); $session->send("$pass\r"); $session->expect(5, "\r \$"); $session->send("$comm1\r"); $session->expect(5, "\r \$"); $session->send("$comm2\r"); $session->expect(5, "\r \$"); $session->send("$comm3\r"); $session->expect(undef);