如何避免perl脚本中的硬编码用户名/密码
我是perl的新手我已经尝试过很多东西对我来说没什么用,请帮助提供一些从配置文件中读取用户名/密码的方法。我需要在这里改变什么,
以下是我的perl脚本:
#!/usr/bin/perl -w
use strict;
use warnings;
use Net::SFTP::Foreign;
my $server="sftp.abcpvt.com";
my $remote="outgoing_folder";
my $user="auser";
my $LOCAL_PATH="/home/sara";
my $file_transfer="DATA.ZIP";
my $password="abc123"
my %args = (user => "$user", password => "$password");
chdir $LOCAL_PATH or die "cannot cd to ($!)\n";
my $sftp = Net::SFTP::Foreign->new(host=>$server,user=>$user,password=>$password) or die "unable to connect";
$sftp->error and die "SSH connection failed: " . $sftp->error;
$sftp->get("$remote/$file_transfer","$LOCAL_PATH/$file_transfer") or die "unable to retrieve file".$sftp->error;
undef $sftp;
exit;
我的配置文件包含以下内容。
Username = “auser”;
Password = “abc123”;
Time_out=180;
Port = 22
我尝试了以下内容,
my $user=get_credentials("/home/sar/config");
my $password=get_credentials("/home/sar/config");
sub get_credentials {
my ($file) = @_;
open my $fh, "<", $file or die $!;
my $line = <$fh>;
chomp($line);
my ($user, $pass) = split /:/, $line;
return ($user, password => $pass);
}
这里我只收到密码,用户名不在这里......
请您分享使用perl脚本中的用户名/密码的示例编码。
答案 0 :(得分:0)
我想你想要这样的东西。
sub get_config {
my ($file) = @_;
open my $fh, "<", $file or die $!;
my %config;
while (<>) {
chomp;
next unless /\S/;
my ($key, $val) = split /\s*=\s*/;
$val =~ s/^"//;
$val =~ s/"$//;
%config{$key} = $val;
}
return \%config;
}
my $config = get_config('/home/a911091/config');
my $user = $config->{Username};
my $pass = $config->{Password};
但是,如果从CPAN中寻找config file module,你会好得多。