Yog Yog - 5 months ago 12x
Perl Question

How to gain access to remote server from perl script using ssh command?

I am trying to gain access of remote server from perl script using ssh command and then I need to call other script file.I am using here ssh public-private key authentication to gain access with out asking any password of remote server.By executing this script i am getting this error:

Name or service not known

Here is my code:


system("ssh root@");



Second line call remote script file and third line logout from remote server and return local server.

I am not sure this code is correct.
Can anybody help to solve this problem?


There are some issues in your code.

  • Always include use strict; and use warnings; in your scripts.
  • Perl tries to interpolate the @ in system("ssh root@");, i.e. it will try to somehow evaluate an array called @1 (which doesn't exist). use strict; and use warnings; would have told you that:

    Possible unintended interpolation of @1 in string at...
    ssh: Could not resolve hostname root.2.3.4: Name or service not known.

    From this you could have seen that actually the command ssh root.2.3.4 was issued (because Perl interpolated the @1 away) which makes no sense.

    You have to either escape the @ (by prepending a backslash, \@) or use single quotes ' instead of double quotes " so that Perl doesn't interpolate that @1 array.

  • You must not use three system() calls because they are executed completely unrelated to each other. The 1st one does (well, does not) an ssh to the remote machine and gets stuck there. The 2nd call tries to execute /root/abc.pl after the 1st call has finished, i.e. it does so on your local machine. The 3rd calls simply locally executes exit in a subshell which basically does nothing.

Putting this together we get

#!/usr/bin/env perl

use strict;
use warnings;

system('ssh root@ /root/abc.pl');

This will ssh to and execute the script /root/abc.pl there (in one go) and return after the script has finished.