How to read the password from the text file in perl

夙愿已清 提交于 2019-12-10 12:13:12

问题


I am new to perl script, The below code is downloading the files from sftp server.

#!/usr/bin/perl

use strict;
use warnings;
use Net::SFTP::Foreign;

my $sftp = Net::SFTP::Foreign->new(
    'auser@sftp.rent.com',
    password => 'auser123',
    more     => ['-v']
);

$sftp->get('outgoing/DATA.ZIP', '/home/sar/')
  or die "unable to retrieve copy: ".$sftp->error;

$sftp->disconnect;

Here i have hard codded the password, I want to avoid password in the script, Is there any other method to read the password from the file or any method is there?

I searched in the stackoverflow and google, i don't know how to use this. I tried below one.

PASSWORD=`cat /home/sar/passwd_file.txt`

my $password = $ENV{'PASSWORD'}

Could you please help me to resolve this code.


回答1:


You can store password in file with limited permissions, but using ssh keys is still better solution.

my $sftp = Net::SFTP::Foreign->new(
    'auser@sftp.rent.com',
    password => get_passw("chmod_600_passw_file"),
    more     => ['-v']
);

sub get_passw {
  my ($file) = @_;
  open my $fh, "<", $file or die $!;

  my $pass = <$fh>; # do { local $/; <$fh> };
  chomp($pass);

  return $pass;
}

If you want to store both user/pass in file separated with : you can,

my $sftp = Net::SFTP::Foreign->new(
    get_credentials("chmod_600_passw_file"),
    more     => ['-v']
);

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



回答2:


To do it exactly like you outlined, first create a shell script in which you run that PASSWORD environmental variable setting command and then launch the perl script you are writting. Of course, incorporate the second (perl) line that you found into your script.

It won't be much safer though, you should consider using other forms of authentication.



来源:https://stackoverflow.com/questions/18871267/how-to-read-the-password-from-the-text-file-in-perl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!