11 июня 2013 г.

Скриптостроительство

vlsdtv | 15:52 |
1. Ключ из реестра

Нужно было посмотреть ключи на лицензионной 7-ке. Сторонних средств под рукой не оказалось  скачивать было лень, поэтому и нашелся данный скриптик на visual basic,в моих загашниках. Он вытягивает ключик из реестра.
Работает под MS Windows XP, 7, 2003.
Делаем copy-paste и сохраняем под удобным именем

If Wscript.Arguments.Count = 0 Then
    strComputer = inputbox("Введите имя компьютера","Enter computer name")
    if strComputer = "" then wscript.quit
Else
    strCOmputer = Wscript.Arguments.Item(0)
End If
Dim Digits (24)
Digits (0) = "B" : Digits (1) = "C": Digits (2) = "D": Digits (3) = "F":
Digits (4) = "G": Digits (5) = "H": Digits (6) = "J": Digits (7) = "K":
Digits (8) = "M": Digits (9) = "P": Digits (10) = "Q": Digits (11) = "R":
Digits (12) = "T": Digits (13) = "V": Digits (14) = "W": Digits (15) = "X":
Digits (16) = "Y": Digits (17) = "2": Digits (18) = "3": Digits (19) = "4":
Digits (20) = "6" : Digits (21) = "7" : Digits (22) = "8": Digits (23) = "9"
Dim HexBuf (100), HexDigitalPID (15)
Set objReg = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\default:StdRegProv")
objReg.GetBinaryValue &H80000002, "SOFTWARE\Microsoft\Windows NT\CurrentVersion\", "DigitalProductId", HexBuf
' Extract Relevant Section of Digital Product ID

StartOffset = 52 : EndOffset =67
For i = StartOffset to EndOffset
  HexDigitalPID (i-StartOffset) = HexBuf(i)
next

' Convert Encoded Product ID to Activation Key

dLen = 29 : sLen = 15
KEYSTRING =""
for i=dLen-1 to 0 step -1
  if ((i + 1) mod 6) = 0 then
    KEYSTRING = KEYSTRING & "-"
  else
    HN = 0
    For N = (sLen -1) to 0 step -1
      Value = ( (HN *2^8 ) Or HexDigitalPID (N))
      HexDigitalPID (N) = Value \ 24
      HN = (Value mod 24)
    next
    KEYSTRING = KEYSTRING & Digits(HN)
  end if
next
KEYSTRING2 = StrReverse (KEYSTRING)

WScript.Echo KEYSTRING2

2. Чтение из AD параметров компьютеров (Имя, дата создания обьекта, дата последнего входа и т.д.)

'***********************************************************************
' Скрипт вытаcкивает много атрибутов объекта компьютер из домена
' никаких привелегий не требуется кроме пользовательских
'***********************************************************************
' ----------------------------------------------------------------------
Option Explicit
   '--------------имя файла отчета и его создание
 Const StrNameTextFileReport = "c:\LastLogon.csv"
 Set FSO = WScript.CreateObject("Scripting.FileSystemObject")
Set CSVFile=FSO.OpenTextFile(StrNameTextFileReport, 2 ,true)
    '--------------объявление переменных
Dim objRootDSE, strConfig, objConnection, objCommand, strQuery
Dim objRecordSet, objDC
Dim FSO, CSVFile
Dim strDNSDomain, objShell, lngBiasKey, lngBias, k, arrstrDCs()
Dim strDN, dtmDate, objDate, lngDate, objList, strUser
Dim strBase, strFilter, strAttributes, lngHigh, lngLow
   'переменные строки для временного хранения значений атрибутов
Dim Strcn,StrDescription,StrOperatingSystem,StrOperatingSystemVersion,StrOperatingSystemServicePack,StrWhenCreated,StrLogonCount,StrlastLogoff,StrlastLogon
Dim StrRes
Dim objCN,objdistinguishedName,objDescription,objOperatingSystem,objOperatingSystemVersion,objOperatingSystemServicePack,objWhenCreated,objLogonCount,objlastLogoff,objlastLogon
'----------------------------------------
'-------------- Используем объект dictionary для хранения параметров для каждого компьютера
Set objList = CreateObject("Scripting.Dictionary")
objList.CompareMode = vbTextCompare
'--------------objCN
Set objCN = CreateObject("Scripting.Dictionary")
objCN.CompareMode = vbTextCompare
'--------------objdistinguishedName
Set objdistinguishedName = CreateObject("Scripting.Dictionary")
objdistinguishedName.CompareMode = vbTextCompare
'--------------objDescription
Set objDescription = CreateObject("Scripting.Dictionary")
objDescription.CompareMode = vbTextCompare
'--------------objOperatingSystem
Set objOperatingSystem = CreateObject("Scripting.Dictionary")
objOperatingSystem.CompareMode = vbTextCompare
'--------------objOperatingSystemVersion
Set objOperatingSystemVersion = CreateObject("Scripting.Dictionary")
objOperatingSystemVersion.CompareMode = vbTextCompare
'--------------objOperatingSystemServicePack
Set objOperatingSystemServicePack = CreateObject("Scripting.Dictionary")
objOperatingSystemServicePack.CompareMode = vbTextCompare
'--------------WhenCreated
Set objWhenCreated = CreateObject("Scripting.Dictionary")
objWhenCreated.CompareMode = vbTextCompare
'--------------objLogonCount
Set objLogonCount = CreateObject("Scripting.Dictionary")
objLogonCount.CompareMode = vbTextCompare
'--------------objlastLogoff
Set objlastLogoff = CreateObject("Scripting.Dictionary")
objlastLogoff.CompareMode = vbTextCompare
'--------------objlastLogon
Set objlastLogon = CreateObject("Scripting.Dictionary")
objlastLogon.CompareMode = vbTextCompare
'-------------------------------------
'-------------- Получение настроек о зонах времени из регистра
Set objShell = CreateObject("Wscript.Shell")
lngBiasKey = objShell.RegRead("HKLM\System\CurrentControlSet\Control\" & "TimeZoneInformation\ActiveTimeBias")
If UCase(TypeName(lngBiasKey)) = "LONG" Then
  lngBias = lngBiasKey
ElseIf UCase(TypeName(lngBiasKey)) = "VARIANT()" Then
  lngBias = 0
  For k = 0 To UBound(lngBiasKey)
    lngBias = lngBias + (lngBiasKey(k) * 256^k)
  Next
End If
'-------------------------------------
' Определение контекста конфигурации и DNS из RootDSE object.
Set objRootDSE = GetObject("LDAP://RootDSE")
strConfig = objRootDSE.Get("configurationNamingContext")
strDNSDomain = objRootDSE.Get("defaultNamingContext")
'-------------------------------------
' Используем ADO для поиска Active Directory на передмет ObjectClass nTDSDSA.
' Это определит все контроллеры домена
Set objCommand = CreateObject("ADODB.Command")
Set objConnection = CreateObject("ADODB.Connection")
objConnection.Provider = "ADsDSOObject"
objConnection.Open "Active Directory Provider"
objCommand.ActiveConnection = objConnection
  
strBase = "<LDAP://" & strConfig & ">"
strFilter = "(objectClass=nTDSDSA)"
strAttributes = "AdsPath"
strQuery = strBase & ";" & strFilter & ";" & strAttributes & ";subtree"
  
objCommand.CommandText = strQuery
objCommand.Properties("Page Size") = 100
objCommand.Properties("Timeout") = 60
objCommand.Properties("Cache Results") = False
  
Set objRecordSet = objCommand.Execute
'-------------------------------------
' Перечисление родительских оъектов класса nTDSDSA. Save Domain Controller
' AdsPaths в динамическом массиве arrstrDCs.
k = 0
Do Until objRecordSet.EOF
  Set objDC = _
    GetObject(GetObject(objRecordSet.Fields("AdsPath")).Parent)
  ReDim Preserve arrstrDCs(k)
  arrstrDCs(k) = objDC.DNSHostName
  k = k + 1
  objRecordSet.MoveNext
Loop
'-------------------------------------
' Получение атрибутов компьютера на каждом контроллере домена
For k = 0 To Ubound(arrstrDCs)
   strBase = "<LDAP://" & arrstrDCs(k) & "/" & strDNSDomain & ">"
   'strFilter = "(&(objectCategory=person)(objectClass=user))"
   strFilter = "(&(objectCategory=computer)(objectClass=computer))"
   'strAttributes = "distinguishedName,lastLogon"
   strAttributes = "cn,distinguishedName,Description,OperatingSystem,OperatingSystemVersion,OperatingSystemServicePack,WhenCreated,LogonCount,lastLogoff,lastLogon"
   strQuery = strBase & ";" & strFilter & ";" & strAttributes & ";subtree"
   objCommand.CommandText = strQuery
   On Error Resume Next
   Set objRecordSet = objCommand.Execute
   If Err.Number <> 0 Then
      On Error GoTo 0
      WScript.Echo "Domain Controller not available: " & arrstrDCs(k)
   Else
      On Error GoTo 0
      Do Until objRecordSet.EOF
         strDN = objRecordSet.Fields("distinguishedName")
'         objCN.Add strDN, objRecordSet.Fields("cn")
'         objdistinguishedName.Add strDN, objRecordSet.Fields("distinguishedName")
'         objDescription.Add strDN,objRecordSet.Fields("Description")
'         objOperatingSystem.Add strDN,objRecordSet.Fields("OperatingSystem")
'         objOperatingSystemVersion.Add strDN,objRecordSet.Fields("OperatingSystemVersion")
'         objOperatingSystemServicePack.Add strDN,objRecordSet.Fields("OperatingSystemServicePack")
'         objWhenCreated.Add strDN,objRecordSet.Fields("WhenCreated")
'         objLogonCount.Add strDN,objRecordSet.Fields("LogonCount")
'         objlastLogoff.Add strDN,objRecordSet.Fields("lastLogoff")
         StrCN = objRecordSet.Fields("cn").Value
         StrOperatingSystem = objRecordSet.Fields("OperatingSystem")
         StrOperatingSystemVersion = objRecordSet.Fields("OperatingSystemVersion")
         StrOperatingSystemServicePack = objRecordSet.Fields("OperatingSystemServicePack")
         StrWhenCreated = objRecordSet.Fields("WhenCreated")
         StrLogonCount = objRecordSet.Fields("LogonCount")
         StrlastLogoff = objRecordSet.Fields("lastLogoff")
         StrlastLogon = objRecordSet.Fields("lastLogon")
         '---------------------------- добавление данных в "Scripting.Dictionary"-s
         If objList.Exists(strDN) Then
            If dtmDate > objList(strDN) Then
               objList(strDN) = FuncConvertTime( StrlastLogon ) 'dtmDate
            End If
         Else
            objList.Add strDN, FuncConvertTime( StrlastLogon ) 'dtmDate
         End If
         '----------------------------
         If objCN.Exists(strDN) Then
         Else
            objCN.Add strDN, StrCN
         End If
         '----------------------------
         If objdistinguishedName.Exists(strDN) Then
         Else
            objdistinguishedName.Add strDN, strDN
         End If        
         '----------------------------
               '********************************
         objDescription.Add strDN,FuncGetDescriptionComputerFromAdByDistinguishedName( strDN )
         '----------------------------
         If objOperatingSystem.Exists(strDN) Then
         Else
            objOperatingSystem.Add strDN, StrOperatingSystem
         End If        
         '----------------------------
         If objOperatingSystemVersion.Exists(strDN) Then
         Else
            objOperatingSystemVersion.Add strDN, StrOperatingSystemVersion
         End If        
         '----------------------------
         If objOperatingSystemServicePack.Exists(strDN) Then
         Else
            objOperatingSystemServicePack.Add strDN, StrOperatingSystemServicePack
         End If        
         '----------------------------
         If objWhenCreated.Exists(strDN) Then
         Else
            objWhenCreated.Add strDN, StrWhenCreated
         End If
         '----------------------------
         If objlastLogoff.Exists(strDN) Then
         Else
            objlastLogoff.Add strDN, FuncConvertTime(StrlastLogoff)
         End If     
         '----------------------------
         If objLogonCount.Exists(strDN) Then
         Else
            objLogonCount.Add strDN, StrLogonCount
         End If
         '----------------------------
         objRecordSet.MoveNext
      Loop
   End If
   Exit For
Next
'-------------------------------------
' Вывод даты последнего lastLogon для каждого пользователя
CSVFile.WriteLine("cn;distinguishedName;Description;OperatingSystem;OperatingSystemVersion;OperatingSystemServicePack;WhenCreated;LogonCount;lastLogoff;lastLogon")
For Each strUser In objList
   CSVFile.WriteLine(objCN(strUser) & " ; " & strUser & " ; " & objDescription(strUser) & " ; " & objOperatingSystem(strUser) & " ; " & objOperatingSystemVersion(strUser) & " ; " & objOperatingSystemServicePack(strUser)  & " ; " & objWhenCreated(strUser)  & " ; " & objLogonCount(strUser) & " ; " & objlastLogoff(strUser) & " ; " & objList(strUser))
Next
'-------------------------------------
' Очистка
objConnection.Close
Set objRootDSE = Nothing
Set objConnection = Nothing
Set objCommand = Nothing
Set objRecordSet = Nothing
Set objDC = Nothing
Set objDate = Nothing
Set objList = Nothing
Set objShell = Nothing
WScript.Echo "Файл " & StrNameTextFileReport & " заполнен"
'********************************************************
'функция преобразует дату из числового формата в нормальный
Function FuncConvertTime(x)
' Получение настроек о зонах времени из регистра
         Set objShell = CreateObject("Wscript.Shell")
         lngBiasKey = objShell.RegRead("HKLM\System\CurrentControlSet\Control\" & "TimeZoneInformation\ActiveTimeBias")
         If UCase(TypeName(lngBiasKey)) = "LONG" Then
           lngBias = lngBiasKey
         ElseIf UCase(TypeName(lngBiasKey)) = "VARIANT()" Then
           lngBias = 0
           For k = 0 To UBound(lngBiasKey)
             lngBias = lngBias + (lngBiasKey(k) * 256^k)
           Next
         End If
         On Error Resume Next
         Set objDate = x'lastLogon'lngDate
         If Err.Number <> 0 Then
            On Error GoTo 0
            dtmDate = #1/1/1601#
         Else
            On Error GoTo 0
            lngHigh = objDate.HighPart
            lngLow = objDate.LowPart
            If lngLow < 0 Then
               lngHigh = lngHigh + 1
            End If
            If (lngHigh = 0) And (lngLow = 0 ) Then
               FuncConvertTime = #1/1/1601#
            Else
               FuncConvertTime = #1/1/1601# + (((lngHigh * (2 ^ 32)) + lngLow)/600000000 - lngBias)/1440
            End If
         End If
          
End Function
'********************************************************
'функция возвращает описание компьютера из AD по DistinguishedName
Function FuncGetDescriptionComputerFromAdByDistinguishedName( DN )
   Dim LDAPQuery
   LDAPQuery = "LDAP://" & DN ' & vbCrLf
   'WScript.Echo "<<" & LDAPQuery & ">>"
   Dim objComputer
   Dim StrobjPropertyDescription
   Set objComputer = GetObject( LDAPQuery )
      '--------------Description
   On Error Resume Next
   FuncGetDescriptionComputerFromAdByDistinguishedName = objComputer.Get("Description")
   If IsNull(FuncGetDescriptionComputerFromAdByDistinguishedName) Then
      FuncGetDescriptionComputerFromAdByDistinguishedName = "-"
   Else
   End If
   StrobjPropertyDescription = Null
End Function

Комментариев нет :

Отправить комментарий

Search