Search string in text file in Windows

  • Works only in Windows!

Create batch-file with name «findrow.bat» and save the following code:

@echo off
rem (c) 18.09.2015
rem infile - file in which you want to search a string
set infile=%1
set searchstring=%2
rem offset - include additional lines to (example, -3) or after (example, 3) search string
set offset=%3
rem get number of search string in file
for /F "delims=:" %%i in ('findstr /N /I /C:%searchstring% %infile%') do (set par=%%i)
set /a pos=%par%+%offset%
goto start
:1
if %offset% LSS 0 set k=1
if %offset% GTR 0 set k=-1
if [%pos%]==[%par%] goto end
set /a pos=%pos%+%k%
rem displays the search string (and additional)
:start
for /f "usebackq delims=" %%x in (`find /n /v "" %infile% ^| find "[%pos%]"`) do (set value=%%x)
echo %value%
goto 1
:end

File creation «findrow.bat» has three input parameters that must always be asked:

findrow.bat %1 %2 %3

Where:
%1 — file in which you want to search a string
%2 — search string
%3 — include additional lines to (example, -3) or after (example, 3) search string

Let’s look at a more complex case, for example, the search string in the binary log of server MySQL. Need to find a command ‘DROP TABLE `mysalers`’ in the binary log mysql-bin.000001:

mysqlbinlog --database=sale "c\:MySQL\data\mysql-bin.000001" > "d:\binlog.txt" | d:\findrow.bat "d:\binlog.txt" "DROP TABLE `mysalers`" -3
output
--------
[325]# at 6558
[326]#150918 10:51:09 server id 1  end_log_pos 6679 CRC32 0x22af3729    Query
thread_id=1     exec_time=0     error_code=0
[327]SET TIMESTAMP=1442562669/*!*/;
[328]DROP TABLE `mysalers` /* generated by server */

As a result, we obtain the desired command to delete a table `mysalers` and 3 lines going to it. These lines are also important because they contain the position of the search string and the future planned for her in the binary log. These positions can then be used when restoring the database of MySQL when you want to skip some commands.

VBScript collect events print from Windows logs

Скрипт позволяет собирать события печати из журналов Windows с локального или удаленного компьютера(ов) и импортировать их в базу Oracle.

Требования для машины, на которой запускаете скрипт:

  • ОС Windows  (7, XP, Server 2003, Server 2008)
  • Oracle client (or instant client) version 10.2 and above.
  • Запускать скрипт под пользователем, который входит в группу Администрирования на других компьютерах сети.

Требования к базе Oracle:

  • Oracle DB 10.2 and above.
  • Создать в какой-нибудь схеме базы Oracle таблицы:
/* список компьютеров, по которым нужно собирать события печати */
CREATE TABLE PRINTLOG_COMPUTERS
(COMPUTER       VARCHAR2(100));
/* сюда будут писаться данные по печати */
CREATE TABLE PRINTLOG
(SYSDATETIME    DATE,
CREATEDTIME     DATE,
OS              VARCHAR2(50),
EVENTID         NUMBER,
SOURCENAME      VARCHAR2(128),
COMPUTER        VARCHAR2(100),
USERNAME        VARCHAR2(128),
MESSAGE         VARCHAR2(4000));
/* сюда будут писаться ошибки, возникающие при сборе событий */
CREATE TABLE PRINTLOG_ERROR
(SYSDATETIME    DATE,
COMPUTER        VARCHAR2(100),
ERRORMESSAGE    VARCHAR2(512));
  • В таблицу PRINTLOG_COMPUTERS внести имена компьютеров, по которым будет собираться статистика печати.

Требования к компьютерам, с которых будут собираться события печати из журналов Windows:

  • Желательно, чтобы компьютеры были под управлением Windows (7, XP, Server 2003, Server 2008)
  • И чтобы находились в одном домене

Исходник скрипта, с комментариями:

'### [ VBScript ]
'### (c) 02.04.2015
'### What: collects events printing (10, 307) from Windows events logs on local or remote computer and writes them to the Oracle database
'### Author: souluran

Dim objWMIService
Dim colLoggedEvents
Dim colLogFiles
Dim ObjLogFile
Dim objEvent
Dim errCon
Dim errMessage
Dim strSearchString
Dim con
Dim objRecordset
Dim PROC, SQL, ERRINS, INS
Dim objRegistry
Dim strKeyPath
Dim flag
Dim arrSubKeys
Dim subkey
Dim EventCode
Dim LogFile
Dim OverWrite
Const HKEY_LOCAL_MACHINE = &H80000002

On Error Resume Next

'--> connection parameters to Oracle
Driver   = "************" '--> for example "Oracle in instantclient_11_2"
dbName   = "************"
dbUser   = "************" '--> better to have a user with the DBA or have privileges Select/Insert/Delete on tables PRINTLOG_COMPUTERS, PRINTLOG, PRINTLOG_ERROR
Password = "************"
dbSchema = "************" '--> scheme that created the table PRINTLOG_COMPUTERS, PRINTLOG, PRINTLOG_ERROR

'--> open connect to Oracle
Set con = CreateObject("ADODB.Connection")
con.ConnectionTimeOut = 20
con.CommandTimeout = 120
con.Open "Driver={" & Driver & "};DBQ=" & dbName & ";UID=" & dbUser & ";PWD=" & Password

Err.Clear
'--> check connect to Oracle
If Err.Number <> 0 Then
    'error handling:
    errCon = "ORACLE: " & Err.Number & " Srce: " & Err.Source & " Desc: " &  Err.Description
    'WScript.Echo errStr
    Err.Clear
    'WScript.Quit
End If

'--> set the start and the end dates for the collection
begdate = "20150101 00:00:00"
enddate = "20150430 23:59:59"

'--> get list of computers
SQL = "select COMPUTER from " & dbSchema & ".PRINTLOG_COMPUTERS order by 1"
Set objRecordset = con.Execute(SQL)
Do Until objRecordset.EOF
    
    Computer = objRecordset.Fields("COMPUTER").Value
    'WScript.Echo Computer

