perl scipt:syntax error of unexpected token while spawing bash command using expect module

StackOverflow https://stackoverflow.com/questions/21621180

  •  08-10-2022
  •  | 
  •  

Pregunta

I am writing perl script to copy a directory to remote machine. I am using an expect module to expect the password and send password.

But getting a syntax error as below

sh: -c: line 0: syntax error near unexpected token scp'
sh: -c: line 0:
system(scp -r /home/user1/data/ 192.168.0.1:/tmp/)'

perl script is:

use Expect;  
$Expect::Debug=2;

$cmd="scp -r /home/user1/data/ 192.168.0.1:/tmp/";

my $exp1=Expect-> spawn("system($cmd)") or die print "cannot spwan process\n";


$exp1-> expect(10,["root@192.168.0.1's password: "=>sub{ $exp1-> send("usr1234\r");}]);

Thank you in advance

¿Fue útil?

Solución 2

I am not entirely sure what goes wrong in your script (execpt for the spawn(system($cmd)) of course, but that is solved in the comments already. Maybe the => is not needed? Or you need to end the password with \n instead of \r? Anyways, it is quite simple minded. I used something like the following to great effect (note that $rsync is my Expect object).

    $rsync=Expect->spawn ("rsync $remUser\@$remIp:$remFiles $locFolder");

    if (! defined($rsync))
    {
        die "spawning failed. Probably fork failed: $!";
    }

    my $matchStatus = $rsync->expect(100, '-re', '(.+)');

    if (! defined $matchStatus)
    {
        die "Nothing got returned within 100 seconds. $!";
    }

    my $spawned = 0;
    while ($spawned eq 0)
    {
        my $return = $rsync->match();

        if ($return =~ m/command not found/)
        {
            die "Command not found, there appears to be no rsync... $!";
        }
        elsif ($return =~ m/RSA key fingerprint is/)
        {
            $rsync->send ("yes\n");
            sleep(5);
        }
        elsif ($return =~ m/password/)
        {
            $rsync->send($password,"\n");
            $spawned = 1;
        }
        else 
        {
            print "rsync answered:\n\n";
            print "$return \n";
            print "I did not expect that. EXIT\n";
            exit(1);
        }
    }

print "Sent Pw...\n";

That handles more different answers and can more easily be modified and debugged. But is a lot longer obviously. I prefer explicit to elegant though.

Otros consejos

spawn expects a shell command, not Perl code. So:

my $exp1=Expect-> spawn($cmd)) or die;

The error message you see is just your shell saying it doesn't know what to do with 'system(scp...'.

And: You'll want to mask the '@'.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top