How can I ssh inside a Perl script?

后端 未结 9 1020
猫巷女王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:09

    or, assuming host keys are present and you want to do something with the command ouput ...

    open(SSH,"/usr/bin/ssh you\@server ps aux |") or die "$!\n";
    while (<SSH>) { 
       # do stuff with $_ 
    }
    close SSH;
    
    0 讨论(0)
  • 2020-12-09 13:11

    Assuming that you're in an environment like me where you can't add additional modules and you can't create an Identity file, then you can use this script as a starting point.

    If you can set up ssh keys then simply use the backticks command already posted, although you might need the -i option

    #!/usr/bin/perl
    use warnings;
    use strict;
    use Expect;
    use Data::Dumper;
    
    my $user = 'user';
    my $pw = 'password';
    my $host = 'host';
    my $cmd = 'id';
    
    my $exp = new Expect;
    $exp->log_file("SSHLOGFILE.txt");
    $exp->log_stdout(0);
    $exp->raw_pty(1);
    
    
    my $cli = "/usr/bin/ssh $user\@$host -o StrictHostKeyChecking=no -q $cmd";
    
    $exp->spawn($cli) or die "Cannot spawn $cli: $!\n";
    
    $exp->expect(5,
     [ qr /ssword:*/ => sub { my $exph = shift;
                              $exph->send("$pw\n");
                              exp_continue; }] );
    
    my $read = $exp->exp_before();
    chomp $read;
    print Dumper($read);
    
    $exp->soft_close();
    
    0 讨论(0)
  • 2020-12-09 13:12

    If you have ssh host keys setup you can simply run the ssh system command and then specify the command to run on the machine after that. For example:

    `ssh user@remoteserver.domain.com id`
    

    You should be able to chomp/store that output.

    0 讨论(0)
提交回复
热议问题