How can I ssh inside a Perl script?

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

    The best way to run commands remotely using SSH is

    $ ssh user@host "command" > output.file
    

    You can use this either in bash or in perl. However, If you want to use perl you can install the perl modules in your local directory path as suggested by brian in his comment or from Perl FAQ at "How do I keep my own module/library directory?". Instead of using Net::SSH I would suggest to use Net::SSH::Perl with the below example.

    #!/usr/bin/perl -w
    use strict;
    use lib qw("/path/to/module/");
    
    use Net::SSH::Perl;
    
    my $hostname = "hostname";
    my $username = "username";
    my $password = "password";
    
    my $cmd = shift;
    
    my $ssh = Net::SSH::Perl->new("$hostname", debug=>0);
    $ssh->login("$username","$password");
    my ($stdout,$stderr,$exit) = $ssh->cmd("$cmd");
    print $stdout;
    

提交回复
热议问题