【问题标题】:Alter code to be simple in Net::OpenSSH在 Net::OpenSSH 中将代码更改为简单
【发布时间】:2018-02-09 15:14:55
【问题描述】:

我是 Perl 编程的新手,目前正尝试在我的代码中使用 Net::OpenSSH 模块,我的新代码如下,其任务是在远程服务器中运行多个命令,

代码如下::

---
---
foreach $s (@servers) {
my $ssh = Net::OpenSSH->new("$username\@$s", timeout=>30);
$ssh->error and die "Unable to connect: " . $ssh->error;
print "Connected to $s\n";

my $fh = $ssh->capture("df -k /home/ | tail -1") or die "Unable to run command\n";
my @df_arr = split(/\s+/, $fh);
print "$s:  Disk space /home/ = $df_arr[3] \n";

my $fh1 = $ssh->capture("svmon -G -O unit=GB | grep memory") or die "Unable to run command\n";
my @sv_arr = split(/\s+/, $fh1);
print "$s:  Free memory = $sv_arr[3] \n\n";

close $fh;
undef $ssh;
}
----
----

这段代码不太好,因为我打算让它更简化并尽可能减少一行。

我可以使用任何技术或方法来简化此代码吗?

【问题讨论】:

标签: regex perl server


【解决方案1】:

我们以这种方式实现它的方法:

  1. sub ssh_connect($username, $password) $ssh = ssh_connect($username, $password)
  2. sub ssh_execute($ssh, $command_str)

你的源代码中重复的代码太多了,也许你可以把它们放到一个子程序中重复使用。

【讨论】:

    猜你喜欢
    • 2011-04-22
    • 1970-01-01
    • 2015-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多