Posts Tagged ‘server 2003’

DNS Records Disappearing

Friday, February 26th, 2010

This post is a little confusing, but it may help someone out there.  In a recent security audit, we were told to disable several services on our servers, one of which was DHCP.  Before disabling it on each server, I verified they were manually configured.  We have some that are set by DHCP with a static.  I then proceeded to disable DHCP on all of the servers with manually configured NICs.

After a couple hours, we had 1 server that could no longer be reached.  of course it was a fairly critical web server.  After investigating, we could reach it in our Indianapolis location, but not Albuquerque.  The server was physically in ABQ.  I started thinking it was a network issue.  Also, the external users that access it from outside our firewall could still reach it.

After looking through the network and trying to see what changed, we realized the server no longer had any records in DNS in ABQ.  How does one record get removed from DNS like that, I thought?  After getting DNS back to how it should be, we started investigating what caused the DNS change.

Finally, we realized the server was using dynamically updated DNS, instead of a manually entered static record…  Never ever did it cross any of our minds that DHCP was keeping the DNS record updated, but it was.  The DHCP service on Windows machines automatically registers with DNS regularly.  This I knew, but I didn’t know that DHCP will register with DNS even if none of the interfaces on the machine are obtaining an address from DHCP.  Interesting.

So, before you disable that service, make sure your DNS records are manual entries and didn’t just come from DHCP’s dynamic updates.

Find Tables Missing Indexes and Create Clustered Indexes for Them

Wednesday, February 24th, 2010

**Update at bottom**

OK, so we had a SQL 2005 database that we migrated from another company.  The application that uses it as a backend was having some terrible performance issues.  We had limited information on the previous configuration, so we bumped the Application up to a newer server since it seemed most of the load issues were with that part.  Afterwards, there were still performance issues and timeouts.  SQL was queuing up commands and taking too long to process them.  So we got the senior DBA involved to help us see what kind of performance increases we could get on the SQL server.  Unfortunately, I did not note all of the changes, but this was the biggest improvement.

We found out that the previous company also had performance issues.  When looking at the tables, we noticed many did not have indexes.  This little query was a lifesaver.  It shows you which tables are without an index, how many reads/writes and if things are queuing.

SELECT

migs.avg_total_user_cost * (migs.avg_user_impact / 100.0) * (migs.user_seeks + migs.user_scans) AS improvement_measure,

