Thursday, December 12, 2013

change system SQL database connection

In windows you can create a database connection for your front end program to use.  Well as with all things in life things change, you decide to get a new database server, you messed up on the initial imaging of the workstations, you decided to expand or consolidate your database servers.  Instead of having to go around to each desktop and dig through control panel on each one to edit the database connection, here's a script to change the server.

This does not create a new database connection on each computer, for that you'll probably want to do configuration through control panel on one of the computers and then export it out the HKLM\SOFTWARE\Wow6432Node\ODBC\ODBC.INI or HKLM\SOFTWARE\ODBC\ODBC.INI keys to a file.

If your database is something other then CMS you'll need to change the key path referenced below.




@echo off
if "%1" == "" goto needarguments
for /f "tokens=2" %%W in ('date /t') do set dater=%%W
for /f "tokens=1-3 delims=/" %%d in ('echo %dater%') do set curdate=%%f%%d%%e
rem what we're changing the CMS database server to.
set dsnserver=newprod



:nextcomp
set remotecomp=%1
rem need to do some ping checks and stuff
echo updating %1 at %time%


for /f "tokens=2 skip=1 delims==" %%q in ('ping -n 1 %1') do set pingtimer=%%q
for /f "tokens=1 delims=m" %%s in ('echo %pingtimer%') do set pingtime1=%%s


if "%pingtime1%" == "1 Received " set pingtime1=down
if "%pingtime1%" == "down" echo %1 down at %date% %time% >> pc-down-dsn-%curdate%.lst
if "%pingtime1%" == "down" goto thiscompfinished



rem this works only if changing the server, if no dsn/odbc connection is
rem yet set up, you'll need to add more registry keys then just this one.
rem echo on
if exist \\%1\c$\windows\syswow64 reg add "\\%1\HKLM\SOFTWARE\Wow6432Node\ODBC\ODBC.INI\CMS" /v Server /t reg_sz /d %dsnserver% /f
if not exist \\%1\c$\windows\syswow64 reg add "\\%1\HKLM\SOFTWARE\ODBC\ODBC.INI\CMS" /v Server /t reg_sz /d %dsnserver% /f
if errorlevel 1 echo %1 had error updating dsn on %date% %time% >> pc-error-dsn-%curdate%.lst
if errorlevel 0 echo %1 updated dsn to %dsnserver% on %date% %time% >> pc-fixed-dsn-%curdate%.lst
echo off


:thiscompfinished
shift
if not "%1" == "" goto nextcomp
echo finished at %date% %time%
goto end


:needarguments
echo usage: %0 comp1 comp2 comp3 etc...
echo make sure to not use any \\







:end

Monday, December 9, 2013

IE Tracking protection lists

Where I'm at we have a web filtering device that will display a full pdf with the employer's terms of service if you go to a website we have blocked.  Problem is one of those is facebook, and if you go to say a news site and it has a facebook like button, the news site isn't blocked, but you still get a huge pdf file come up on your screen.

Thankfully if you're running a newer version of Internet Explorer, there is a feature called "Tracking Protection Lists", while meant to improve your privacy, they can also disable the facebook "like" button that you find on many websites. Problem is digging through all of IE's settings can be a pain.  So here is a simple internal web page for users to go to load the page (just have to click a button on the page).

note: If you're using IIS to serve this you will need to go into the server's "MIME Types" and add
the .tpl extension.  I labeled it as "application/ie", IIS apparently won't serve unknown MIME types.

First file is the tracking protection list file that we want IE to load.
#------------------don't include this line in facebook-block.tpl ---------------------------
msFilterList
: Expires = 5
# blocked strings
- like.php
# domain rules
-d facebook.com
-d facebook.net
# from http://anglachelg.blogspot.com/2011/04/create-your-own-tpl-for-ie9.html
#------------------don't include this line in facebook-block.tpl ---------------------------

------index.html --- don't include this line ---------------------
<!DOCTYPE html />
<html >
<head>
<!--- from http://msdn.microsoft.com/en-us/library/hh273399%28v=vs.85%29.aspx -->
    <title>Internet Explorer 9 Tracking Protection list loader</title>
    <script type="text/javascript">
 
    function checkTP() {
    //checks whether Tracking Protection has been enabled (any list is on)
        if (window.external.msTrackingProtectionEnabled())
      {
            document.getElementById("results").innerHTML = "Tracking protection is: ON";
        } else {
            document.getElementById("results").innerHTML = "Tracking protection is: OFF";
        }
    }

    //loads a list specified by input field
    function loadTPFile() {
        var URL = document.getElementById("tplfile").value;      
        var description = 'Facebook blocking Tracking Protection List';      
        window.external.msAddTrackingProtectionList(URL, description);
    }
</script>

</head>
<body>
<!---- First check that you have tracking protection enabled by click the
"check tracking protection" button
<div>
  <button onclick="checkTP();">Check tracking protection</button>
  <span id="results">Tracking protection is: </span>
</div>
<p />
Remember that you need to have tracking protection "on" for this to work
if tracking protection is off, go to: <br>
tools, tracking protection, select "Your Personalized List" and click enable, close, <br>
then click on the "check tracking protection" button again.

