How to read the password from the text file in per

2019-06-14 14: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.

2条回答
Summer. ? 凉城
2楼-- · 2019-06-14 14:58

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.

查看更多
叼着烟拽天下
3楼-- · 2019-06-14 15:07

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);
}
查看更多
登录 后发表回答