Shop

My New Shop
MTS Creations

Subscribe to My YouTube Channel

Wednesday, May 29, 2013

Dynamic Hosts File for Work/Home

I run a server at my house and needed a better way to switch my hosts file for when I'm at home or when I'm anywhere else with my laptop (mainly work).

So I pieced this script together from multiple other scripts that I found online.
First, it checks my IPCONFIG for IPv4 and then grabs the first one and checks it against my home IP schema. Depending on what it finds it XCOPYs the corresponding _work/_home hosts file to the hosts file.

In the hosts file I just simply have the host names for my domains listed to my home servers internal IP address.

I add this script to my "Startup" folder so it runs every time that I start my laptop.

@echo off
IPCONFIG |FIND "IPv4" > c:\TEMPIP.txt
FOR /F "tokens=2 delims=:" %%a in (c:\TEMPIP.txt) do (
    if defined IP (
        echo "IP is defined %%a"
        exit /b 9993
    ) else (
        set IP=%%a
        call :process "%%a"
    )
)

:process
del c:\TEMPIP.txt
set IP=%IP:~1%
echo Your Internal IP Address should be "%IP%"
IF not x%IP:10.0.25.=%==x%IP% (
    call :home
    GOTO :EOF
) ELSE (
    call :work
    GOTO :EOF
)
pause
GOTO :EOF;

:work
IF exist "C:\Windows\System32\drivers\etc\hosts_work" (
    XCOPY /Y "C:\Windows\System32\drivers\etc\_work" "C:\Windows\System32\drivers\etc\hosts"
    echo "You are at WORK %IP%"
    move "C:\Windows\System32\drivers\etc\hosts_work" "C:\Windows\System32\drivers\etc\hosts_home"
) ELSE (
    echo "Sorry, you're still at WORK!"
)
pause
GOTO :EOF;

:home
IF exist "C:\Windows\System32\drivers\etc\hosts_home" (
    XCOPY /Y "C:\Windows\System32\drivers\etc\_home" "C:\Windows\System32\drivers\etc\hosts"
    echo "You are at HOME %IP%"
    move "C:\Windows\System32\drivers\etc\hosts_home" "C:\Windows\System32\drivers\etc\hosts_work"
) ELSE (
    echo "WOW! Did you stay home?"
)
pause
GOTO :EOF;

:EOF
Post a Comment