Err.Clear
    '--> check computer to access
    Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & Computer & "\root\cimv2")
    If Err.Number <> 0 Then
        errMessage = Err.Description
        'WScript.Echo errMessage
        ERRINS = "INSERT INTO " & dbSchema & ".printlog_error VALUES(sysdate,'" & Computer & "','" & errMessage & "')"
        Set objRecordsetErr = con.Execute(ERRINS)
        Err.Clear
        errMessage = vbNullString
    Else    
        '--> check version OS Windows
        Set colOperatingSystems = objWMIService.ExecQuery("Select * from Win32_OperatingSystem")
        OS = vbNullString
        For Each objOperatingSystem in colOperatingSystems
            OS = objOperatingSystem.Caption
            Exit For
        Next
        'WScript.Echo OS
        
        '--> set logfile and evencode for Windows XP and 7
        If InStr(OS, "Windows XP") > 0 Or InStr(OS, "Windows(R) XP") > 0 Or
  InStr(OS, "Server 2003") > 0 Then
            LogFile = "System"
            EventCode = "10" 'event print for Windows XP (2003)
        ElseIf InStr(OS, "Windows 7") > 0 Or InStr(OS, "Windows(R) 7") Or InStr(OS, "Server 2008") > 0 Then
            LogFile = "Microsoft-Windows-PrintService/Operational"
            EventCode = "307" 'event print for Windows 7 (2008)
            
            '--> check exists registry key for read printing events on Windows 7
            Set objRegistry = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & Computer & "\root\default:StdRegProv")
            strKeyPath = "SYSTEM\CurrentControlSet\services\eventlog"
            objRegistry.EnumKey HKEY_LOCAL_MACHINE, strKeyPath, arrSubKeys
            flag = 0
            For Each subkey In arrSubKeys
                If subkey = LogFile Then
                    flag = 1
                    Exit For
                End If
            Next
            
            If flag = 0 Then
                'WScript.Echo "Create new key Microsoft-Windows-PrintService/Operational."
                strKeyPath = "SYSTEM\CurrentControlSet\services\eventlog\Microsoft-Windows-PrintService/Operational"
                objRegistry.CreateKey HKEY_LOCAL_MACHINE, strKeyPath
            End If
        End If
    
        Rec = 0
        '--> check the log for events
        Set colLogFiles = objWMIService.ExecQuery("Select * from Win32_NTLogEvent Where Logfile = '" & LogFile & "' and EventCode = '" & EventCode & "'")
        For Each ObjLogFile In colLogFiles
            Rec = 1
            Exit For
        Next
    
        If Rec = 0 Then
            errMessage = "The " & LogFile & " are failed or not contained events " & EventCode
            'WScript.Echo errMessage
            ERRINS = "INSERT INTO " & dbSchema & ".PRINTLOG_ERROR VALUES(sysdate,'" & Computer & "','" & errMessage & "')"
            Set objRecordsetErr = con.Execute(ERRINS)
            errMessage = vbNullString
        Else 
        
        '--> option overwrite exists records in table (0 - OFF, 1 - ON)
        OverWrite = 0
        If OverWrite = 1 Then
            DEL = "DELETE FROM " & dbSchema & ".PRINTLOG where computer = '" & computer & "' and trunc(CREATEDTIME) >= to_date(substr('" & begdate & "', 1, 8), 'yyyymmdd') " _
                & " and trunc(CREATEDTIME) <= to_date(substr('" & enddate & "', 1, 8), 'yyyymmdd')"
            Set objRecordsetDel = con.Execute(DEL)
        End If

            '--> search events in a given period
            cnt = 0        
            Set colLoggedEvents = objWMIService.ExecQuery("Select * from Win32_NTLogEvent Where Logfile = '" & LogFile & "' and EventCode = '" & EventCode & "' and TimeGenerated >= '"& begdate &"' and TimeGenerated <= '" & enddate & "'")
            cnt = colLoggedEvents.Count
            If cnt > 0 Then
                'WScript.Echo cnt
                For Each objEvent In colLoggedEvents
                     strSearchString = objEvent.Message
                 
                     EventCode = objEvent.EventCode
                     SourceName = objEvent.SourceName
                     If InStr(objEvent.ComputerName, ".keramin.int") > 0 Then
                        ComputerName = LCase(objEvent.ComputerName)
                     Else
                        ComputerName = LCase(objEvent.ComputerName) & ".keramin.int"
                     End If
                     UserName = LCase(objEvent.User)
                     CreatedTime = objEvent.TimeWritten
                     Message = Replace(objEvent.Message, "'", "")
                         
                     INS = "INSERT INTO " & dbSchema & ".PRINTLOG VALUES(sysdate, to_date(substr('" & CreatedTime & "', 1, 14), 'yyyymmddhh24miss'),'" & OS & "','" & EventCode & "','"    & SourceName & "','" & ComputerName & "','" & UserName & "','" & Message & "')"
                     Set objRecordsetIns = con.Execute(INS)
                             
                Next

            Else
                errMessage = "There was no events print in " & LogFile & " from " & begdate & " to " & enddate
                'WScript.Echo errMessage
                'ERRINS = "INSERT INTO " & dbSchema & ".PRINTLOG_ERROR VALUES(sysdate,to_date(substr('" & begdate & "', 1, 8), 'yyyymmdd'),'" & Computer & "','" & errMessage & "')"
                'Set objRecordsetErr = con.Execute(ERRINS)
                errMessage = vbNullString
            End If
        End if
    End If
    
objRecordset.MoveNext
Loop

