如何在 Perl 脚本中使用 ssh? [英] How can I ssh inside a Perl script?

查看:34
本文介绍了如何在 Perl 脚本中使用 ssh?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过 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 中的建议在您的本地目录路径中安装 perl 模块如何保留自己的模块/库目录?".我建议不要使用 Net::SSH,而是在下面的示例中使用 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