【问题标题】:How to avoid the hard coded username/password in perl script如何避免 perl 脚本中硬编码的用户名/密码
【发布时间】: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


【解决方案1】:

我想你想要这样的东西。

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

【讨论】:

  • 我收到错误无法在 @INC 中找到 config.pm(@INC 包含:/usr/lib64/perl5/site_perl/5.8.8/x86_64-linux-thread-multi...是否可以在没有配置模块的情况下读取用户名和密码...请帮我戴夫
  • 这里我将使用文本文件而不是配置来存储用户名/密码/端口号/time_out
  • “无法在 @INC 中找到 config.pm”。什么是config.pm?你是从哪里弄来的?你是说 Config.pm 吗?
  • 我认为这根本无法回答我的问题。