Image

Image

Search This Blog

Thursday, June 05, 2014

Allow login only if the member of a certain OU comes from a certain IP subnet

@echo off
:: (c)2014 sorinakis@g*il.com
setlocal enableextensions enabledelayedexpansion
set config=c:\pair.txt

:: find the primary OU that user belongs to
for /F "tokens=3 delims=/,CN=" %%n in ('"gpresult /R | findstr CN | findstr /I %username%"') do (
 set myou=%%n
)
:: echo myou is: !myou!

:: find the client subnet (need gettscip.exe from www.ctrl-alt-del.com.au in the path somewhere)
for /F "tokens=2 delims=/: " %%f in ('gettscip.exe') do (
 for /F "tokens=1-3 delims=/." %%g in ('echo %%f') do set mynet=%%g.%%h.%%i
)
:: echo mynet is: !mynet!

:: read the config file containing the pair IP_subnet/Organisational_Unit (or group)
:: the pair have to be separated by a space, ex: '192.168.1 Users' comments start with ;
for /F "eol=; tokens=1,2 delims=/ " %%l in ('type !config!') do (
 set net=%%l
:: set group=%%m
 set ou=%%m

:: find if the user belongs to a group
rem for /f %%f in ('"net user /domain %username% | findstr /i %group%"') do set /a ingroup=yes

:: if the two pairs are identical, the user can login from that subnet
 if "!net!"=="!mynet!" (
::  if "!ingroup!"=="yes" (
 if /I "!ou!"=="!myou!" (
   set canrun=yes
  )
 )
)
::echo canrun: !canrun!

:: if the user can't login let him know, then end the session
if NOT "!canrun!"=="yes" (
 echo Sorry %username%, "!myou!" are NOT ALLOWED to login from !mynet!.0/24
 msg %username% Sorry, %username% is NOT ALLOWED to login from this location.
 shutdown /l
)

:: Cleanup variables at end
endlocal

Blog Archive