Jump to content

script (bat?) to check IP address of a PC and take action


Recommended Posts

I have a set of users that are circumventing my policies by connecting to another access point. my attempts to fix this on the client side have so far failed since the cheapass cisco desktop cards will not use windows wireless and the cisco utility cannot be secured. However when these users connect to the other SSID (which is still on my network but i cant restrict access to -dont ask), their IP address changes so that gave me an idea. I can run a script on my server via scheduled tasks that checks the IP address of these 15 machines every 15 minutes or so with nslookup, if the ip isnt on the approved scope, it executes something like:

shutdown /t 30 /c "dont do that" /m \\badpc

the machines are on deep freeze so they will revert and if it annoys them enough theyll stop switching SSIDs and ill stop getting emails about it.

i know how to nslookup to get the ip and then what to do once the decision is made but i dont know how to compare the current IP to the allowed set

any ideas?

Link to comment
Share on other sites


10.10.6.* bad ip range

10.10.9.* allowed ip range

as far as the method of detection i figured id either nslookup or ping would do the trick but scraping their output into variables and comparing them is the part im grey on.

nslookup machine-name-14

ping machine-name-14 /n 1

Link to comment
Share on other sites

10.10.6.* bad ip range

10.10.9.* allowed ip range

as far as the method of detection i figured id either nslookup or ping would do the trick but scraping their output into variables and comparing them is the part im grey on.

nslookup machine-name-14

ping machine-name-14 /n 1

There is casually ;) a full fledged NT FOR tokens and delimiters tutorial here:

http://www.robvanderwoude.com/ntfortokens.php

using, among the other things, PING.

A simple example with IPCONFIG is here:

http://www.boot-land.net/forums/index.php?showtopic=5881

Do an actual PING and an actual NSLOOKUP, and post the results, the parsing may be different in different language OS. :unsure:

As an example, here is an actual output of PING on my machine, pinging for a machine named "hall":

C:\>ping Hall -n 1

Esecuzione di Ping Hall [10.2.7.2] con 32 byte di dati:

Risposta da 10.2.7.2: byte=32 durata<1ms TTL=128

Statistiche Ping per 10.2.7.2:
Pacchetti: Trasmessi = 1, Ricevuti = 1, Persi = 0 (0% persi),
Tempo approssimativo percorsi andata/ritorno in millisecondi:
Minimo = 0ms, Massimo = 0ms, Medio = 0ms

Which can be parsed with a simple batch cleverly named parsehallip.cmd ;):

@ECHO OFF
FOR /F "tokens=2 delims=[]" %%A in ('PING hall -n 1 ^| FIND "["') DO (
SET hall=%%A
SET hall
)

Which, when executed results in:

C:\>parsehallip.cmd
hall=10.2.7.2

jaclaz

Link to comment
Share on other sites

hers what my ping and nslookup outputs look like

C:\>ping machine-name-14 /n 1

Pinging machine-name-14.ad.domain.com [10.10.9.200] with 32 bytes of data:

Reply from 10.10.9.200: bytes=32 time=16ms TTL=125

Ping statistics for 10.10.9.200:
Packets: Sent = 1, Received = 1, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
Minimum = 16ms, Maximum = 16ms, Average = 16ms

C:\>nslookup machine-name-14
Server: dc-01.ad.domain.com
Address: 10.10.2.2

Name: machine-name-14.ad.domain.com
Address: 10.10.9.200


C:\>

Link to comment
Share on other sites

I do not know if this VBS script will help you. What this script does is ping

10.10.6. from 0 to 255 if there a positive reply then it added to a txt file.

Save as PingMultiComputers.vbs

Option Explicit 

Dim Act :Set Act = CreateObject("Wscript.Shell")
Dim Fso :Set Fso = CreateObject("Scripting.FileSystemObject")
Dim Wmi :Set Wmi = GetObject("winmgmts:\\.\root\cimv2")
Dim C1, Obj, Lne,Ping, Ts, Txt, ZZ
Lne = " ---------------------------------- "
Txt = Fso.GetParentFolderName(WScript.ScriptFullName) & "\PingResults.txt"
C1 = 0

ZZ = MsgBox("This Script Will Take Approx 15 Minutes To Run",4132,"Continue Yes Or No")
If ZZ = 6 Then PingAll()

Function PingAll()
Act.Popup "Beginning Script",5,"Active Script",4128
Set Ts = Fso.CreateTextFile(Txt)
Ts.WriteLine Vbcrlf & " Start Time : " & Now
Ts.WriteLine Lne & vbCrLf
Do Until C1 = 255
Set Ping = Wmi.ExecQuery("Select * From Win32_PingStatus where Address = '10.10.6." & C1 & "'")
For Each Obj in Ping
If IsNull(Obj.StatusCode) Or Obj.StatusCode <> 0 Then
'-> Uncomment Below If You Want Off Line Results
' Ts.WriteLine " Off Line :" & Obj.Address
' Ts.WriteLine Lne
Else
Ts.WriteLine " On Line :" & Obj.Address
Ts.WriteLine Lne
End If
Next
C1 = C1 + 1
Loop
Ts.WriteLine vbcrlf & " End Time : " & Now
Ts.WriteLine Lne
Ts.Close
Act.Run("notepad " & Chr(34) & Txt & Chr(34)),1,True
End Function

Link to comment
Share on other sites