'--> close connect to Oracle
con.Close
Set objRecordsetErr = Nothing
Set objRecordsetIns = Nothing
Set objRecordsetDel = Nothing
Set con = Nothing
 >        End if
    End If
    
objRecordset.MoveNext
Loop

'--> close connect to Oracle
con.Close
Set objRecordsetErr = Nothing

А вот маленький запрос =), который возвращает нужные для статистики данные по таблице PRINTLOG:

SELECT SYSDATETIME,
         CREATEDTIME,
         EVENTID,
         SOURCENAME,
         COMPUTER,
         OS,
         USERNAME,
         SUBSTR (
            REGEXP_REPLACE (MESSAGE,
                            'Документ \d+, |Document \d+, ',
                            ''),
            1,
              REGEXP_INSTR (
                 REGEXP_REPLACE (MESSAGE,
                                 'Документ \d+, |Document \d+, ',
                                 ''),
                 'владельца|owned|, которым владеет')
            - 1)
            DOC,
         REGEXP_REPLACE (
            TRIM (
               REGEXP_REPLACE (
                  SUBSTR (
                     MESSAGE,
                     REGEXP_INSTR (
                        MESSAGE,
                        'владельца|owned by|, которым владеет')),
                  'владельца |owned by |, которым владеет')),
            ' (.*)')
            OWNER,
         SUBSTR (
            REGEXP_REPLACE (
               SUBSTR (
                  MESSAGE,
                  REGEXP_INSTR (
                     MESSAGE,
                     'напечатан на |был распечатан на |was printed ')),
               'напечатан на |был распечатан на |was printed on '),
            1,
              REGEXP_INSTR (
                 REGEXP_REPLACE (
                    SUBSTR (
                       MESSAGE,
                       REGEXP_INSTR (
                          MESSAGE,
                          'напечатан на |был распечатан на |was printed on ')),
                    'напечатан на |был распечатан на |was printed on '),
                 'через порт|via port|through port')
            - 2)
            PRINTER,
         SUBSTR (
            REGEXP_REPLACE (
               SUBSTR (
                  MESSAGE,
                  REGEXP_INSTR (MESSAGE,
                                'через порт |via port |through port ')),
               'через порт |via port |through port '),
            1,
              REGEXP_INSTR (
                 REGEXP_REPLACE (
                    SUBSTR (
                       MESSAGE,
                       REGEXP_INSTR (
                          MESSAGE,
                          'через порт |via port |through port ')),
                    'через порт |via port |through port '),
                 ' Размер: | Размер в байтах: | Size in bytes: ')
            - 3)
            PORT,
         SUBSTR (
            REGEXP_REPLACE (
               SUBSTR (
                  MESSAGE,
                  REGEXP_INSTR (
                     MESSAGE,
                     'Размер: |Размер в байтах: |Size in bytes: ')),
               'Размер: |Размер в байтах: |Size in bytes: '),
            1,
              REGEXP_INSTR (
                 REGEXP_REPLACE (
                    SUBSTR (
                       MESSAGE,
                       REGEXP_INSTR (
                          MESSAGE,
                          'Размер: | Размер в байтах: | Size in bytes: ')),
                    'Размер: | Размер в байтах: | Size in bytes: '),
                 ' байт;|число страниц: |(.|;) Pages printed: |(.|;) Страниц напечатано: ')
            - 1)
            BYTES,
         TRIM (
            REGEXP_REPLACE (
               SUBSTR (
                  MESSAGE,
                  REGEXP_INSTR (
                     MESSAGE,
                     ' байт; |число страниц: | Pages printed: | Страниц напечатано: ')),
                  ' байт; |число страниц: |Страниц напечатано: |(p|P)ages printed: |[.] Действий пользователя не требуется[.]|[.] No user action is required[.]|'
               || CHR (13)
               || CHR (10)))
            PAGES,
         MESSAGE
FROM printlog
ORDER BY 1;

Если будут какие-то вопросы обращайтесь, возможно помогу.
Также в скором времени создам пост с подобный скриптом, но написанном на Python.

