【发布时间】:2026-02-04 04:05:02
【问题描述】:
如何避免 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 脚本中使用用户名/密码的示例编码。
【问题讨论】:
-
(1) 如果您不明白这里的答案:*.com/questions/18871267/… 要么不要使用它,要么完全按照提供的方式使用它,不要随意更改,并不会感到惊讶'不工作。 (2) 什么是“拆分”分割线,它期望得到什么值,你的配置文件是否匹配该格式?但是,按照 Dave Cross 所说的去做并使用配置文件模块(如果不是 Config::Any 那么 Config::Tiny 或 Config::Simple 将是一个好的开始)。
标签: linux perl unix sftp perl-module