Since the pinged machine address is also in square brackets [], the snippet will work allright.

Let's go on, let's call it checkping.cmd:

@ECHO OFF
SETLOCAL ENABLEEXTENSIONS
SETLOCAL ENABLEDELAYEDEXPANSION
::Usage: checkping.cmd machine-name
SET Target=%1
IF %Target%.==. ECHO Missing target!&PAUSE&GOTO :EOF
FOR /F "tokens=2 delims=[]" %%A in ('PING %Target% -n 1 ^| FIND "["') DO (
SET TargetIP=%%A
)
IF NOT DEFINED TargetIP ECHO NO IP found!&PAUSE&GOTO :EOF
SET TargetIP
:Compare

jaclaz

Link to comment
Share on other sites

Here's another option, something I threw together in a few mins, quick and dirty:

option explicit
on error resume next
dim shl, fso, pc, list, qry, wmi, colping, ping, rwmi, colcomp, comp, user, logfl
const in_file = "pc_list.txt"
const log_file = "caught.txt"

Set shl = createobject("Wscript.Shell")
set fso = createobject("Scripting.FileSystemObject")
set list = fso.opentextfile (in_file, 1) '1=ForReading
do until list.atendofstream
pc = list.readline
if(pc<>"") then process(pc)
Loop

function process(compname)
qry = "Select * From Win32_PingStatus Where Address = '" & compname & "'"
set wmi = getobject("winmgmts:\\.\root\cimv2")
set colping = wmi.execquery(qry)
for each ping in colping
if ping.statuscode=0 then
'PC is reachable, verify IP range
if(left(ping.protocoladdress,8)) = "10.10.6." then
'we've got ourselves a rule breaker!
set rwmi = getobject("winmgmts:{impersonationLevel=impersonate}!\\" & compname & "\root\cimv2")
qry = "Select * From Win32_ComputerSystem"
set colcomp = rwmi.execquery(qry)
for each comp in colcomp
user = comp.username
next
set logfl = fso.opentextfile(log_file, 8, true) '8=ForAppending
logfl.writeline(now() & ", " & compname & ", " & ping.protocoladdress & ", " & user)
logfl.close
shl.run ("shutdown /t 30 /c " & chr(34) & "dont do that" & chr(34) & " /m \\" & compname)
end if
end if
next
end function

It will read the PC names from the file called "pc_list.txt" (no need to worry about trailing blank lines either). Then it'll "ping" them using WMI. If they're reachable and it starts with 10.10.6. then it logs everything (timestamp, computer name, IP and logged on user) in caught.txt (just change the file names in the constants) in CSV format so you can see who are doing it and finally calls shutdown the way you wanted it. It executes pretty much instantly (<1sec for 15 PCs here, ICMP ping latency being the biggest slowdown).

No error-prone text parsing of slow-running utils (like ping or nslookup) involved either (which usually fails should any error message should be returned instead of the expected output -- expect those to crash for a number of reasons, like the PC being turned off, wifi glitches, DNS not resolving, an IPv6 address being returned instead, your own connection having a hiccup or many other common issues -- quite error prone really, in fact, the "solution" in post #7 doesn't work *at all* on Win7, it just hangs there, even with a valid host!). The only "external requirement" is shutdown.exe which you wanted to call. It would be trivial to log different stuff, matching bad IP ranges using regular expressions or whatever else you so please.

It's not tested very much (only inside one VM, as my entire "real" network is all on IPv6), poorly commented, ugly in general, and has little to nothing in terms of error handling or anything like that. It assumes the account running the script (you, or whichever user account you'll use to schedule this to run every few mins) has permissions to run WMI queries on the remote PCs, NTFS permissions to write the log file and such, so you might have to do some debugging (run whateverscriptname.vbs //x to start the debugger -- visual studio works fine for this too)

Hopefully that helps :)

Link to comment
Share on other sites

Here's an all in one batch idea:

(untested)

@FOR /F "EOL=@" %%# IN (%~sf0) DO (
@PING %%#|FIND "10.10.6.">NUL 2>&1&&SHUTDOWN /r /t 20 /c "Goodbye!" /m \\%%#)
@GOTO :EOF
SPARE_PC
ANOTHER-WS
DICKSCOMP
BADBOYZ
etc.

From line four onwards each line will contain your individual computer names.

Link to comment
Share on other sites

thanks guys I knew this was possible but didnt expect that id have multiple choices. I think im going to use CoffeeFiends version because logging this would be nice since it will potentially be rebooting up to 15 machines without confirmation so being able to backtrace and tell when it was done would be helpful. Oh how I hope the same batch of misbehaving students is here on Monday. I can see it now:

My know-it-all student comes in and switches his PC to the other SSID and shows the other ones how to do it so they can all stream radio and dick around on myspace instead of paying attention to their instructor

15 minutes or so goes by and BAM! they all get a popup saying "This PC is not permitted to use SSIDs other than LABSSID. Rebooting..."

Mass chaos and whining occurs because they all had to save their work quickly or loose it

Instructor calls me and says "Did you do that?"

I say no your students did when they jumped APs! BUWAHAHAHAHA!

oh in case anyone thinks Im being unnecessarily mean, the instructors requested the internet to be locked down and the students in question are part of a work training program and are basically being paid learn how to get a job and very few jobs require a working knowledge of myspace :)

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...