‘CREATE INDEX [missing_index_' + CONVERT (varchar, mig.index_group_handle) + '_' + CONVERT (varchar, mid.index_handle)

+ '_' + LEFT (PARSENAME(mid.statement, 1), 32) + ']‘

+ ‘ ON ‘ + mid.statement

+ ‘ (’ + ISNULL (mid.equality_columns,”)

+ CASE WHEN mid.equality_columns IS NOT NULL AND mid.inequality_columns IS NOT NULL THEN ‘,’ ELSE ” END

+ ISNULL (mid.inequality_columns, ”)

+ ‘)’

+ ISNULL (’ INCLUDE (’ + mid.included_columns + ‘)’, ”) AS create_index_statement,

migs.*, mid.database_id, mid.[object_id]

FROM sys.dm_db_missing_index_groups mig

INNER JOIN sys.dm_db_missing_index_group_stats migs ON migs.group_handle = mig.index_group_handle

INNER JOIN sys.dm_db_missing_index_details mid ON mig.index_handle = mid.index_handle

WHERE migs.avg_total_user_cost * (migs.avg_user_impact / 100.0) * (migs.user_seeks + migs.user_scans) > 10

ORDER BY migs.avg_total_user_cost * migs.avg_user_impact * (migs.user_seeks + migs.user_scans) DESC

The second column is a query string generated by the first query that will create indexes based on what is needed.  A note though, that query only creates standard indexes.  I recommend to change it to create clustered indexes.  They are considerably faster.  Here are the commands I used to create our indexes.

CREATE CLUSTERED INDEX cix_MASTER1_HISTORY on MASTER1_HISTORY(mrID)

CREATE CLUSTERED INDEX cix_MASTER1_DESCRIPTIONS on MASTER1_DESCRIPTIONS(mrID)

CREATE CLUSTERED INDEX cix_MASTER1_TIMETRACKING on MASTER1_TIMETRACKING(mrID)

CREATE CLUSTERED INDEX cix_MASTER2_HISTORY on MASTER2_HISTORY(mrID)

Hopefully this helps some of you out there

**Updated 3/1/2010

This query to find indexes is dynamic.  it doesn’t actually find all tables missing indexes, it finds tables that are CURRENTLY being searched without indexes and ranks them based on the performance problems they are causing.  So run this query when your SQL starts getting backed up.

How To Seize FSMO Roles and Clean Up Failed Domain Controllers In Active Directory

Friday, December 18th, 2009

Alright, so I think at some point, every SysAdmin will have a domain controller fail.  Every SysAdmin should also know that unless you run dcpromo.exe to demote a domain controller before removing it from AD, you can have some issues.  From FSMO to DFRS, it’s just not a good situation.  Here is a summary guide on how to clean up AD after one of your Domain Controllers fail.  Also, this looks long, but it’s all very simple, just putting it into step-by-step sort of drags it out, so no worries, this should be about a 30 minute process.

USE CAUTION: Improperly using ntdsutil may result in partial or complete loss of Active Directory functionality… Don’t go exploring without doing your research.

STEP 1:

Finding Current FSMO Role Masters

First, We need to know whether that particular server was holding any of the FSMO roles.  To check this, we have a couple options, Either via the GUI(1), or via ntdsutil(2).  Personally, I prefer to do it via ntdsutil, as I always feel that there is more power in the command line.  Also, I just hate using a mouse. There are other options, but these two are all that I will cover in this post. For more you can look into “netdom” or “replmon” tools from microsoft, these are not included in windows by default, so I will overlook them for now.  (NOTE: For this, I definitely recommend ntdsutil, as in step 2, I will expect it to already be open and connected.  the GUI Method, is more for information.)

Method 1:

Open AD Users and Computers.

Right-click the name of the domain you are wanting to look at, then select Operations Masters.

FindFSMO1

From this view, you can determine the current Domain-Specific RID Master, PDC Emulator, and Infrastructure Master FSMO Roles.

Now, open AD Domains and Trusts,

Right-click the AD Domains and Trusts in the nav. pane and go to Operations Masters.  This will show you the Domain Naming Master Role.

Finally, to find the Schema Master, you will have an extra step.   You will need to register the Schmmgmt.dll library first.

Goto: Start>Run and type:

regsvr32 schmmgmt.dll

Hit Enter, you should see a success message.

Now, that should allow you to open a new console: AD Schema.  To open it, goto: Start>Run, type:

mmc

hit enter.  Now, in the management console, goto File>Add/Remove Snap-in> click Add.  Double Click Active Directory Schema and close the add/remove dialog windows.

Now, right-click the AD Schema icon and goto Operations Masters.

Method 2:

To check the FSMO Roles via the command line using ntdsutil, we will need to do the following.

Alright, let’s open up a command prompt, then type

ntdsutil

and hit enter.

at the ntdsutil prompt, you will type

roles

hit enter.

Now, you should see a screen that says “fsmo maintenance”.  type

connections

and hit enter again. Here you will connect to the server you want to become the FSMO master(localhost works, if thats what you want). So type:

connect to server <FQDN of server>

and hit enter again. now you will leave the server connections page and go back to fsmo maintenance. Type:

q

Now we should be back in fsmo maintenance, type

select operation target

Hit Enter. Then type:

list roles

Once you hit enter, it should show you the servers that hold each role.
FindFSMO2

Type “q” to get back to fsmo maintenance, but stay at this screen for the next step.

STEP 2:

Seizing FSMO Roles From Dead Server

OK, so this step is optional.  based on the results of your last step.  You only need to seize the roles if the FSMO master is no longer operational.  To do this step we will use ntdsutil.

Now, we need to seize the roles that are on our dead server.  You should know what roles your dead server holds from the last step, so only do this command for those.  Remember, I had you connect to the server that will receive the FSMO role(s).  A quick way to see the syntax for seizing is just type “?” and it will show you how to transfer/seize, it is basically:

seize <role>

as in:

seize schema master

or for transfers(only to be done if current master is still live/active)

transfer <role>

To verify the roles transferred(ignore the errors you get at first, you are guaranteed to have one since the current master is unavailable), put in

select operation target

then the same way we found the masters before:

list roles for connected server

Now, we’re almost done, we have transferred the FSMO roles(the biggest potential problem), and just need to cleanup the AD metadata and sites/services.

STEP 3:

Metadata Cleanup

For the next step, we will go back to the first ntdsutil prompt.  type “q” and hit enter until your prompt says “ntdsutil:”.  Type

metadata cleanup

hit enter. You should still be connected to a domain controller, but if you closed ntdsutil and reopened it, you will need to put in

connections

then

connect to server <servername>

then type quit back to the metadata cleanup prompt (”q”). Now, we will pick our target for cleanup. Type:

select operation target

At this point, if you only have 1 domain, or within the domain you pick, only 1 site, you can skip some steps. Your domain number, site number will be “0″(zero) if there is only one. For the sake of thoroughness, I will show you how to find the index anyway. To find the domain, type:

list domains

Now, find the domain you want to work with, and type:

select domain <number>

Now, we find the site within the domain where the domain controller used to reside.

list sites

put in the site you want:

select site <number>

To find the servers within that site, type:

list servers in site

then we will select the inactive server by typing:

select server <number>

Now, type enter “q” to quit back to metadata cleanup prompt. The final command to cleanup all metadata for that server is:

remove selected

You will receive a warning, but if you’re positive that server is down and will need rebuilt, you should be safe to hit Yes.  You should get a message saying it was removed successfully.  If you receive an error that the object could not be found, it was probably already removed from the domain controller.  Open up AD Users and Computers to verify the server is gone from the Domain Controllers OU.  Alright, we’re almost done, just another 5 minutes of work, at the most.

Step 4:

Remove The Server From Sites & Services

This will be done via the AD Sites & Services Snap-in.  Just expand the site where the server was located, and delete the object for the failed server… This step is done.

Step 5:

Remove The Server From DNS

This step depends a lot on how you have your DNS set up, I am assuming the DNS is run on a Windows server, and hopefully a DC.  It doesn’t have to be, that’s just how i prefer it.  Unfortunately, where I work, The DNS servers are separate and I have no access to them… such a pain.  Anyway, open up your DNS Management Console.  I hope you know this, but it’s:
Start>run> type “mmc”, hit enter. Goto File>Add/Remove Snap-in>hit Add>double-click DNS>Close>Close.
Now, expand the zone where the server used to be(probably Forward Lookup Zones>domain.local), and delete the A record(also called a host record) for the server. Remove the CNAME record in the _msdcs.root domain of forest zone in DNS. If you have reverse lookup zones, also remove the server from these zones. If you have anywhere else the server is referenced, or are unsure, you might want to check for these now.

You’re Done!  Now, you should be good to go.  Let me know if any of you have issues with this guide, notice anything wrong, or just have errors/questions.  I will be glad to help, and I know I have some pretty atrocious grammar/spelling at times.

Killing Processes on Server 2000 from VBScript

Thursday, October 8th, 2009

Alright, so we have a report server that has a massive SQL database and is running Server 2000 SP4. I honestly don’t know too much about it, because we have a DBA who does pretty much 90% of the maintenance/admin work on this server and the reports have nothing to do with the programs I work with. Anyway, the reports that are run export the SQL data to Excel spreadsheets. Once the report is run, the Excel process is left running. This server is already extremely old and bogged down as is, so having over a hundred instances of Excel running on it wasn’t helping. I wrote a script to check for all processes named “excel” and see how long they have been running, then kill the ones that were running for what seem to be too long of time. I had some issues, because Server 2000 does not have all of the capabilies as 2003, obviously. This script requires that you download pskill, part of the PSTools suite from SysInternals(now Microsoft). Now, while the script requires PSKill, it is able to run on server 2000/2003/2008(and 2000/xp/vista/7), so hopefully it is still useful to someone else out there. The script is below and I tried to make sure it was well-commented to help you out. Feel free to leave any suggestions/questions below. Enjoy.


''''This script requires pskill, part of the PSTools suite from SysInternals(now Microsoft). This script is assuming pskill is in your path for cmd line(generally, c:\windows(winnt on 2000/nt)\system32\)

Option Explicit
Dim strComputer, objWMIService, colProcessList, objProcess, PDate, Days, Hrs, Min, Sec, objSWbemLocator, WshShell
strComputer = "."
Set WshShell = CreateObject("wscript.shell")
Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colProcessList = objWMIService.ExecQuery("Select * from Win32_Process Where Name = 'Excel.exe'") ' Replace Excel with whatever the process is you're looking for.
Do
If colProcessList.Count = 0 Then ' This kills the script if the process we are looking for is not running.(also ties with last commented line for looping)
Exit Do
Else
For Each objProcess in colProcessList
If objProcess.CreationDate "" Then
PDate = Left(objProcess.CreationDate,14) ' pulls the date process started in format: yyyymmddhhmmss
Days = DateDiff("d",DateSerial(Left(PDate,4),Mid(PDate,5,2),Mid(PDate,7,2)),Date) ' find how many days process has been running
Hrs = Hour(Now) - Mid(PDate,9,2) ' find how many hours process was running, if started same day
Min = Minute(Now) - Mid(PDate,11,2) ' same but for minutes
Sec = Second(Now) - Mid(Pdate,13,2) ' same but for seconds
If Hrs > 6 Then ' This is where you specify how long the process has to have been running in order for it to be killed, so you don't kill active jobs. Change it from "Hrs" to "Min" or "Sec" for minutes or seconds. Change 6 to whatever number of units.(currently set to kill processes over 6 hours old)
WshShell.Run "pskill -t " & objProcess.ProcessId, 0, False
Else
If Days > 0 Then ' This is a failsafe to the previous "If". Since it only detects how many hours process was running, if started same day. This guarantees that it kills anything over a day old.
WshShell.Run "pskill -t " & objProcess.ProcessId, 0, False
End If
End If
End If
Next
WScript.Sleep 1000 ' wait before trying again
Set colProcessList = objWMIService.ExecQuery("Select * from Win32_Process Where Name = 'Excel.exe'") ' Recheck for processes ' This makes the script keep looking until there aren't any active processes. i.e. a report is being run now, we will wait until it is done to kill the process and the script.
End If
Loop

Login Script for Everyone

Monday, September 21st, 2009

UPDATED 12/23/09: The script on the bottom is the original.  I have made a few changes to log all errors and to fix a couple glitches that come up in some environments.  Changed the syntax of the addWindowsPrinterConnection command, and made it set default printer.  Here is the new script(the original post is below):


Option Explicit
Const ADS_PROPERTY_APPEND = 3 'sets the variable to Append
Const ADS_UF_NORMAL_ACCOUNT = 512
Const E_ADS_PROPERTY_NOT_FOUND = &h8000500D
CONST HKEY_LOCAL_MACHINE = &H80000002
Const ForReading = 1
Const ForWriting = 2
Const ForAppending = 8

Dim WshShell : Set WshShell = CreateObject(”wscript.shell”)
Dim strContainer, strUser, i, objRootDSE, strDisplayName, ObjFSO, objInFile, objContainer, strLine, strName, objOU, objGroup, objUser, objFile, objFile2, varDomainNC, objRoot, strText, FirstLine, arrMemberOf, Group, strFirstName, strLastName, strLine2, objOU2, objNetwork, strGroup, objConnection, objCommand, objRecordSet, objErrorLog, strComputer, colItems, objWMIService, colInstalledPrinters, strComputer2
Set objOU2 = GetObject(”LDAP://CN=users,DC=domain,DC=local”)
Set objOU = GetObject(”LDAP://ou=users,ou=indianapolis,DC=domain,DC=local”)
ObjOU.Filter= Array(”user”)
Set objGroup = objOU2.Getobject(”group”, “cn=CSRs”)
Set objFSO = CreateObject(”Scripting.FileSystemObject”)
Set objNetwork = WScript.CreateObject(”Wscript.Network”)
Set objRootDSE = GetObject(”LDAP://rootDSE”)
strComputer2 = “.”
Dim CRLF
CRLF = Chr(13) & Chr(10)

‘*************(Global Scripting) this section applies to all computers no matter what group users are in.

”default lockheed banner script
Function Ask(strAction)

Dim intButton
intButton = MsgBox(strAction, _
vbQuestion + vbYesNo, _
L_Welcome_MsgBox_Title_Text )
Ask = intButton = vbYes

End Function

MsgBox “This system is the property of this Corporation, and is intended for” & CRLF & _
“the use of authorized users only. All activities of individuals using this computer” & CRLF & _
“with or without authority, or in excess of their authority, may be monitored and recorded” & CRLF & _
“by system personnel. If any such monitoring reveals evidence of criminal activity or is in” & CRLF & _
“violation of foreign or U.S. state or federal law, such evidence may be provided to law” & CRLF & _
“enforcement officials and/or used for further legal action by this Corporation and/or the” & CRLF & _
“organization’s Information Protection group. Unauthorized use of this system is prohibited” & CRLF & _
“and may result in revocation of access, disciplinary action and/or legal action. The” & CRLF & _
“company reserves the right to monitor and review user activity, files and electronic messages.” & CRLF & _
“REMINDER: Information transmitted to a foreign person on this network may be subject ” & CRLF & _
“to applicable Export Control laws. Contact your Export Coordinator for assistance.” & CRLF & _
“(This machine is not authorized for classified processing)”, _
vbOKOnly, _
“SYSTEM USE MONITORING NOTICE – IPM-003 Banner Statement”

WshShell.Run “net use s: /delete”, 0, False
WshShell.Run “Net use s: \\server\shared /persistent:yes”, 0, False

‘*************End of global scripting

”pull local computer name for loggin info.
strComputer = objNetwork.ComputerName

”pull logon id
strUser = objNetwork.UserName

”turn logon id into container name for LDAP queries

Set objConnection = CreateObject(”ADODB.Connection”)
objConnection.Open “Provider=ADsDSOObject;”
Set objCommand = CreateObject(”ADODB.Command”)
objCommand.ActiveConnection = objConnection
objCommand.CommandText = “;(&(objectCategory=User)(samAccountName=” & strUser & “));name;subtree”
Set objRecordSet = objCommand.Execute
On Error Resume Next
strUser = objRecordSet.Fields(”name”)
On Error GoTo 0
objConnection.Close
Set objRecordSet = Nothing
Set objCommand = Nothing
Set objConnection = Nothing
strUser = Replace(strUser, “,”, “\,”)

‘’set user to have LDAP queries run
ON ERROR RESUME NEXT
Set objUser = GetObject(”LDAP://cn=” & strUser & “,ou=users,ou=indianapolis,dc=domain,dc=local”)
If Err.Number = 0 Then

”\/\/\/\/\/\/Determine Group memberships. PLEASE NOTE: group names must be in UPPER case and the “Left(strGroup, X)”
‘ X must be the number of characters in the group name.
‘\/\/\/\/\/\/\/

arrMemberOf = objUser.GetEx(”memberOf”)

If Err.Number <> E_ADS_PROPERTY_NOT_FOUND Then
For Each Group in arrMemberOf
strGroup = UCase(Group)
strGroup = Right(strGroup, Len(strGroup) – 3)
If Left(strGroup, 2) = “IT” Then
‘*****IT group scripting

‘’set Z:IT drive
WshShell.Run “net use z: /delete”, 0, False
WshShell.Run “Net use z: \\server\it /persistent:yes”, 0, False

”Prepare to set printers
Set objWMIService = GetObject(”winmgmts:\\” & strComputer & “\root\cimv2″)

”This prevents script from stopping when mapping network printers on the server where they
”are shared from
ON ERROR RESUME NEXT

”Add Printers

objNetwork.AddWindowsPrinterConnection “\\server\Xerox WorkCentre 5675 PS”
objNetwork.SetDefaultPrinter “\\server\Xerox WorkCentre 5675 PS”

‘*****End of IT
Else
If Left(strGroup, 4) = “CSRS” Then
‘*****CSR group scripting

‘*****End of CSR
Else
If Left(strGroup, 10) = “MANAGEMENT” Then
‘*****Management group scripting – NOTE: all managers are members of “Team Leads” group

‘*****End of Management
Else
If Left(strGroup, 7) = “Quality” Then
‘*****Quality scripting – NOTE: all quality are members of “TeamLeads” group

‘*****End of Quality
Else
If Left(strGroup, 10) = “TEAMLEADS” Then
‘*****Team Lead scripting

”Prepare to set printers
Set objWMIService = GetObject(”winmgmts:\\” & strComputer & “\root\cimv2″)

”This prevents script from stopping when mapping network printers on the server
”where they are shared from
ON ERROR RESUME NEXT

”Add Printers
objNetwork.AddWindowsPrinterConnection “\\server\Xerox WorkCentre 5675 PS”

‘*****End of Team Lead
End If
End If
End If
End If
End If
Next
Else
‘*****Create Error Log if groups could not be determined

Set objErrorLog = objFSO.OpenTextFile(”\\server\errors\signonerrors.txt”, ForAppending, True)
objErrorLog.WriteLine strUser & ” on ” & strComputer & ” could not be found in Active Directory on ” & Date
objErrorLog.WriteLine “The error code is ” & Err.Number
Err.Clear
End If
Else
‘*****Create Error Log for all other errors
Set objErrorLog = objFSO.OpenTextFile(”\\server\errors\signonerrors.txt”, ForAppending, True)
objErrorLog.WriteLine strUser & ” on ” & strComputer & ” had the following error: ” & Err.Number & ” on ” & Date
Err.Clear
End If

ORIGINAL POST: We have a new program in with a new domain. On our other networks, there are seperate logon scripts for pretty much every security group and they all call other scripts. With this network, i wanted to keep things simple, so this script connects to AD and checks their group membership before running the apropriate commands for each group. This particular network does not have any shares yet, and isn’t very complex, but here is the base of it. Let me know if you want to know how to add anything more to it.

Option Explicit
Const ADS_PROPERTY_APPEND = 3 'sets the variable to Append
Const ADS_UF_NORMAL_ACCOUNT = 512
Const E_ADS_PROPERTY_NOT_FOUND = &h8000500D
CONST HKEY_LOCAL_MACHINE = &H80000002
Const ForReading = 1
Const ForWriting = 2
Const ForAppending = 8

Dim WshShell : Set WshShell = CreateObject(”wscript.shell”)
Dim strContainer, strUser, i, objRootDSE, strDisplayName, ObjFSO, objInFile, objContainer, strLine, strName, objOU, objGroup, objUser, objFile, objFile2, varDomainNC, objRoot, strText, FirstLine, arrMemberOf, Group, strFirstName, strLastName, strLine2, objOU2, objNetwork, strGroup, objConnection, objCommand, objRecordSet, objErrorLog, strComputer, colItems, objWMIService, colInstalledPrinters, strComputer2
Set objOU2 = GetObject(”LDAP://CN=users,DC=arra,DC=local”)
Set objOU = GetObject(”LDAP://OU=arra-users,DC=arra,DC=local”)
ObjOU.Filter= Array(”user”)
Set objGroup = objOU2.Getobject(”group”, “cn=CSRs”)
Set objFSO = CreateObject(”Scripting.FileSystemObject”)
Set objNetwork = WScript.CreateObject(”Wscript.Network”)
Set objRootDSE = GetObject(”LDAP://rootDSE”)
strComputer2 = “.”
Dim CRLF
CRLF = Chr(13) & Chr(10)

‘*************(Global Scripting) this section applies to all computers no matter what group users are in.

”default lockheed banner script
Function Ask(strAction)

Dim intButton
intButton = MsgBox(strAction, _
vbQuestion + vbYesNo, _
L_Welcome_MsgBox_Title_Text )
Ask = intButton = vbYes

End Function

MsgBox “This system is the property of this Corporation, and is intended for” & CRLF & _
“the use of authorized users only. All activities of individuals using this computer” & CRLF & _
“with or without authority, or in excess of their authority, may be monitored and recorded” & CRLF & _
“by system personnel. If any such monitoring reveals evidence of criminal activity or is in” & CRLF & _
“violation of foreign or U.S. state or federal law, such evidence may be provided to law” & CRLF & _
“enforcement officials and/or used for further legal action by this Corporation and/or the” & CRLF & _
“organization’s Information Protection group. Unauthorized use of this system is prohibited” & CRLF & _
“and may result in revocation of access, disciplinary action and/or legal action. The” & CRLF & _
“company reserves the right to monitor and review user activity, files and electronic messages.” & CRLF & _
“REMINDER: Information transmitted to a foreign person on this network may be subject ” & CRLF & _
“to applicable Export Control laws. Contact your Export Coordinator for assistance.” & CRLF & _
“(This machine is not authorized for classified processing)”, _
vbOKOnly, _
“SYSTEM USE MONITORING NOTICE – IPM-003 Banner Statement”

‘*************End of global scripting

”pull local computer name for loggin info.
strComputer = objNetwork.ComputerName

”pull logon id
strUser = objNetwork.UserName

”turn logon id into container name for LDAP queries

Set objConnection = CreateObject(”ADODB.Connection”)
objConnection.Open “Provider=ADsDSOObject;”
Set objCommand = CreateObject(”ADODB.Command”)
objCommand.ActiveConnection = objConnection
objCommand.CommandText = “;(&(objectCategory=User)(samAccountName=” & strUser & “));name;subtree”
Set objRecordSet = objCommand.Execute
On Error Resume Next
strUser = objRecordSet.Fields(”name”)
On Error GoTo 0
objConnection.Close
Set objRecordSet = Nothing
Set objCommand = Nothing
Set objConnection = Nothing

‘’set user to have LDAP queries run
Set objUser = GetObject(”LDAP://cn=” & strUser & “,ou=arra-users,dc=arra,dc=local”)

”\/\/\/\/\/\/Determine Group memberships. PLEASE NOTE: group names must be in UPPER case and the “Left(strGroup, X)”
‘ X must be the number of characters in the group name.
‘\/\/\/\/\/\/\/

arrMemberOf = objUser.GetEx(”memberOf”)

If Err.Number E_ADS_PROPERTY_NOT_FOUND Then
For Each Group in arrMemberOf
strGroup = UCase(Group)
strGroup = Right(strGroup, Len(strGroup) – 3)
If Left(strGroup, 2) = “IT” Then
‘*****IT group scripting

‘’set Z:IT drive
WshShell.Run “net use z: /delete”, 0, False
WshShell.Run “Net use z: \\indarradc04\it”, 0, False

”Prepare to set printers
Set objWMIService = GetObject(”winmgmts:\\” & strComputer & “\root\cimv2″)

”This prevents script from stopping when mapping network printers on the server where they
”are shared from
ON ERROR RESUME NEXT

”Add Printers
objNetwork.AddWindowsPrinterConnection(”\\indarradc03\Xerox WorkCentre 5675 PS”)

‘*****End of IT
Else
If Left(strGroup, 4) = “CSRS” Then
‘*****CSR group scripting

‘*****End of CSR
Else
If Left(strGroup, 10) = “MANAGEMENT” Then
‘*****Management group scripting – NOTE: all managers are members of “Team Leads” group

‘*****End of Management
Else
If Left(strGroup, 10) = “TEAM LEADS” Then
‘*****Team Lead scripting

”Prepare to set printers
Set objWMIService = GetObject(”winmgmts:\\” & strComputer & “\root\cimv2″)

”This prevents script from stopping when mapping network printers on the server
”where they are shared from
ON ERROR RESUME NEXT

”Add Printers
objNetwork.AddWindowsPrinterConnection(”\\indarradc03\Xerox WorkCentre 5675 PS”)

‘*****End of Team Lead
End If
End If
End If
End If
Next
Else
‘*****Create Error Log if groups could not be determined

Set objErrorLog = objFSO.OpenTextFile(”\\indarradc04\errors\signonerrors.txt”, ForAppending, True)
objErrorLog.WriteLine strUser & ” on ” & strComputer & ” could not be found in Active Directory on ” & Date
Err.Clear
End If

Again, let me know if you need help modifying/adding anything for your own use.

**UPDATE(9/25)**

Changed the
WshShell.Exec(”net use…”)
lines to
WshShell.Run “net use…”, 0, False

This allows us(and does it already) to set any outside commands or scripts(in this case mapping drives, but can call bat files or whatever) to run invisibly(the 0), and “False” says to continue with the rest of the script immediately, True would mean to wait for the outside command to complete before continuing. This site has the details.

Run Method(Windows Script Host)

Windows Updates and Proxy Servers

Thursday, September 3rd, 2009

So, in our environment, we have several segregated networks. Each has their own (squid) proxy server and none have previously had issues with automatic updates. All were supposedly set the same way, with the proxy being pushed through group policy. The gpo was set to only push the proxy to normal users and not members of the IT team, mainly because we just don’t like having it. Anyway, there is one network that could not get the microsoft update web page to load. When we looked at the proxy, it looked as though it was redirecting the page to a null site. The reason it was only affecting the one network was: The other networks have the ability to bypass the proxy if the page didn’t load and it wasn’t listed as blocked, whereas this particular network was forced to have all traffice through the proxy. The key to making it work was one simple command:

proxycfg -p <your proxy>:<proxyport>

That sets your proxy info, now you need to restart update services for it to really make a difference:

net stop wuauserv

net start wuauserv

Anyway, I know this is a simple little post, but hope it helps someone.

UPDATE (9/17):

For Vista/Server 2008 use this command instead of proxycfg:

netsh winhttp set proxy [myproxy]:[myport]

VBScript to find a file (virtually) anywhere in the domain.

Wednesday, August 5th, 2009

Alright, I haven’t posted in a while, but I also haven’t had any new issues develop that I felt would be helpful or insightful to any of you out there. But today, I did have to write a script to find out if a file had been copied from the directory it was supposed to be in to any other place in the domain. At first, I thought they were crazy, but I turned to my good friend VBScript and got the job done. There are several pieces to this script, each very useful in it’s own right. First, it connects to the domain controller and finds out what domain you are in(handy if you work on several domains and don’t want to fiddle to make it work different places), then it makes a .txt file with every computer account in the domain on a line. The next step is pinging each of the machines listed to see if they are are available. Then, it connects and scans the C drive (via c$) for the file name recursively scans hidden folders and files as well. Then, it finds any shared folders on the system(say a server, where shares are not on C:) and scans them recursively. It reports if the file was found on the system or not and if it was, the exact location on the machine. Anyway, let me know if you have any questions on how to get this working for different scenarios or need to just make certain snippets work.

***Updated 8/7/09 with revisions to make script shorter, more efficient and work better with regular expression/pattern searching***

''Script to find all machines in AD, search C drive of all machines for a pattern in the filename, then search any shared folders for the file and reports
'' whether it was found and whether the machines are reachable by ping.
'' Side Note -- Can not scan shares on Windows 2000 or older, it will simply skip those shares. It will still scan C drive on Windows 2000, not NT

Option Explicit
CONST HKEY_LOCAL_MACHINE = &H80000002
Const ForReading = 1
Const ForWriting = 2
Const ForAppending = 8
Dim strResultsFile, strServerName, strErrorNumber, strErrorDescription
Dim strAge, strLatestFile, strClientName, strDNSDomain
Dim strBase, strFilter, strAttributes, strQuery
Dim objWMIService, objLocator, objResultsFile, objRootDSE, objCommand, objConnection
Dim objRecordSet
Dim strSearchName
Dim objNetwork : Set objNetwork = CreateObject("WScript.Network")
Dim strFileName : strFileName = "computers.txt"
Dim objFSO : Set objFSO = CreateObject("Scripting.FileSystemObject")
Dim WshShell : Set WshShell = CreateObject("wscript.shell")
Dim i
Dim ii
Dim objFile, objCurrentFile, objTempList, objFS, objList, strCurrentFile2, objLogFile1, objLogFile2
Dim strComputer()
Dim strRet

'Here, you can put in the Regulare Expression pattern to use when searching.
Dim objRegEx : Set objRegEx = CreateObject("VBScript.RegExp")
objRegEx.Global = True
objRegEx.IgnoreCase = True
objRegEx.Pattern = ".*pip_dvalles.*"

Dim IsFound
Dim strReply, png, strPing
Dim strList, objShare, strShare
Dim strShares()
Dim strDate, strTime, strHour, strMinute, strSeconds, Now, NowStart, ConnectTime
NowStart = Now
strResultsFile = "computers.txt"
strDate = CStr(Year(Date) * 10000 + Month(Date) * 100 + Day(Date))
strTime = Time
strHour = Hour (strTime)
strMinute = Minute (strTime)
strSeconds = Second (strTime)
Dim strFound, strNotFound
strFound = "C:\Found.txt"
strNotFound = "C:\NotFound.txt"

Set objLogFile1 = objFSO.OpenTextFile(strNotFound, ForAppending, True)
Set objLogFile2 = objFSO.OpenTextFile(strFound, ForAppending, True)

'Check for the presence of the Computer.txt file in the same folder as the script
If Not objFSO.FileExists(strFileName) Then

Set objResultsFile = objFsO.OpenTextFile (strResultsFile, ForWriting, True)
' Start getting a list of all servers from AD
' Determine DNS domain name from RootDSE object.
Set objRootDSE = GetObject("LDAP://RootDSE")
strDNSDomain = objRootDSE.Get("DefaultNamingContext")
'Start the ADO connection
Set objCommand = CreateObject("ADODB.Command")
Set objConnection = CreateObject("ADODB.Connection")
objConnection.Provider = "ADsDSOObject"
objConnection.Open "Active Directory Provider"
objCommand.ActiveConnection = objConnection

'Set the ADO connection query strings
strBase = ""
strFilter = "(objectCategory=computer)"
strAttributes = "distinguishedName,objectCategory,name"

'Create the Query
strQuery = strBase & ";" & strFilter & ";" & strAttributes & ";subtree"
objCommand.CommandText = strQuery
objCommand.Properties("Page Size") = 100
objCommand.Properties("Timeout") = 30
objCommand.Properties("Cache Results") = False
Set objRecordSet = objCommand.Execute

objRecordSet.MoveFirst

'Find all computers in the domain
While Not objRecordset.EOF
ON ERROR RESUME NEXT
strServerName = objRecordset.Fields("name")
Set objWMIService = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\" & strServerName & "\root\cimv2")
strErrorNumber = Err.Number
strErrorDescription = Err.Description

objResultsFile.WriteLine strServerName

'NEXT!
objRecordSet.MoveNext

Wend
objResultsFile.Close
WScript.Echo "All computer accounts in " & strDNSDOMAIN & " have been found." & vbCrLf & "Click OK to scan for file: " & objSearchFile
Set objFile = objFSO.OpenTextFile(strFileName, ForReading)
Else
Set objFile = objFSO.OpenTextFile(strFileName, ForReading)
End if

'start parsing through computer.txt
Do Until objFile.AtEndOfStream
isFound = FALSE
Redim Preserve strComputer(i)
strComputer(i) = objFile.ReadLine

'Ping Computers to make sure that they are reachable.
Set png = WshShell.exec("ping -n 1 " & strComputer(i))
Do Until png.Status = 1 : WScript.Sleep 10 : Loop
strPing = png.StdOut.ReadAll

'NOTE: The string being looked for in the Instr is case sensitive.
'Do not change the case of any character which appears on the
'same line as a Case InStr. AS this will result in a failure.
Select Case True
Case InStr(strPing, "Request timed out") > 1
strReply = "Request timed out"
Case InStr(strPing, "could not find host") > 1
strReply = "Host not reachable"
Case InStr(strPing, "Reply from") > 1
strReply = "Ping Successful"
End Select

' Connects to the operating system's file system
ON ERROR RESUME NEXT
Set objFS = GetObject("WinNT://" & strComputer(i) & "/LanmanServer,FileService")
objList = ""

' Loops through each share and checks for file
For Each objShare In objFS
strShare = LCase(objShare.name)
Set objTempList = WshShell.Exec("cmd /c dir /a/s/b \\" & strComputer(i) & "\" & strShare)
Do Until objTempList.StdOut.AtEndOfStream
objCurrentFile = objTempList.StdOut.ReadLine
If objRegEx.Test(objFSO.GetBaseName(objCurrentFile)) Then
strCurrentFile2 = objfSO.GetBaseName(objCurrentFile)
objLogFile2.WriteLine Now & " - The file " & objSearchFile & " was found on " & strComputer(i) & " at " & objCurrentFile
isFound = True
Else
If isFound = False Then
isFound = False
Else
isFound = True
End If
End If
Loop
objList = LCase(objShare.name) & vbCrLf & objList
Next

'Check for file on remote PC
Set objTempList = WshShell.Exec("cmd /c dir /a/s/b \\" & strComputer(i) & "c$")
Do Until objTempList.StdOut.AtEndOfStream
objCurrentFile = objTempList.StdOut.ReadLine
If objRegEx.Test(objFSO.GetBaseName(objCurrentFile)) Then
strCurrentFile2 = objfSO.GetBaseName(objCurrentFile)
objLogFile2.WriteLine Now & " - The file " & objSearchFile & " was found on " & strComputer(i) & " at " & objCurrentFile
isFound = True
Else
If isFound = False Then
isFound = False
Else
isFound = True
End If
End If
Loop

'Write to Not Found Log, if not found.
If isFound = False Then
objLogFile1.WriteLine Now & "No File matching the pattern (" & objRegEx.Pattern & ") was found on " & strComputer(i)
End If
Loop
objLogFile1.Close
objLogFile2.Close
WScript.Echo "Done scanning, LogFiles are located at:" & vbCrLf & strFound & vbCrLf & strNotFound & vbCrLf & "Click OK to finish"

Hope this helps someone out there.

Java Remote Install via GPO and Permissions

Monday, June 29th, 2009

Alright, so we had some training that needed the latest Java(6u14) to work.  I extracted the .msi and pushed it out by GPO by doing the following:

Download the version you want from: http://java.com/en/download/manual.jsp

Install Java to the machine you are using.  Once done, go to

C:\documents and settings\<your username>\application data\sun\java\jre<version> folder.

In this folder, there is an msi and a file called data1.cab.  Copy this to a file share accessible by the clients.

Go to GPMC and add  a new GPO, go to Computer Settings>Software Settings>Software Installation>Right click and add new.  Put in the UNC to the msi file(the cab must be in the same directory as the msi btw).  Then set any permissions you want by going to the properties after it is added.

This is the basic way to get Java to install via GPO.  We had one issue, where the training application needed users to have admin rights to the Java folder for the training to run.  Here is what I did for that.

First, make sure you have PSExec installed on the machine you ware working on.

Run a command psexec \\<remote machine name> echo y| cacls “c:\program files\java” /g “<domain>\domain users”:f

This grants any domain users on the machine have /f(full access) to the java folder.  The echo y| is piped in because, cacls command doesnt have a switch to automatically answer y/n to confirm.  this pipes in the y after you run the command.

There is a great program out there for modifying settings in MSI files.  It’s called orca.  you can get it here. Once installed you can do a ctrl+f to find settings and change them.  Some googling may be needed to find what values things need to be set to, but this is one that I do with Java to make it not prompt users for updates constantly.

In orcca, open the jre<version> msi and go to Property table(left column) and find AutoUpdateCheck in the right side.  Change the value to 0(zero).  Then save the msi.  For more options, you can find info on sun’s website and just by looking through the msi in orca.  A lot of the options are selfexplanatory, but there is the ability to go way more in depth than I currently know how, as well.

WSUS Updates

Sunday, June 28th, 2009

Well, it seems not everything was working quite as planned after my last post.  Here are some other processes to help get WSUS up and going, though.

First if you are getting either of these error codes:

both the 0×80190194 and 0×80244019 error codes are the same as HTTP status 404(resource not found).

Check your selfupdate folder and make sure everything is in place.  Then check IIS MIME type settings.  It won’t serve up types it doesn’t know.  Here are the MIME types required for WSUS to operate:

.cab – application/octet-stream
.msp – application/octet-stream
.msi – application/octet-stream
.psf – application/octet-stream

One other thing to check if you are getting the error that “SelfUpdate is Not Working” (I dont remember the code, working from notes/memory here).  Check your registry:

Make sure the value for PortNumber under the “HKLM\SOFTWARE\Microsoft\Update Services\Server\Setup” key is set to the correct port (the one your WSUS site is on, 80, 8350, etc)

I checked, and the value of PortNumber on my WSUS server was 8530. Well, the WSUS (default as well) website is on port 80, so I changed the PortNumber value to 80 (decimal) and restarted IIS. This didn’t seem to clear anything up (I still saw the errors in the logs), but subsequently this past weekend I bounced the server due to some Windows Updates, and I have yet to see any problems so far after the reboot.

One other issue I have seen is Event ID 506 From Windows Server Update Services.  It means clients are unable to connect to the selfupdate folder.  This error comes from selfupdate not being able to get connections on 127.0.0.1:80.  WSUS checks this port to make sure selfupdate is working, so, go to IIS and make sure that it is available.  Also, under the default site in IIS, make sure The selfupdate folder is set for Anonymous logon.  Also, make sure you uncheck require secure authentication on the default site(just selfupdate folder) unless you have WSUS configured for SSL.

This step is crucial and I have had to do it on 3 WSUS servers so far.

1. Open a command window.
2. Type cscript <WSUSInstallDir>\setup\InstallSelfupdateOnPort80.vbs

This makes sure that selfupdate is on the default site.  I have to do this if there is already a site running on default site or sharepoint, so remember this.

I am sorry this was such a sloppy post, but honestly, his is one area where I wanted to post, but just didnt keep enough notes to know exactly what it was that I did to resolve my issues.  Anyway, hopefully some of this jumble helps.

How to Modify Registry Settings via Batch File(or DOS promt) OR Making WSUS work

Wednesday, June 24th, 2009

The need for this came about recently at my new job.  The place has no patch management software in place and is incredibly far behind and failing compliance in their security audits.  I threw in a WSUS server, thinking it would be fairly easy since I had done it before in new environments without ever having a hitch.  Well, let me tell you, this was no picnic.  There were previously 4 seperate WSUS servers for different OUs… Stupid.  Anyway, it took me some time to remove the GPOs and remnants of the ols SUS servers.  They hadn’t been used in over 4 years and none of the current staff knew they ever existed anyway.

I cleaned everything up(or so I thought), and installed WSUS clean on our utility server(running Server 03).  synchronized with Microsoft and approved all critical updates.  I put in a GPO on the domain linked to the OUs containing anything that wasn’t a server, since I wasn’t up for going through checking server updates and they don’t have a test environment.  (There are well over 100 servers here, I don’t want to patch them all with a faulty patch and lose my job in less than a month)… Aanyway, only about 20/500 PCs joined, I tried everything from PSEXECing gpupdate /force, remotely installing the newest windows update client, and a couple other things.  nothing was working.  I went over the Group Policies dozens of times.  Why wasn’t it working?  I still have yet to figure it out, but I do have a workaround.

The settings for the clients that I wanted were as follows:

WSUS Server http://wsus:8530

Download and install every thrusday at 11pm

The registry keys for these settings are at:

HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate

and

HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate\AU

This is what I put in the .bat file:


reg add HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate /v WUServer /t reg_sz /d "http://wsus:8350" /f
reg add HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate /v WUStatusServer /t reg_sz /d "http://wsus:8350" /f
reg add HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate\AU /v UseWUServer /t reg_dword /d 1 /f
reg add HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate\AU /v AUOptions /t reg_dword /d 4 /f
reg add HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate\AU /v NoAutoUpdate /t reg_dword /d 0 /f
reg add HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate\AU /v ScheduledInstallDay /t reg_dword /d 5 /f
reg add HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate\AU /v ScheduledInstallTime /t reg_dword /d 23 /f

I set the script to run at Computer startup via GPO, and voila, They are all joining.  Now I need to figure out the cause of all my pain.  Here are a couple more resources that may help with other questions.  Leave a comment if you have any questions and I’ll do my best to answer it.

MS-DOS “REG” command help

Automatic Updates Registry Values