--->
<p />
This is for blocking the facebook like button (and facebook's other tracking mechanisims),
that are on many websites nowdays, which cause the company's usage policy to pop up.  To stop this: <br>
click on "load TPL file"
and click on the "add list" button
<p />
<div>
  <button onclick="loadTPFile();">Load TPL file</button>
  <input id= "tplfile" type="text" value="facebook-block.tpl" size="60" />
</div>

<p />
Remember if you go to the facebook.com website itself you will still get a copy of the company's
Internet usage policy poping up.
</body>
</html>


Monday, September 23, 2013

enable basic games in windows

To enable/disable features in windows 7 you use dism (deployment image servicing and management).

The following batch file will enable the basic games (chess, minesweeper, solitaire, etc...), but not any of the internet games.
This will have to be ran with full admin privileges.

rem --------------games-enable-w7.bat--------------
rem to get a list of whats available and enabled/disabled
rem dism /online /Get-Features
echo make sure you're running this with admin privleges
dism /online /enable-feature /featurename:"InboxGames"
dism /online /disable-feature /featurename:"Internet Games"
dism /online /disable-feature /featurename:"More Games"
rem ---------end of batch script----------------


Wednesday, July 31, 2013

setting windows permissions from the command line using icacls

Why set permissions from the command line when you can just right click and check or uncheck a few boxes?

Well checking boxes is great, if you only have one computer or two, and never have to re-do it.  Once you have a few, well it's probably time to script it :)

Here are some basic ones I've used

To lock down a folder so that no one can delete what they created, a write only folder, (two liner):
icacls d:\writeonlyfolder /deny Everyone:(CI)(OI)(DE)
icacls d:\writeonlyfolder /deny Everyone:(CI)(OI)(DC)


So that people can't put any files in a folder (just subfolders)
icacls d:\parentfolder /deny "Domain Users":(WD)

This is a locked down structure, where only the creator of a folder on a share
has access to the contents, no one else can even get into the folder created, other then administrators.

rem we do want administrators and the creator of the folder though to have access
icacls d:\secured /grant:r "Domain Administrators":(OI)(CI)F
icacls d:\secured /grant:r "Creator Owner":(OI)(CI)F
allow users to create folders in the parent folder.
icacls d:\secured /grant:r users:WRXM
remove any inheritance which could cause issues.
icacls d:\secured /inheritance:r 

Background on how windows file permissions work:

Tuesday, July 9, 2013

Git revision control on windows via cygwin

With all this scripting one needs to be able to track the changes to their larger scripts.  You can do the crude append -## to the file-name where ## is some revision number, but if you have a large script that you change a lot over a long period of time, relying on this, or file system backups, just doesn't work very well.  Fortunately the programming field has revision control, and I've decided to use GIT.   Unfortunately tortoise git while it is easy to use and install, caused some issues where browsing via network neighborhood to a remote site was slowed down tremendously.

So I decide to use cygwin and the git it has, unfortunately the git gui interface (which I'm use to from tortoise git), is a little tricky to set up.

When in the cygwin setup go into the "Devel" section and select all the items that start with git, including gitk, then go to the "X11" section and select, X-Start-menu-icons, and xinit.  Once the cygwin setup program finished up, click on the start button, all programs, cygwin-x, X win server.  You should see a white terminal box pop up.  Use normal unix/linux commands to go the directory where your scripts are, and run your git commands.  The reason for using the white terminal window from the X-win-server is so that you can run gitk.  For some reason git gui gives me an error, but gitk works just fine.

The git gui that is in cygwin is just for browsing the history of your code, to actually commit changes, and do anything other then view, you will still need to use the command line:

For those new to git at the command line this is my cheetsheet
for more commands and details of the commands check http://www.vogella.com/articles/Git/article.html

first create the repository
git init

add files to the repository
git add filename

see the changes since the last commit:
git diff

commit the changes:
git commit -m "some comments"

commit a particular file:
git commit script.bat

git status

git add script.bat

git log

see the commits for a file
git log filename

see the diffs of each commit for a file
git log -p filename

see the entire history
git log --follow -p file

Thursday, May 23, 2013

Monitor Inventory script

Inventory time.  That time of the year where property control (or whatever they call it in your business), wants to know where everything is, usually for tax or insurance purposes.

There's a good chance you already have a means for easily finding a computer if you have its serial number, several products will make it so that it's at least not too hard, and you may even have your own records for the computers.  If you don't already, I have a script for that, that I'll post latter.  However property control wants to know about everything, not just the tower unit, but furniture, metal detectors, TV's, monitors, etc...

I can't help you for most of those things, but if you got property control asking you where are your different monitors, because they're hooked into the computer, or maybe you did some moving or replacing of the monitors, I have something that may help, if they have the serial numbers for the monitors.

I've only ran this on dell computers with dell monitors with admin rights to all the computers, but if you have a different setup, you can still try this script, no guarantees though.... If you still can't find your monitor, make sure the computer is on, and that it's not in a store room somewhere unplugged.


The resulting csv file looks like:
machine, monitor model, serial, mfg, date of mfg

comp1,DELL 1702FP,8G1522CGxxx1,DEL,12/2002
comp2,DELL 1907FP,DC32364Hxxx2,DEL,4/2006
comp3,DEL 1908FPBLK,D325J958xxx3,DEL,5/2009
comp4,DELL 1702FP,8G1522CGxxx4,DEL,12/2002

remember, on dell monitors at least, it only pulls approximately the last half of the monitor's serial number.

this is the batch file that has all the computers you want to check for monitors on, and runs a vbscript on each one, which saves the monitor information into a csv file.


rem monitor-inventory.bat
rem you'll probably want to change the location of the csv file
set csvfile=\\fileserver\staff\it-docs\monitors.csv
rem the first line of the csv file so you know what's in each column.
echo machine, monitor model, serial, mfg, date of mfg >> %csvfile%
rem the list of the computers are in the parenthesies for the following lines, if you have
rem a lot of computers you can add more lines, or have multiple copies of this bat file
rem with different names, and different computers listed in each
for %%C in (server reception secretary manager boss comp1 comp2 comp3 comp4 ) do cscript %progpath%mon-serial-num-v2.vbs %%C >> %csvfile% //nologo
for %%C in (comp5 comp6 video guard) do cscript %progpath%mon-serial-num.vbs %%C >> %csvfile% //nologo
rem --------------------------------------------------


The following is the core vb script that is based in large part on a script from: http://social.technet.microsoft.com/Forums/da-DK/ITCG/thread/18f72e8d-d3ee-4e51-a55d-aa5fd26db974
Some modifications were made to make it work with my batch file above.


'--------------------------------------------------------------

Option Explicit
Dim WshShell
Set WshShell = WScript.CreateObject("WScript.Shell")
Dim strComputer, message


Dim intMonitorCount
Dim oRegistry, sBaseKey, sBaseKey2, sBaseKey3, skey, skey2, skey3
Dim sValue
dim i, iRC, iRC2, iRC3
Dim arSubKeys, arSubKeys2, arSubKeys3, arrintEDID
Dim strRawEDID
Dim ByteValue, strSerFind, strMdlFind
Dim intSerFoundAt, intMdlFoundAt, findit
Dim tmp, tmpser, tmpmdl, tmpctr
Dim batch, bHeader
batch = True
'most of this script is stolen from: http://social.technet.microsoft.com/Forums/da-DK/ITCG/thread/18f72e8d-d3ee-4e51-a55d-aa5fd26db974


If WScript.Arguments.Count = 1 Then
strComputer = WScript.Arguments(0)
'batch = True
Else
strComputer = wshShell.ExpandEnvironmentStrings("")
strComputer = InputBox("Check Monitor info for what PC","PC Name?",strComputer)
End If


If strcomputer = "" Then WScript.Quit
strComputer = UCase(strComputer)


If batch Then
Dim fso,logfile, appendout
logfile = wshShell.ExpandEnvironmentStrings("%userprofile%") & "\desktop\MonitorInfo.csv"


'setup Log
Const ForAppend = 8
Set fso = CreateObject("Scripting.FileSystemObject")
If Not fso.FileExists(logfile) Then bHeader = True
set appendout = fso.OpenTextFile(logfile, ForAppend, True)


If bHeader Then
appendout.writeline "Computer,Model,Serial #,Vendor ID,Manufacture Date,Messages"
End If
End If


Dim strarrRawEDID()
intMonitorCount=0
Const HKLM = &H80000002 'HKEY_LOCAL_MACHINE
'get a handle to the WMI registry object
On Error Resume Next
Set oRegistry = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "/root/default:StdRegProv")


If Err <> 0 Then
If batch Then
EchoAndLog strComputer & ",,,,," & Err.Description
Else
MsgBox "Failed. " & Err.Description,vbCritical + vbOKOnly,strComputer
WScript.Quit
End If
End If




sBaseKey = "SYSTEM\CurrentControlSet\Enum\DISPLAY\"
'enumerate all the keys HKLM\SYSTEM\CurrentControlSet\Enum\DISPLAY\
iRC = oRegistry.EnumKey(HKLM, sBaseKey, arSubKeys)
For Each sKey In arSubKeys
'we are now in the registry at the level of:
'HKLM\SYSTEM\CurrentControlSet\Enum\DISPLAY\<VESA_Monitor_ID\
'we need to dive in one more level and check the data of the "HardwareID" value
sBaseKey2 = sBaseKey & sKey & "\"
iRC2 = oRegistry.EnumKey(HKLM, sBaseKey2, arSubKeys2)
For Each sKey2 In arSubKeys2
'now we are at the level of:
'HKLM\SYSTEM\CurrentControlSet\Enum\DISPLAY\<VESA_Monitor_ID\<PNP_ID>\
'so we can check the "HardwareID" value
oRegistry.GetMultiStringValue HKLM, sBaseKey2 & sKey2 & "\", "HardwareID", sValue
for tmpctr=0 to ubound(svalue)
If lcase(left(svalue(tmpctr),8))="monitor\" then
'If it is a monitor we will check for the existance of a control subkey
'that way we know it is an active monitor
sBaseKey3 = sBaseKey2 & sKey2 & "\"
iRC3 = oRegistry.EnumKey(HKLM, sBaseKey3, arSubKeys3)
For Each sKey3 In arSubKeys3
'Kaplan edit
strRawEDID = ""
If skey3="Control" Then
'If the Control sub-key exists then we should read the edid info
oRegistry.GetBinaryValue HKLM, sbasekey3 & "Device Parameters\", "EDID", arrintEDID
If vartype(arrintedid) <> 8204 then 'and If we don't find it...
strRawEDID="EDID Not Available" 'store an "unavailable message
else
for each bytevalue in arrintedid 'otherwise conver the byte array from the registry into a string (for easier processing later)
strRawEDID=strRawEDID & chr(bytevalue)
Next
End If
'now take the string and store it in an array, that way we can support multiple monitors
redim preserve strarrRawEDID(intMonitorCount)
strarrRawEDID(intMonitorCount)=strRawEDID
intMonitorCount=intMonitorCount+1
End If
Next
End If
Next
Next
Next
'*****************************************************************************************
'now the EDID info for each active monitor is stored in an array of strings called strarrRawEDID
'so we can process it to get the good stuff out of it which we will store in a 5 dimensional array
'called arrMonitorInfo, the dimensions are as follows:
'0=VESA Mfg ID, 1=VESA Device ID, 2=MFG Date (M/YYYY),3=Serial Num (If available),4=Model Descriptor
'5=EDID Version
'*****************************************************************************************
On Error Resume Next
dim arrMonitorInfo()
redim arrMonitorInfo(intMonitorCount-1,5)
dim location(3)
for tmpctr=0 to intMonitorCount-1
If strarrRawEDID(tmpctr) <> "EDID Not Available" then
'*********************************************************************
'first get the model and serial numbers from the vesa descriptor
'blocks in the edid. the model number is required to be present
'according to the spec. (v1.2 and beyond)but serial number is not
'required. There are 4 descriptor blocks in edid at offset locations
'&H36 &H48 &H5a and &H6c each block is 18 bytes long
'*********************************************************************
location(0)=mid(strarrRawEDID(tmpctr),&H36+1,18)
location(1)=mid(strarrRawEDID(tmpctr),&H48+1,18)
location(2)=mid(strarrRawEDID(tmpctr),&H5a+1,18)
location(3)=mid(strarrRawEDID(tmpctr),&H6c+1,18)


'you can tell If the location contains a serial number If it starts with &H00 00 00 ff
strSerFind=chr(&H00) & chr(&H00) & chr(&H00) & chr(&Hff)
'or a model description If it starts with &H00 00 00 fc
strMdlFind=chr(&H00) & chr(&H00) & chr(&H00) & chr(&Hfc)


intSerFoundAt=-1
intMdlFoundAt=-1
for findit = 0 to 3
If instr(location(findit),strSerFind)>0 then
intSerFoundAt=findit
End If
If instr(location(findit),strMdlFind)>0 then
intMdlFoundAt=findit
End If
Next


'If a location containing a serial number block was found then store it
If intSerFoundAt<>-1 then
tmp=right(location(intSerFoundAt),14)
If instr(tmp,chr(&H0a))>0 then
tmpser=trim(left(tmp,instr(tmp,chr(&H0a))-1))
Else
tmpser=trim(tmp)
End If
'although it is not part of the edid spec it seems as though the
'serial number will frequently be preceeded by &H00, this
'compensates for that
If left(tmpser,1)=chr(0) then tmpser=right(tmpser,len(tmpser)-1)
else
tmpser="Not Found"
End If


'If a location containing a model number block was found then store it
If intMdlFoundAt<>-1 then
tmp=right(location(intMdlFoundAt),14)
If instr(tmp,chr(&H0a))>0 then
tmpmdl=trim(left(tmp,instr(tmp,chr(&H0a))-1))
else
tmpmdl=trim(tmp)
End If
'although it is not part of the edid spec it seems as though the
'serial number will frequently be preceeded by &H00, this
'compensates for that
If left(tmpmdl,1)=chr(0) then tmpmdl=right(tmpmdl,len(tmpmdl)-1)
else
tmpmdl="Not Found"
End If


'**************************************************************
'Next get the mfg date
'**************************************************************
Dim tmpmfgweek,tmpmfgyear,tmpmdt
'the week of manufacture is stored at EDID offset &H10
tmpmfgweek=asc(mid(strarrRawEDID(tmpctr),&H10+1,1))


'the year of manufacture is stored at EDID offset &H11
'and is the current year -1990
tmpmfgyear=(asc(mid(strarrRawEDID(tmpctr),&H11+1,1)))+1990


'store it in month/year format
tmpmdt=month(dateadd("ww",tmpmfgweek,datevalue("1/1/" & tmpmfgyear))) & "/" & tmpmfgyear


'**************************************************************
'Next get the edid version
'**************************************************************
'the version is at EDID offset &H12
Dim tmpEDIDMajorVer, tmpEDIDRev, tmpVer
tmpEDIDMajorVer=asc(mid(strarrRawEDID(tmpctr),&H12+1,1))


'the revision level is at EDID offset &H13
tmpEDIDRev=asc(mid(strarrRawEDID(tmpctr),&H13+1,1))


'store it in month/year format
tmpver=chr(48+tmpEDIDMajorVer) & "." & chr(48+tmpEDIDRev)


'**************************************************************
'Next get the mfg id
'**************************************************************
'the mfg id is 2 bytes starting at EDID offset &H08
'the id is three characters long. using 5 bits to represent
'each character. the bits are used so that 1=A 2=B etc..
'
'get the data
Dim tmpEDIDMfg, tmpMfg
dim Char1, Char2, Char3
Dim Byte1, Byte2
tmpEDIDMfg=mid(strarrRawEDID(tmpctr),&H08+1,2)
Char1=0 : Char2=0 : Char3=0
Byte1=asc(left(tmpEDIDMfg,1)) 'get the first half of the string
Byte2=asc(right(tmpEDIDMfg,1)) 'get the first half of the string
'now shift the bits
'shift the 64 bit to the 16 bit
If (Byte1 and 64) > 0 then Char1=Char1+16
'shift the 32 bit to the 8 bit
If (Byte1 and 32) > 0 then Char1=Char1+8
'etc....
If (Byte1 and 16) > 0 then Char1=Char1+4
If (Byte1 and 8) > 0 then Char1=Char1+2
If (Byte1 and 4) > 0 then Char1=Char1+1


'the 2nd character uses the 2 bit and the 1 bit of the 1st byte
If (Byte1 and 2) > 0 then Char2=Char2+16
If (Byte1 and 1) > 0 then Char2=Char2+8
'and the 128,64 and 32 bits of the 2nd byte
If (Byte2 and 128) > 0 then Char2=Char2+4
If (Byte2 and 64) > 0 then Char2=Char2+2
If (Byte2 and 32) > 0 then Char2=Char2+1


'the bits for the 3rd character don't need shifting
'we can use them as they are
Char3=Char3+(Byte2 and 16)
Char3=Char3+(Byte2 and 8)
Char3=Char3+(Byte2 and 4)
Char3=Char3+(Byte2 and 2)
Char3=Char3+(Byte2 and 1)
tmpmfg=chr(Char1+64) & chr(Char2+64) & chr(Char3+64)


'**************************************************************
'Next get the device id
'**************************************************************
'the device id is 2bytes starting at EDID offset &H0a
'the bytes are in reverse order.
'this code is not text. it is just a 2 byte code assigned
'by the manufacturer. they should be unique to a model
Dim tmpEDIDDev1, tmpEDIDDev2, tmpDev


tmpEDIDDev1=hex(asc(mid(strarrRawEDID(tmpctr),&H0a+1,1)))
tmpEDIDDev2=hex(asc(mid(strarrRawEDID(tmpctr),&H0b+1,1)))
If len(tmpEDIDDev1)=1 then tmpEDIDDev1="0" & tmpEDIDDev1
If len(tmpEDIDDev2)=1 then tmpEDIDDev2="0" & tmpEDIDDev2
tmpdev=tmpEDIDDev2 & tmpEDIDDev1


'**************************************************************
'finally store all the values into the array
'**************************************************************
'Kaplan adds code to avoid duplication...


If Not InArray(tmpser,arrMonitorInfo,3) Then
arrMonitorInfo(tmpctr,0)=tmpmfg
arrMonitorInfo(tmpctr,1)=tmpdev
arrMonitorInfo(tmpctr,2)=tmpmdt
arrMonitorInfo(tmpctr,3)=tmpser
arrMonitorInfo(tmpctr,4)=tmpmdl
arrMonitorInfo(tmpctr,5)=tmpVer
End If
End If
Next


'For now just a simple screen print will suffice for output.
'But you could take this output and write it to a database or a file
'and in that way use it for asset management.
i = 0
for tmpctr = 0 to intMonitorCount-1
If arrMonitorInfo(tmpctr,1) <> "" And arrMonitorInfo(tmpctr,0) <> "PNP" Then
If batch Then
EchoAndLog strComputer & "," & arrMonitorInfo(tmpctr,4) & "," & _
arrMonitorInfo(tmpctr,3)& "," & arrMonitorInfo(tmpctr,0) & "," & _
arrMonitorInfo(tmpctr,2)
Else
message = message & "Monitor " & chr(i+65) & ")" & VbCrLf & _
"Model Name: " & arrMonitorInfo(tmpctr,4) & VbCrLf & _
"Serial Number: " & arrMonitorInfo(tmpctr,3)& VbCrLf & _
"VESA Manufacturer ID: " & arrMonitorInfo(tmpctr,0) & VbCrLf & _
"Manufacture Date: " & arrMonitorInfo(tmpctr,2) & VbCrLf & VbCrLf
'wscript.echo ".........." & "Device ID: " & arrMonitorInfo(tmpctr,1)
'wscript.echo ".........." & "EDID Version: " & arrMonitorInfo(tmpctr,5)
i = i + 1
End If
End If
Next


If not batch Then
MsgBox message, vbInformation + vbOKOnly,strComputer & " Monitor Info"
End If


Function InArray(strValue,List,Col)
Dim i
For i = 0 to UBound(List)
If List(i,col) = cstr(strValue) Then
InArray = True
Exit Function
End If
Next
InArray = False
End Function


Sub EchoAndLog (message)
'Echo output and write to log
Wscript.Echo message
AppendOut.WriteLine message
End Sub

Saturday, April 27, 2013

dhclient and /etc/resolv.conf being overwritten.

In ubuntu 12.12 (the one I'm currently using), dhclient is used to get a dhcp lease.  For most people this works just dandy.  However if you use it for routing, and/or running your own dns server inside your network, or just want to have some dns servers used for whatever reason that the dhcp server doesn't issue you can do the following.  

If you go into the /etc/dhcp directory you will see a file called dhclient.conf
somewhere (anywhere really), in the file put the following line:
prepend domain-name-servers 8.8.8.8;

if you want just your custom dns server:
supersede domain-name-servers 8.8.8.8;


This will put the 8.8.8.8 dns server at the top of the list of dns servers in the /etc/resolv.conf file, in addition the to usual ones that the dhcp server gave to your computer. 

Of course for your network you will probably replace 8.8.8.8 with the ip address of another dns server (unless you really want to use one of google's dns servers).  


In fedora you have to go to /etc/sysconfig/network-scripts/, and find the file for your network device (something like ifcfg-ethX, where X is a number usually 0).

change the line PEERDNS=yes to =no.


Friday, April 26, 2013

installing ssh fedora

Fedora nowadays doesn't have the ssh server by default, if you want it here's how (fedora no longer uses /etc/init.d):

yum install openssh
service sshd start
service sshd enable

note: if you want to start/enable other services on fedora you can replace sshd with the name of the other service.

Wednesday, April 24, 2013

proxmox tips

To force a vm to shutdown you can't do it from the web interface so instead you'll have to ssh in and use your root username and password.  Once you're ssh'd in type:
qm shutdown <vmid> -forceStop
more details at: http://pve.proxmox.com/wiki/Manual:_qm




Proxmox is a nice setup overall, but the java vnc interface to view the desktop of the vm is just lousy.  A way around that is to ssh in and go to the /etc/pve/nodes/proxmox/qemu-server directory.  In the 1##.conf file (where 1## is the id of the VM), put the following lines:
args: -vnc 0.0.0.0:10
You can do this with each vm, just make sure the change the number after the last colon, as
each vnc connection has to be on it's own port.  Then you can vnc using your favorite vnc viewer, and use the ip address/hostname of the proxmox server followed by a : and the number that's at the end of the line you put in the VM's config file.  In this case it would be "vncviewer proxmox-machine:10"

More details on your vnc options and proxmox are at: http://pve.proxmox.com/wiki/Vnc_2.0


For tips on how to deal with the screen resolution of linux in a VM (both X and console):
http://thescriptingadmin.blogspot.com/2013/04/fedora-too-high-resolution-in-vm.html


Friday, April 5, 2013

ssh-agent in cygwin

If you do command line work like I do, and remote into a linux machine via ssh, you may or may not be aware of ssh keys.  If you use an ssh key you can log into the machine without a password.  However to keep things secure, you really should use a password on your ssh key, but if you had to type in the password every time you used the key, that would sort of defeat the purpose of the ssh key.  So they have ssh-agent for linux and cygwin (if you're using putty use pagent instead).

Normally you first run ssh-agent, then run ssh-add (or just have it loaded via kde, gnome, or .bash_profile if you don't use a gui at all on linux).  On cygwin though you might encounter the error message "Could not open a connection to your authentication agent" when you type in ssh-add.  The solution is apparently to run the following command: "exec ssh-agent bash", and once you get a new bash shell then type ssh-add.


enable remote registry service on windows 7

Windows 7 by default disables the remote registry service (probably for security reasons).  To enable it from  the command line type the following:

sc \\computername config remoteregistry start= auto
make sure you have a space between the = sign and auto
if you're doing this on your local computer you can drop the \\computername part
you can also replace "remoteregistry" with the name of another service to enable or disable it.


once you've enabled the service you can either reboot the computer, or just start it now with:

sc \\computername start remoteregistry


If you want to know why we want to enable this service, it's so that you can pull up the registry of a remote computer that's currently in use (normally hkey_local_machine) via regedit on your local machine.  This way you don't have to interrupt whoever is currently at the computer by using RDP, VNC, or kicking the user out of their chair, at most you may have to tell them to reboot their machine at some point.

Thursday, March 21, 2013

printer statistics via SNMP

At work we have some multi-function copiers that do the whole print, scan, copy, deal.  What do you do if you want to track printer usage?.  You can either enable monitoring of print jobs on the print server, if your users go through a print server, or you can track the page counts on the printers themselves, if they are network printers.

In addition to tracking page counts, this script tracks how many sheets of paper are left in each of the trays (if your network printer is advanced enough to do that), and dumps all the information to a csv file.  Right now I'm running the script every hour or so to track what happens if I adjust some default settings.

For this you will need net-snmp, which you can get at: http://sourceforge.net/projects/net-snmp/files/net-snmp%20binaries/ if you're using windows, if you're using linux do apt-get install snmp or yum install net-snmp depending on your distro so that you get snmpwalk installed.

For linux you'll probably need to create a bash script of your own, based on the nagios script I used at:  http://exchange.nagios.org/directory/Plugins/Hardware/Printers/SNMP-Printer-Check/details

Without further ado here's my batch script (for windows):



@echo off
set snmpexe=c:\usr\bin\snmpwalk.exe
rem make sure to include the .exe at the end
rem netsnmp binaries are available from:
rem http://sourceforge.net/projects/net-snmp/files/net-snmp%20binaries/
rem shouldn't need to change anything between this and ":appendfile"
set prnip=%1
echo checking on the amount of paper left in the trays for printer %prnip%
for /f "tokens=2" %%W in ('date /t') do set dater=%%W
for /f "tokens=1,2 delims=:" %%t in ('echo %time%') do set timer=%%t:%%u
for /f "tokens=1-3 delims=/" %%d in ('echo %dater%') do set curdate=%%f%%d%%e
for /f "tokens=3 delims=/" %%y in ('echo %dater%') do set curyear=%%y
rem reset variables for when we run this multiple times (usually on different printers),
rem in the same enviroment (don't want previous valuse affecting this run).
set tray0=x
set tray1=x
set tray2=x
set tray3=x
set tray4=x
set pgcount=x
if "%1" == "" goto usage
if NOT exist %snmpexe% goto usage

if exist prn-%prnip%-%curyear%.csv goto appendfile
:newfile
echo this tells you how many sheets are still in each input tray/cassette in a printer
echo date ,time ,envelope ,tray1 ,tray2 ,tray3 ,tray4 ,pagecount >> prn-%prnip%-%curyear%.csv


:appendfile
rem this is for a printer with 4 regular trays and a "multi-purpose" tray, you
rem many need to change this a bit if your printer hardware is a little different
rem this is based on code from
rem http://exchange.nagios.org/directory/Plugins/Hardware/Printers/SNMP-Printer-Check/details
for /f "tokens=4" %%c in ('%snmpexe% -v1 -c public %prnip% 1.3.6.1.2.1.43.8.2.1.10.1.1') do set tray0=%%c
for /f "tokens=4" %%c in ('%snmpexe% -v1 -c public %prnip% 1.3.6.1.2.1.43.8.2.1.10.1.2') do set tray1=%%c
for /f "tokens=4" %%c in ('%snmpexe% -v1 -c public %prnip% 1.3.6.1.2.1.43.8.2.1.10.1.3') do set tray2=%%c
for /f "tokens=4" %%c in ('%snmpexe% -v1 -c public %prnip% 1.3.6.1.2.1.43.8.2.1.10.1.4') do set tray3=%%c
for /f "tokens=4" %%c in ('%snmpexe% -v1 -c public %prnip% 1.3.6.1.2.1.43.8.2.1.10.1.5') do set tray4=%%c
for /f "tokens=4" %%c in ('%snmpexe% -v1 -c public %prnip% 1.3.6.1.2.1.43.10.2.1.4.1.1') do set pgcount=%%c

echo %date% ,%timer% ,%tray0% ,%tray1% ,%tray2% ,%tray3% ,%tray4% ,%pgcount% >> prn-%prnip%-%curyear%.csv

goto end

:usage
echo usage: input-tray-count.bat ip-of-printer
echo this requires snmpwalk in the specified location
echo this will tell you how many sheets you have left in each input tray/cassette in a printer

:end

Monday, March 18, 2013

company CA without a cert server

For those who administer a network, sometimes you need to create a root certificate.  This can be for an internal web-server, or for deploying internal software, or for other reasons.  In many places you have a server setup who's sole purpose it get generate SSL and maybe other certificates for the company.  If you don't wan't to dedicate an entire server to this task though because you don't need to be constantly generating new certificates there is an alternative.

OpenSSL is an open source program (hence the Open part), that allows you to generate SSL certificates, everything from a root certificate (for your company root CA), to a regular certificate that's signed by the root CA.

If you're on a linux machine do your usual apt-get install openssl or yum install openssl, and skip the next paragraph for windows.

If you're on windows, you'll need to go to: http://www.openssl.org/related/binaries.html, and follow the links till you can download the openssl binary (full version) for window at  http://slproweb.com/products/Win32OpenSSL.html (you may need to download and install the visual C++ redistrutable).  You'll also want to add c:\openssl-win32\bin to your system's path or have the DLL's installed to the c:\windows\system32 directory.

To create a root certificate go to the c:\openssl-win32\bin directory and type:
openssl req -nodes -new -x509 -keyout my-ca.key -out my-ca.crt -days 3650 -config openssl.cfg
-leave the e-mail address blank.
-the above root ca will be valid for 13 years.

make the following directories, demoCA, demoCA\newcerts, and demoCA\private
under c:\openssl-win32\bin?
so you should have c:\openssl-win32\bin\demoCA\newcerts as one of your paths



move the *-ca.crt file to demoCA
the *-ca.key file to demoCA\private
in the openssl.cnf file go to the CA_default section and make sure that private_key = $dir/private/my-ca.key
and change certificate = $dir/my-ca.crt
(change my-ca.key to whatever you typed in the openssl command above)


type echo 01 > \demoCA\serial
and in explorer navigate to the demoCA folder and create a new text file
and name it index.txt (don't put anything in it).



to create server certificates for wsus:
openssl req -nodes -new -keyout servername.key -out servername.csr -days 1825 -config openssl.cfg
for Common Name enter servername.company.com
leave email address blank, and hit enter for challenge password and optional company name.

then sign it using the ca (certifies for 5 yesrs)
openssl ca -out server.crt -in server.csr -days 1825 -config openssl.cfg

then export it to pfx format for iis:
openssl pkcs12 -export -out server.pfx -inkey server.key -in server.crt -certfile my-ca.crt
type in a password for the pfx
ignore message about "unable to write 'random state'




Thursday, March 7, 2013

rrd illegal time fix, and editing xml with sed


And now for some BASHing...

If you use rrd, and do a reboot of your computer, on rare occasion you might run into an error like the following (I put xxx in some places for privacy).  

ERROR: Cannot update /var/www/mrtg/xxx/10.x.x.5_xx.rrd with '1359389221:4100149299:563322753' /var/www/mrtg/xxx/10.x.x.5_xx.rrd: illegal attempt to update using time 1359389221 when last update time is 1359402962 (minimum one second step)

That long 10 digit number starting with 1359... is a unix time stamp, which is just the number of seconds that have elapsed since january 1st 1970.  If you can't figure out the cause of this error, you can edit the rrd files.  Unfortunately they are in a binary format and need to first be exported to xml, edited, and then converted back to binary format.  While there is a python script for editing xml files exported from rrd databases, it required a library which I was unable to properly install on my linux machine.  So I decided to create a bash script using sed, and not bother with python (or it's libraries)


Remember this is a BASH script, not a BATCH script.  So if you're going to run this on a windows machine you'll need to install cygwin first, and run it from inside of cygwin.  



#!/bin/bash
# you will probably want to run this as
# find . -iname "*.rrd" -print0 |xargs -0 -I {} rrd-fixer.sh {}

#first we convert the rrd file to xml format
rrdtool dump $1 > $1.xml
#we need to figure out the current unix date (epoc format, number of seconds
#since 1970)
udate=`date +%s`
#the heart and soul, take out the bad last update stamp, and replace it with
# one mrtg (or other rrd based tools), won't barf on
sed -e "s/<lastupdate>1[0-9]\{9\}/<lastupdate>$udate/" $1.xml > $1.fixed.xml
#rrdtool won't overwrite the bad rrd file on it's own, so have to remove
#it ourselves
rm $1
#convert the .xml file back to .rrd format
rrdtool restore $1.fixed.xml $1
#cleanup the xml files
rm $1.xml
rm $1.fixed.xml

# ---------- end of bash script --------------------------

note: if you want to run this on a folder with many rrd files (like mrtg or smokeping will often create), you will probably want to run the script in the following manner:
find . -name "*.rrd" -print0 |xargs -0 -I {} rrd-fixer.sh {}
or if you want to simplify it:
ls -1 *.rrd |xargs rrd-fixer.sh



fyi, the python script I came across is at: http://pierre.palatin.fr/old/rrd-repair

Thursday, February 28, 2013

net send for windows vista/7/8

Remember back in the day of NT/2000/XP, where you could type
net send computername some message here?

If you tried to do a net send with any version of windows since xp (vista/7/8), you've probably noticed that Microsoft removed net send entirely (with xp sp2, they disabled the service, but you could easily re-enable it).

Microsoft probably did this for security/anti-spam.  Back in the days when I was in college, I would often be getting net send spam.

You can use msg.exe which will send a message to a terminal server (has to be a server vision of windows), or to display a popup on your local computer.  If we combine that with psexec we have a way to replicate the functionality,

psexec \\remotecomputer msg.exe * /server:remotecomputer some message here

However this doesn't work very well if you have many computers (say a whole office?) that you need to send a message to.
So here's a script to make it easier if you have multiple computers:

rem --------beginning of netsend7.bat-------------------------


@echo off

rem this is for sending messages to computers using psexec and msg.exe

rem instead of net send. as net send doesn't exist in windows after xp

rem NEEDS PSEXEC.EXE in the the path or same folder.




if "%~1" == "" goto error




rem need to convert the list of computers

rem from comma to space delimited

for /f "tokens=*" %%c in ('echo %~1') do set comps=%%c

echo the computers are %comps%




rem extract the message from the command line

for /f "tokens=1,* delims= " %%p in ('echo %*') do set msg=%%q

echo the message is: %msg%




rem call the subroutine for each message.

for %%c in (%comps%) do call :submsg %%c







goto end




:submsg

set subcomp=%1

rem echo messaging %subcomp%, with message %msg%

psexec \\%subcomp% msg.exe * /server:%subcomp% %msg%

exit /b




:error

echo make sure to include quotes at the beginning and

echo end of the list of computers, but not the message,

echo usage "comp1,comp2,comp3,etc..." some message to the computers




rem check for psexec

where /q "$path:psexec.exe"

if %errorlevel% == 0 goto end

echo .

if not exist psexec.exe echo you need to have psexec.exe somewhere in the path.




:end


rem --------end of netsend7.bat-------------------------



If you want to accomplish the same thing without psexec, there is a guy who figured out a method using vbscript and setting a remoteRPC key in the registry on every computer you're messaging to:


Wednesday, February 27, 2013

synchronizing cross platform

If you've been in the computer field at all for the past few years, you've heard of the cloud, amazon s3, ec2, dropbox, windows live, carbonite, google docs, etc....

What if you don't want to store everything in the cloud, either it's too private, or don't want to run afoul of some data privacy laws (hippa?), or it would just cost too much to store all of the hours of baby videos you took.

Now you could use robocopy, or rsync, but these are both one direction.  If you have a laptop that you edit information on along with a desktop (or another laptop?), you probably want to sync your information between the two not just do a one direction backup.

Unison is the program I've been using to keep various repositories of information in sync.   It's cross platform, bi-directional, and doesn't involve the cloud, you control where everything is.

my usage is:
unison -batch profile.prf

the -batch option automates the synchronization process, without it, unison will ask about each and every file that it's copying, should it copy, delete, overwrite one, etc..., so you should probably run it just the first time without the -batch option (if at all).

profile.prf is the name of the configuration file (in the .unison folder if you don't specify a path to it), it can be any name though (pro.prf, home-sync.prf, etc...).

it'll also run over ssh like rsync does, or run a server also like rsync.

a unique feature of unison which I enable is for it to store previous versions of files into a separate folder (or you can store them in a hidden folder in the listing of folders being synchronized).

one of my .prf files, this is for windows, but unison on linux works just as well, just change the folders.

#######------start of prf file--------------

root = //server1/share/synced-folder1
root = //server2/share/synced-folder2

path = subfolder1
path = subfolder2
path = subfolder3

#as this is for windows, don't use fastcheck for unix usually
fastcheck = true
backup = Name *
#ignore any hidden folders, and cd images
ignore = Name {,.}*{.iso}
#where unison stores it's previous versions
backupdir = c:\Users\user1\unison-bak
#where to store the logs
logfile = c:\Users\user1\unison-logs\info-db
#the maximum number of previous versions
maxbackups = 10
#######------end of prf file--------------

Tuesday, February 26, 2013

sysinternals tools hanging due to license

You probably have come across (either in this blog or on other sites), various tools from sysinternals (psexec, psinfo, pskill, etc...).

While these are great tools, for the sysadmin, especially when it comes to automating and scripting, you may have noticed that they been absorbed my microsoft.  On it's own, being acquired by microsoft isn't necessarily a bad thing, however microsoft does now insist that you agree to a license the first time you use a sysinternals tool as a particular user on a particular machine.  This can be very problematic when running scripts on remote machines via psexec (the sysinternals tool will hang and not give you any indication that it's because you need to agree to a license).

One way to get around this is to put in registry keys onto the remote computer that you already accepted the eula,
reg.exe ADD HKCU\Software\Sysinternals\PsKill /v EulaAccepted /t REG_DWORD /d 1 /f
reg.exe ADD HKCU\Software\Sysinternals\PsList /v EulaAccepted /t REG_DWORD /d 1 /f
reg.exe ADD HKCU\Software\Sysinternals\PsInfo /v EulaAccepted /t REG_DWORD /d 1 /f
reg.exe ADD HKCU\Software\Sysinternals\PSexec /v EulaAccepted /t REG_DWORD /d 1 /f
reg.exe ADD "HKCU\Software\Sysinternals\Process Explorer" /v EulaAccepted /t REG_DWORD /d 1 /f
reg.exe ADD "HKCU\Software\Sysinternals\Process Monitor" /v EulaAccepted /t REG_DWORD /d 1 /f
reg.exe ADD "HKCU\Software\Sysinternals\Autoruns" /v EulaAccepted /t REG_DWORD /d 1 /f
reg.exe ADD "HKCU\Software\Sysinternals\TCPView" /v EulaAccepted /t REG_DWORD /d 1 /f
reg.exe ADD "HKCU\Software\Sysinternals\RootkitRevealer" /v EulaAccepted /t REG_DWORD /d 1 /f

many thinks to http://peter.hahndorf.eu/blog/post/2010/03/07/WorkAroundSysinternalsLicensePopups  for the information, please go there for a more complete listing of registry entries for each of the sysinternals tools.  

Monday, February 25, 2013

Monitoring free space

Previously I described one unusual method to help clear out space on windows, details are here, If you want to make sure your windows server (or workstation), doesn't get too low on free space you can use some of the many monitoring tools out there which eat up system resources when you use them and/or cost an arm and a leg.  My solution is to have a script which goes out and checks the drives, and saves the information to a csv file so you can check for trends using any spreadsheet program.  It will also send out an e-mail if the space is too low.  I run this script from the windows task scheduler at 7am and 7pm, against all the different servers.

Usage:  drv-space.bat  servername

note: e-mail functionality requires blat.exe which you can get at http://www.blat.net/, and you will have to set some variables in the script also.


rem -----begin script --------

@echo off
set tech=network.admin
set techdom=company.com
set mailserver=mail.company.com
set machinednsdomain=company.com
set blatexe=c:\utils\blat.exe
set freespacenum=1000000000
rem shouldn't need to change any variable below here
rem usage drv-space.bat servername
set server=%1
echo processing server %server% at %date% %time%
for /f "tokens=2" %%W in ('date /t') do set dater=%%W
for /f "tokens=1,2 delims=:" %%t in ('echo %time%') do set timer=%%t:%%u
for /f "tokens=1-3 delims=/" %%d in ('echo %dater%') do set curdate=%%f%%d%%e
for /f "tokens=3 delims=/" %%y in ('echo %dater%') do set curyear=%%y
echo checking drive space
for /f "tokens=3" %%s in ('dir \\%server%\c$ ^|find "free"') do set drvct=%%s
for /f "tokens=3" %%s in ('dir \\%server%\d$ ^|find "free"') do set drvdt=%%s
for /f "tokens=3" %%s in ('dir \\%server%\e$ ^|find "free"') do set drvet=%%s
rem strip out the commas from the values
set drvc=%drvct:,=%
set drvd=%drvdt:,=%
set drve=%drvet:,=%
echo checking if we have at least a gig on drive c. 
if %drvc% LSS %freespacenum% goto emailwarning
goto savetocsv
:emailwarning
echo on 
echo we got less then 1 gig
rem if we have less then one gig we need to send an e-mail, but only if we haven't already done so today.  
if exist %temp%\%server%-%curdate%-low-space-msg.txt goto savetocsv
echo apparently need to email about %server% at %time%, only %drvc% bytes free
echo drive c on %server% has only %drvct% bytes of free space on it as of %date% %time% > %temp%\%server%-%curdate%-low-space-msg.txt
%blatexe% %temp%\%server%-%curdate%-low-space-msg.txt -to %tech%@%techdom% -server %mailserver% -f %COMPUTERNAME%_drv-space-check@%machinednsdomain% -s "%server% low on free space"
:savetocsv
if not exist %server%-free-space-%curyear%.csv echo date ,time ,drive c ,drive d ,drive e >> %server%-free-space-%curyear%.csv
echo saving to csv %time%
echo %date% ,%timer% ,%drvc% ,%drvd% ,%drve% >> %server%-free-space-%curyear%.csv

rem -----------------end of script----------------

Thursday, February 21, 2013

freeing space, move uninstall packs

Any modern version of windows has many, many, updates over the course of its lifetime (2000, xp, vista, 7, etc...).  While you probably knew this already, you may not know that every time you install the windows updates (which are vital to keeping your system secure, and hopefully more stable), there is a folder created which stores some files in case you need to uninstall them.  This folder is under the windows system directory (usually c:\windows), and looks like $NtUninstalllKB######$ where ###### is some 6 digit number (and it may become 7 digits some years from now).

On server 2003, if you keep it up to date these files now take up a little less then a gig worth of space.  For most desktops this isn't an issue especially in an office, unless the person is filling up their hard drive with huge multi-media files.  On our servers at work though, drive C (where we have windows), was for some strange reason set to only 12gigs, and as some of these servers are in remote locations (I support offices in 7 different cities across the state), I can't just re-size the partition, and as it's a 6 year old server still under a support contract, I can't just add a drive, so I have to move whatever I can off of the drive.  There's the usual items of course, uninstall programs you don't need, move unneeded files, clear out the temp directories, empty the recycle bin, etc...., but I needed to be more aggressive, as some things just had to be on drive C that took up a huge amount of space.

If you do some checking, various sites, and Microsoft say that you should be able to remove the $NtUninstalllKB######$ folders, but me being the overly cautious sort, didn't want to just delete them, so I decided I want to move them to a different drive, but also still have windows be able to use them via junctions.  A junction is like a hard link for a directory under linux.  You can have a folder on a drive and you can have multiple junctions that also point to that folder, but as far as any programs are concerned they don't realize it's a junction they went through it just looks like another copy of the folder.

My script will move the $NtUninstalllKB######$ folders from c:\windows to a folder on another ntfs drive on the local machine and then create identical junctions for each of the folders on c:\windows that point to the new location.

Once you've cleared out a good amount of space on your drive, check out my script to alert you before you run out of space.  

You will need the sysinternals tool junction.exe
http://technet.microsoft.com/en-us/sysinternals/bb896768.aspx
about junctions: http://en.wikipedia.org/wiki/NTFS_junction_point

about the $NTUninstallKB##### folders
http://support.microsoft.com/kb/956324/en-us
http://seanconnolly.com/archive/2009/07/31/can-i-delete-ntuninstall-folders-in-the-windows-directory.aspx



rem ----------------------script starts here-------------

@echo off

rem this is meant to make room on drive c for older servers
rem that have drive c be too small, but other drives where
rem drive c files can be moved to.

set junexe=d:\mis\single-progs\junction.exe
if not exist %junexe% goto error
rem no trailing backslash
set dstloc=e:\windows
if not exist %dstlock% goto error

echo processing %computername% at %date% %time%

rem extract current month, year, date, etc...
for /f "tokens=2" %%W in ('date /t') do set dater=%%W
rem for /f "tokens=1,2 delims=:" %%t in ('echo %time%') do set timer=%%t:%%u
for /f "tokens=1-3 delims=/" %%d in ('echo %dater%') do set curdate=%%f%%d%%e
for /f "tokens=3 delims=/" %%y in ('echo %dater%') do set curyear=%%y
for /f "tokens=1-3 delims=/" %%d in ('echo %dater%') do set curmonth=%%d
for /f "tokens=1-3 delims=/" %%d in ('echo %dater%') do set DOMC=%%e
rem only if the current month is february or later do we compute the last month
rem and set the lastmonth variable to year.
if %curmonth% GTR 1 set /a lastmonth=%curmonth% - 1
if "%curmonth%" == 01 set lastmonth=year
rem if the lastmonth is before november, add a zero in front of it
if %lastmonth% LSS 10 set lastmonth=0%lastmonth%



:uninstallpacks

rem uninstall packs, take up almost 1gb on the server when uncompressed (compression can only do so much).

if exist %temp%\ntupdateuninstalls.lst del %temp%\ntupdateuninstalls.lst
for /f "tokens=5" %%d in ('dir /a:d c:\windows\?NtUninstallKB* ^|find /v "JUNCTION" ^|find /v "%curyear%"') do echo %%d >> %temp%\ntupdateuninstalls.lst
if "%lastmonth%" == "year" goto copyandlink
rem if we're in january just do last years stuff.
rem if we're in a latter month and it's less then 10 days into the current month, we don't want to move
rem last month's items, otherwise we'll move everything except for this months.

if %curdate% LSS 10 for /f "tokens=5" %%d in ('dir /a:d c:\windows\?NtUninstallKB* ^|find /v "JUNCTION" ^|find /i "%curyear%" ^|find /v "%curmonth%" ^|find /v "%lastmonth%"') do echo %%d >> %temp%\ntupdateuninstalls.lst

if %curdate% GEQ 10 for /f "tokens=5" %%d in ('dir /a:d c:\windows\?NtUninstallKB* ^|find /v "JUNCTION" ^|find /i "%curyear%" ^|find /v "%curmonth%"') do echo %%d >> %temp%\ntupdateuninstalls.lst

:copyandlink

for /f %%l in ('type %temp%\ntupdateuninstalls.lst') do robocopy c:\windows\%%l %dstloc%\%%l /e /z /move

for /f %%l in ('type %temp%\ntupdateuninstalls.lst') do %junexe% c:\windows\%%l %dstloc%\%%l

rem for /f %%l in ('type %temp%\ntupdateuninstalls.lst') do compact /c %dstloc%\%%1

del %temp%\ntupdateuninstalls.lst
echo finished at %time%
pause
goto end

:error
echo you need to have junction.exe from sysinternals, and set
echo the junexe variable to point to the file, currently it's %junexe%
if exist %dstloc% goto end
echo make sure that you create a destination folder (perferably on a different drive
echo on a separate drive from your windows install) and set the dstloc variable
echo to reflect that location, currently it's %dstloc%
echo make sure to not end with a backslash
set /p mkdstloc=should I try to create %dstloc% (y/n):
if /i "%mkdstloc%" == "y" mkdir %dstloc%

:end

rem ----------------------script ends here-------------

Tuesday, February 19, 2013

remote desktop for non admins

Windows by default will allow all administrators (domain admins, local admins, etc...), but no one else.  To allow non admins you need to add them to the "Remote Desktop Users" group.  You can do this easily enough via control panel (if you can remote in as an admin on the machine), but if you have a hundred machines, the following becomes more friendly (and much quicker, if you use the up arrow to retrieve the last command in your command line history).  You will need psexec.

psexec -h \\remote-pc -u domain\administrator net localgroup "remote desktop users" domain\user1 /add

enable remote desktop

Windows remote desktop, so useful, especially in an office environment, where you just have to do some things with a mouse, but it's not enabled by default (probably a good thing for security reasons).
But what if you want to get into a remote windows machine, and it's over an hour away, talk the person through control panel?, or just go in yourself (especially when you have about a dozen computers to do this with)?.

The following changes a value in the registry which will then enable remote desktop, you could use regedit, and it's connect to network registry feature (though with windows 7 you have to enable the remote registry service for that to work), but I prefer the following:

reg add "HKLM\SYSTEM\CurrentControlSet\Control\Terminal Server" /v fDenyTSConnections /t reg_dword /d 0 /f

some say that you have to reboot the machine after you do this, I personally didn't (maybe I was lucky?)

you can run the above command via psexec (the -h is required for windows vista/7 machines),
ie: psexec -h \\remote-pc -u domain\administrator reg add "HKLM ....

thanks to orielly and the backroomtech.com for the registry edit, if you want the gui version check these sites:
http://oreilly.com/windows/archive/server-hacks-remote-desktop.html
http://thebackroomtech.com/2007/05/18/how-to-enable-remote-desktop-on-a-windows-xp-machine-remotely/

Intro

Welcome to my blog, the scripting admin.  Why the scripting admin?, most windows network administrators are use to point and click, and using the mouse.  However there are plenty of scripts for windows, and command line interfaces so that you don't have to use a mouse, and that is what I prefer especially with my linux background, so much so, I've gained the reputation at work, and am sometimes asked to create custom scripts.  This is a journal of my scripting/command line usage, and while it's mostly windows, I will be throwing in some linux also.


ps.  While there is http://scriptingadmin.blogspot.com he is a different person.