How can I ssh inside a Perl script?

后端 未结 9 1043
猫巷女王i
猫巷女王i 2020-12-09 12:14

I want to SSH to a server and execute a simple command like \"id\" and get the output of it and store it to a file on my primary server. I do not have privileges to install

9条回答
  •  一生所求
    2020-12-09 13:01

    I know this is a very old thread, but since I encounter the same problem I found another useful solution in case that someone is using Linux.

    #!/usr/bin/perl
    use strict;
    use warnings;
    use Data::Dumper;
    
    my $host = $ARGV[0];
    my $port = $ARGV[1];
    my $cmd = $ARGV[2];
    
    my @output = readpipe( "ssh -p ".
                   $port." ".
                   $host." ".
                   $cmd."" );
    
    chomp @output;
    
    print Dumper \@output;
    
    __END__
    
    perl sample.pl 127.0.0.1 22 "which perl"
    Ubuntu 16.04.1 LTS
    $VAR1 = [
              '/usr/bin/perl'
            ];
    

    This assumes that you have configured ssh-keys so no user input will be required. I did not want to have hard coded values this is the best way for me that worked the best. I am using readpipe to achieve that.

    Hope this helps to have a solution in case of not hard coding.

提交回复
热议问题