Ssh, update .ssh/config for your dynamic ip

From Andreida
Revision as of 11:52, 16 February 2016 by Andreas (talk | contribs) (Created page with "If you want to access your remote/home system with an entry like the following, but the IP is a dynamic one, then continue reading <pre> Host ShortNameForYourServer HostNa...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

If you want to access your remote/home system with an entry like the following, but the IP is a dynamic one, then continue reading

Host ShortNameForYourServer
    HostName        NameOfYourServerOrIP
    Port            22
    User            smith
    ForwardAgent    no
    ForwardX11      no


  • Allow server to create file with ip

Create somewhere on your webspace a file like

<?php
if (isset($_REQUEST['set']) && $_REQUEST['set'] === "true")
{
    $ip = $_SERVER['REMOTE_ADDR'];
    file_put_contents("ip", $ip);
}
  • Call the script from the computer with the dynamic ip (ssh-server)

Create a cronjob like the following (crontab -e)

5,20,35,50 * * * * wget -q -O /dev/null  http://your-domain.com/set?set=true > /dev/null
  • Create a script on the ssh-client to modify the .ssh/config file (you need to modify the script!)

Make sure to have the following entries in your config file for this server:

No IP entries in known_hosts:

UserKnownHostsFile    /dev/null

no check for the ip:

StrictHostKeyChecking no


#!/usr/bin/php
<?php
$sUrl = "http://your-domain.com/ip";
$sProxy = 'tcp://proxy-of-your-company-or-remove-line:8080';
$sHost = 'YourSshServer';
$sConfigFilePath = "/home/you/.ssh/config";

$arrHeader = array();
$arrHeader[] = 'Content-type: application/x-www-form-urlencoded';

$arrOptions = array('http' => 
                array(
                    'method'    => 'POST',
                    'header'    => $arrHeader,
                    'proxy'     => $sProxy,
                    )
        );
$context = stream_context_create($arrOptions);
$sIp = @file_get_contents($sUrl, false, $context);

$arrFile = file($sConfigFilePath, FILE_IGNORE_NEW_LINES);

$sSearch = 'Host ' . $sHost;
foreach($arrFile as $nKey => $sLine) 
{
	if (trim($sLine) == $sSearch) 
	{
		$arrFile[$nKey + 1] = "HostName\t\t\t" . $sIp;
	}
}

file_put_contents($sConfigFilePath, implode("\n", $arrFile) );

  • Create a cronjob on your ssh client computer to call the script
10,25,40,55 * * * * /home/you/bin/update-YourSshServer.php