Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace host key automatically on linux

Tags:

perl

sftp

I have a script that connects to an SFTP server with the following code:

use Net::SFTP::Foreign;
my %cfg = (
    user        => "$user", 
    password    => "$password",
    port        => 22,
    more        => [-o => 'StrictHostKeyChecking no']
);
my $sftp = Net::SFTP::Foreign->new("$host",%cfg);

I am using StrictHostKeyChecking to make sure the script automatically accepts the ssh key. The issue begins when the server replaces the host key with new one. I get the error: WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!

So I have to manually remove the key by running ssh-keygen -R testserver.com After that the script works fine again. I am trying to find a way to autmatically replace the key if it changes. Technically I can run ssh-keygen -R testserver.com every time the script runs, but I do not like that solution. So far I am not able to a good automated way to replace the key.

like image 559
Andrey Avatar asked Oct 14 '25 14:10

Andrey


1 Answers

Add another option that points UserKnownHostsFile to /dev/null should do the trick, not that it's recommend from security perspective ;-)

use Net::SFTP::Foreign;
my %cfg = (
    user        => "$user", 
    password    => "$password",
    port        => 22,
    more        => [-o => 'StrictHostKeyChecking=no',
                    -o => 'UserKnownHostsFile=/dev/null']
);
my $sftp = Net::SFTP::Foreign->new("$host",%cfg);
like image 121
runwuf Avatar answered Oct 17 '25 09:10

runwuf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!