gpt4 book ai didi

linux - 如何避免在 perl 脚本中硬编码用户名/密码

转载 作者:太空宇宙 更新时间:2023-11-04 06:04:58 24 4
gpt4 key购买 nike

如何避免在 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 脚本中使用用户名/密码的示例代码。

最佳答案

我想你想要这样的东西。

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};

但是你最好寻找 config file module来自 CPAN。

关于linux - 如何避免在 perl 脚本中硬编码用户名/密码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18891634/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com