Ssh, update .ssh/config for your dynamic ip

From Andreida
Jump to: navigation, search

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

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 > /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

$sUrl = "";
$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' => 
                    '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
Personal tools