Переполнение NONPAGED/PAGED POOL

  • Исследования проводились для Windows XP, 2003

Если один из пулов (paged pool или nonpaged pool) бесконечно растет и не высвобождается память для работы иных процессов, то это может привести к зависанию или нестабильной работе ОС или приложений.

1. Для исследования того, какой процесс (драйвер) вызывает переполнение paged pool (nonpaged pool) пула памяти, понадобится набор утилит из Windows Rootkit:

  • POOLMON.exe — в реальном времени отображает заполнение и освобождение пулов памяти процессами(драйверами), но вместо их названия показывает их теги(tags).
  • STRINGS.exe — по тегу найденному при помощи POOLMON, определяет название процессов
  • SIGCHECK.exe — по названию процесса находит полное его описание (к какому приложению он относится, версия, размер и т.п.)

2. Где можно посмотреть загрузки пулов. Это можно сделать, открыв Менеджер Задач (в cmd> taskmgr). Перейти в закладку Производительность(Perfomance). В отдельном блоке Kernel Memory (K) увидим Total, Paged, Nonpaged.

3. Анализ пулов
3.1 Запускаем POOLMON.exe. В нем выполняем сортировку по типу пула (NONPAGED или PAGED), нажимая букву <P>. Затем сортируем по величине занимаемой области пула в байтах, нажимая букву <B>.
3.2 Запоминаем название тега драйвера (например, SaEe), который занимает больше всего пула памяти или странно себя ведет, т.е. периодически увеличивается, при этом почти не высвобождая память для других процессов.

4. Поиск драйвера процесса по тегу его образа
4.1 Поскольку большинство образов драйверов находятся в директории %Systemroot%\System32\Drivers, то утилиты STRINGS и SIGCHECK нужно поместить в каталог c:\WINDOWS\system32\drivers\.
4.2 Открыть CMD и выполнить команду:

c:\WINDOWS\system32\drivers\strings.exe * | findstr tag 

,где <tag> — имя тага процесса (вводить не менее 3-х символа тега).

Пример,

c:\WINDOWS\system32\drivers\strings.exe * | findstr SaEe

Данная команда выведет все процессы содержащие 4 заданных символа в названии образа драйвера.
Пример,

C:\WINDOWS\system32\drivers\srtsp.sys: hSaEeWj

Из результат поиска видим, что по настоящему тег образа драйвера может состоять из большего количества символов, чем отобразил POOLMON. В нашем случае поиск привели к образу драйвера srtsp.sys
4.3 Получив имя образа драйвера, при помощи SIGCHECK можно получить информации о том, от какого приложения этот драйвер. Для этого выполняем в CMD:

c:\WINDOWS\system32\drivers\Sigcheck srtsp.sys

В результате получили следующую информацию:

C:\WINDOWS\system32\drivers\srtsp.sys: 
Verified: Signed 
Signing date: 23:08 04.03.2011 
Publisher: Symantec Corporation 
Description: Symantec AutoProtect 
Product: AutoProtect 
Version: 10.3 
File version: 10.3.6.4

Наш драйвер относится к Антивирусу Symantec (продукт AutoProtect автозащита самого антивируса), его версия 10.3.6.4 5. Теперь, когда у нас есть «имя винновника» загрузки пула, можно удалить или переустановить приложение, либо попытаться обновить драйвер, или же бороздить Google в поисках готового решения подобной проблемы для данного приложения.

Запуск приложени по расписанию от SYSTEM в Windows Server 2008 R2

Для того, чтобы приложение запустилось по расписанию (Task Scheduler) от SYSTEM в Windows Server 2008 R2, необходимо, чтобы существовал каталог desktop по одному из путей (в зависимости от разрядности приложения):

c:\Windows\SysWOW64\config\systemprofile\desktop    (x86)
c:\Windows\System32\config\systemprofile\desktop    (x64)

Если каталога нет, то создаем его вручную.