如何在Perl脚本中使用ssh? [英] How can I ssh inside a Perl script?
问题描述
我想SSH到服务器并执行一个简单的命令,例如"id",并获取它的输出并将其存储到我的主服务器上的文件中.我没有安装 Net :: SSH 的特权,这会使我的工作非常容易.请为此提供解决方案.我尝试使用后退标记,但无法将输出存储在运行脚本的计算机上.
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 Net::SSH which would make my task very easy. Please provide me a solution for this. I tried using back-ticks but I am not able to store the output on the machine from which my script runs.
推荐答案
使用SSH远程运行命令的最佳方法是
The best way to run commands remotely using SSH is
$ ssh user@host "command" > output.file
您可以在bash或perl中使用它.但是,如果要使用perl,则可以按照brian在他的评论中的建议或在Perl FAQ中的"如何保留自己的模块/库目录?".建议不要使用Net :: SSH :: Perl和下面的示例.
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;
这篇关于如何在Perl脚本中使用ssh?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!