繁体   English   中英

如何使用Perl在while循环中从文件切换不同的字符串

[英]How to switch different strings from file in a while loop using Perl

我有一个问题,这可能是一个简单的问题,但是我没有找到答案。

我有一个字符串文件(每个字符串在单独的行中,我需要在cmd中使用每个字符串(行)。

我正在使用“ while”循环,但是我不知道如何将每个字符串附加到循环中。

当XXX.XXX.XXX是需要在循环中更改的字符串时,我需要运行以下命令。

c:\putty\putty.exe -ssh "root@XXX.XXX.XXX.XXX" -pw "password" -m "c:\putty\putty.txt"

尝试这个:

#!/usr/bin/perl
use warnings;
use strict;

open my $fh, "<", "file.txt" or die $!;

while (my $line = <$fh>)
{
    chomp $line;

    #Here you can replace 'XXX.XXX.XXX' with '$line'. Modify below line as per your requirement. 
    my $cmd = `c:\\putty\\putty.exe -ssh "root\@$line" -pw "password" -m "c:\\putty\\putty.txt"`;
}
close $fh;

更详细的版本是:

use strict;
use warnings;

my $file = "file_of_strings.file";

# Open file and read contents before closing handle
open(FH, "<", $file) or die "Unable to open \"$file\" $!";
chomp(my @users = <FH>);
close(FH);

for my $user (@users) { 
    # Frame remote command
    my $cmd = "c:\putty\putty.exe -ssh 'root\@${user}' -pw 'password' -m 'c:\putty\putty.txt'";

    if (system $cmd != 0) {    # system command returns 0 on successful execution
        print "Successfully executed command: $cmd\n";
    } else {    
        print "Failed to execute command: $cmd exited $? $!\n"; # Better to log the exit code ($?) and error message, if any($!).
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM