<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
	<channel>
		<title><![CDATA[Серый форум &mdash; JScript: отлов выключения компьютера]]></title>
		<link>https://forum.script-coding.com/viewtopic.php?id=8634</link>
		<atom:link href="https://forum.script-coding.com/extern.php?action=feed&amp;tid=8634&amp;type=rss" rel="self" type="application/rss+xml" />
		<description><![CDATA[Недавние сообщения в теме «JScript: отлов выключения компьютера».]]></description>
		<lastBuildDate>Sun, 01 Sep 2013 07:44:24 +0000</lastBuildDate>
		<generator>PunBB</generator>
		<item>
			<title><![CDATA[Re: JScript: отлов выключения компьютера]]></title>
			<link>https://forum.script-coding.com/viewtopic.php?pid=75149#p75149</link>
			<description><![CDATA[<div class="codebox"><pre><code>set wshshell=CreateObject(&quot;wscript.shell&quot;)
set fso = CreateObject(&quot;Scripting.FileSystemObject&quot;)

call wshshell.run(&quot;%comspec% /c mofcomp -N:root\cimv2 %SystemRoot%\system32\Wbem\Wbemcons.mof&amp;&amp;pause&quot;,9,-1)
call wshshell.run(&quot;%comspec% /c mofcomp -N:root\subscription %SystemRoot%\system32\Wbem\scrcons.mof&amp;&amp;pause&quot;,9,-1)

Computer=&quot;.&quot;
Set Service = GetObject(&quot;winmgmts:\\&quot; &amp; Computer &amp; &quot;\Root\CIMV2&quot;)

mondel(Service)

Set oFilter = Service.Get(&quot;__EventFilter&quot;).SpawnInstance_
oFilter.Name = &quot;Мой монитор выключения и перезагрузки&quot;
oFilter.QueryLanguage = &quot;WQL&quot;
oFilter.Query = &quot;SELECT * FROM __InstanceCreationEvent WITHIN 1 WHERE TargetInstance ISA &#039;Win32_NTLogEvent&#039;  AND TargetInstance.Logfile = &#039;System&#039; and TargetInstance.SourceName= &#039;USER32&#039; and TargetInstance.EventCode = &#039;1074&#039; or TargetInstance.EventCode = &#039;1076&#039;&quot;
oFilter.Put_

FolderMon=&quot;C:\монитор выключения и перезагрузки&quot;
FileMon=FolderMon &amp; &quot;\Мой монитор выключения и перезагрузки лог.txt&quot;
if NOT fso.FolderExists then fso.CreateFolder FolderMon

Set oConsumer = Service.Get(&quot;LogFileEventConsumer&quot;).SpawnInstance_
oConsumer.Name = &quot;Мой монитор выключения и перезагрузки лог&quot;
oConsumer.FileName = FileMon
oConsumer.Text = &quot;Компьютер: %TargetInstance.ComputerName%, Сообщение: %TargetInstance.Message%, Запись: %TargetInstance.RecordNumber%, Пользователь: %TargetInstance.User%, Источник: %TargetInstance.SourceName%, Время события:  %TargetInstance.TimeGenerated%, Время записи: %TargetInstance.TimeWritten%&quot;
oConsumer.Put_
Set oFilter = Service.Get(&quot;__EventFilter.Name=&#039;Мой монитор выключения и перезагрузки&#039;&quot;)
Set oConsumer = Service.Get(&quot;LogFileEventConsumer.Name=&#039;Мой монитор выключения и перезагрузки лог&#039;&quot;)
Set oBinding = Service.Get(&quot;__FilterToConsumerBinding&quot;).SpawnInstance_
oBinding.Filter = oFilter.Path_
oBinding.Consumer = oConsumer.Path_
oBinding.Put_

SMTP=&quot;mail.n-d.ru&quot;
From=&quot;ginzburg@n-d.ru&quot;
Too=&quot;it@n-d.ru&quot;
Subj=&quot;&quot;&quot;Мои логи выключения и перезагрузки на &quot;&quot; &amp; now&quot;
Body=Subj
SendInterval=86400 * 1000

Script=&quot;Call SendPost(&quot;&quot;&quot; &amp; SMTP &amp; &quot;&quot;&quot;, &quot;&quot;&quot; &amp; Too &amp; &quot;&quot;&quot;, &quot;&quot;&quot; &amp; From &amp; &quot;&quot;&quot;, &quot; &amp; Subj &amp; &quot;, &quot; &amp; Body &amp; &quot;):&quot; &amp; _
&quot;Function SendPost(strSMTPServer, strTo, strFrom, strSubject, strBody):&quot; &amp; _
&quot;    Set iMsg = CreateObject(&quot;&quot;CDO.Message&quot;&quot;):&quot; &amp; _
&quot;    Set iConf = CreateObject(&quot;&quot;CDO.Configuration&quot;&quot;):&quot; &amp; _
&quot;    Set Flds = iConf.Fields:&quot; &amp; _
&quot;    Flds.Item(&quot;&quot;http://schemas.microsoft.com/cdo/configuration/sendusing&quot;&quot;) = 2:&quot; &amp; _
&quot;    Flds.Item(&quot;&quot;http://schemas.microsoft.com/cdo/configuration/smtpserver&quot;&quot;) = strSMTPServer:&quot; &amp; _
&quot;    Flds.Item(&quot;&quot;http://schemas.microsoft.com/cdo/configuration/smtpconnectiontimeout&quot;&quot;) = 10:&quot; &amp; _
&quot;    Flds.Update:&quot; &amp; _
&quot;    iMsg.Configuration = iConf:&quot; &amp; _
&quot;    iMsg.To = strTo:&quot; &amp; _
&quot;    iMsg.From = strFrom:&quot; &amp; _
&quot;    iMsg.Subject = strSubject:&quot; &amp; _
&quot;    iMsg.TextBody = strBody:&quot; &amp; _
&quot;    iMsg.AddAttachment &quot;&quot;&quot; &amp; FileMon &amp; &quot;&quot;&quot;:&quot; &amp; _
&quot;    iMsg.Send:&quot; &amp; _
&quot;End Function&quot;

Set Service=GetObject(&quot;winmgmts:\\&quot; &amp; computer &amp; &quot;\root\subscription&quot;)

mondel(Service)

Set oTimer=Service.Get(&quot;__IntervalTimerInstruction&quot;).SpawnInstance_
oTimer.IntervalBetweenEvents = SendInterval
oTimer.TimerId = &quot;Мой супертаймер для выключения и перезагрузки&quot;
oTimer.Put_
Set oFilter=Service.Get(&quot;__EventFilter&quot;).SpawnInstance_
oFilter.Name = &quot;Мой отправитель логов выключения и перезагрузки&quot;
oFilter.QueryLanguage = &quot;WQL&quot;
oFilter.Query = &quot;SELECT * FROM __TimerEvent WHERE TimerID=&#039;Мой супертаймер для выключения и перезагрузки&#039;&quot;
oFilter.Put_
Set oScript=Service.Get(&quot;ActiveScriptEventConsumer&quot;).SpawnInstance_
oScript.Name = &quot;Мой скрипт отправителя логов выключения и перезагрузки&quot;
oScript.ScriptText = Script
oScript.ScriptingEngine = &quot;VBScript&quot;
oScript.Put_
Set oFilter = Service.Get(&quot;__EventFilter.Name=&#039;Мой отправитель логов выключения и перезагрузки&#039;&quot;)
Set oConsumer = Service.Get(&quot;ActiveScriptEventConsumer.Name=&#039;Мой скрипт отправителя логов выключения и перезагрузки&#039;&quot;)
Set oBinding=Service.Get(&quot;__FilterToConsumerBinding&quot;).SpawnInstance_
oBinding.Filter=oFilter.Path_
oBinding.Consumer=oConsumer.Path_
oBinding.Put_

sub mondel(objService)
    on error resume next
    for each c in objService.ExecQuery(&quot;select * from __EventFilter&quot;)
        if instr(lcase(c.name),&quot;мой&quot;) then
            msgbox c.name
            c.Delete_
        end if
    next
    for each c in objService.ExecQuery(&quot;select * from __IntervalTimerInstruction&quot;)
        if instr(lcase(c.TimerId),&quot;мой&quot;) then
            msgbox c.TimerId
            c.Delete_
        end if
    next
    for each c in objService.ExecQuery(&quot;select * from __TimerEvent&quot;)
        if instr(lcase(c.name),&quot;мой&quot;) then
            msgbox c.name
            c.Delete_
        end if
    next
    for each c in objService.ExecQuery(&quot;select * from LogFileEventConsumer&quot;)
        if instr(lcase(c.name),&quot;мой&quot;) then
            msgbox c.name
            c.Delete_
        end if
    next
    for each c in objService.ExecQuery(&quot;select * from ActiveScriptEventConsumer&quot;)
        if instr(lcase(c.name),&quot;мой&quot;) then
            msgbox c.name
            c.Delete_
        end if
    next
    for each c in objService.ExecQuery(&quot;select * from __FilterToConsumerBinding&quot;)
        if instr(lcase(c.Consumer),&quot;мой&quot;) then
            msgbox c.Consumer
            c.Delete_
        end if
    next
    on error goto 0
end sub

WScript.Quit()

On Error Resume Next
Dim mywriteFile,strComputer,objWMIService,myobj,myobjFile
Set myobj = CreateObject(&quot;Scripting.FileSystemObject&quot;)
If Not myobj.FileExists(&quot;c:\SCOMServers.txt&quot;) Then
Wscript.echo &quot; Input File C:\System.txt is missing. Script cannot proceed without Input File&quot;
Wscript.quit
End If
Set myobjFile = myobj.OpenTextFile(&quot;C:\SCOMServers.txt&quot;, 1)
IDCount = 1
Do Until myobjFile.AtEndOfStream
strcomputer = myobjFile.ReadLine
            Set mywriteFile = myobj.CreateTextFile(&quot;C:\report&quot; &amp; strcomputer &amp;&quot;.csv&quot;,2)
            mywritefile.writeline &quot;Computer Name&quot; &amp; &quot;,&quot; &amp; &quot;Event Message&quot; &amp; &quot;,&quot; &amp; &quot;Record Number&quot; &amp;&quot;,&quot;&amp;&quot;Source Name&quot; &amp;&quot;,&quot; &amp;&quot;Event Type&quot; &amp;&quot;,&quot; &amp;&quot;Time Generated&quot; &amp;&quot;,&quot;&amp;&quot;Time Written&quot; &amp;&quot;,&quot; &amp; &quot; User&quot;
            Set objWMIService = GetObject(&quot;winmgmts:&quot; _  
            &amp; &quot;{impersonationLevel=impersonate}!\\&quot; &amp; strComputer &amp; &quot;\root\cimv2&quot;)
            Set colLoggedEvents = objWMIService.ExecQuery _
            (&quot;Select * from Win32_NTLogEvent Where Logfile = &#039;System&#039; and SourceName= &#039;USER32&#039; and EventCode = &#039;1074&#039; or EventCode = &#039;1076&#039;&quot; )
            For Each objEvent in colLoggedEvents  
      &#039;            Wscript.Echo &quot;Computer Name: &quot; &amp; objEvent.ComputerName
      &#039;            Wscript.Echo &quot;Message: &quot; &amp; objEvent.Message  
      &#039;            Wscript.Echo &quot;Record Number: &quot; &amp; objEvent.RecordNumber  
      &#039;            Wscript.Echo &quot;Source Name: &quot; &amp; objEvent.SourceName
      &#039;            Wscript.Echo &quot;Event Type: &quot; &amp; objEvent.Type  
      &#039;            WScript.Echo &quot;TimeGenerated: &quot; &amp; WMIDateStringToDate(objEvent.TimeGenerated)
       &#039;            WScript.Echo &quot;TimeWritten: &quot; &amp; WMIDateStringToDate(objEvent.TimeWritten)
      &#039;            Wscript.Echo &quot;User: &quot; &amp; objEvent.User
            mywritefile.writeline objEvent.ComputerName &amp; &quot;,&quot; &amp; objEvent.Message &amp; &quot;,,&quot; &amp; objEvent.RecordNumber &amp;&quot;,&quot;&amp; objEvent.SourceName &amp; &quot;,&quot; &amp; objEvent.Type &amp;&quot;,&quot; &amp; WMIDateStringToDate(objEvent.TimeGenerated) &amp; &quot;,&quot; &amp; WMIDateStringToDate(objEvent.TimeWritten) &amp; &quot;,&quot; &amp; objEvent.User
            Next
IDCount = IDcount + 1
loop
      

            Function WMIDateStringToDate(dtmDate)
            &#039;WScript.Echo dtm:
            WMIDateStringToDate = CDate(Mid(dtmDate, 5, 2) &amp; &quot;/&quot; &amp; _
            Mid(dtmDate, 7, 2) &amp; &quot;/&quot; &amp; Left(dtmDate, 4) _
            &amp; &quot; &quot; &amp; Mid (dtmDate, 9, 2) &amp; &quot;:&quot; &amp; Mid(dtmDate, 11, 2) &amp; &quot;:&quot; &amp; Mid(dtmDate,13, 2))
            End Function
</code></pre></div>]]></description>
			<author><![CDATA[null@example.com (smaharbA)]]></author>
			<pubDate>Sun, 01 Sep 2013 07:44:24 +0000</pubDate>
			<guid>https://forum.script-coding.com/viewtopic.php?pid=75149#p75149</guid>
		</item>
		<item>
			<title><![CDATA[Re: JScript: отлов выключения компьютера]]></title>
			<link>https://forum.script-coding.com/viewtopic.php?pid=75111#p75111</link>
			<description><![CDATA[<p>Проверь включена ли опция &quot;Allow shutdown without having to log on&quot; в локальных политиках безопасности:</p><div class="quotebox"><blockquote><p>Завершение работы: разрешить завершение работы системы без выполнения входа в систему.</p><p>Этот параметр безопасности определяет, можно ли завершить работу компьютера, не выполняя вход в систему Windows.</p><p>Если эта политика включена, команду &quot;Завершение работы&quot; можно выбрать на экране входа в Windows.</p><p>Если эта политика отключена, команда &quot;Завершение работы&quot; не отображается на экране входа в Windows. В этом случае, чтобы завершить работу системы, пользователю необходимо успешно выполнить вход в систему и он должен иметь право на завершение работы системы.</p><p>По умолчанию на рабочих станциях: включен.<br /><strong>По умолчанию на серверах: отключен</strong>.</p></blockquote></div><p>Server 2003: Domain Security Setting\Local Polices\Security Options	<br />Shutdown: Allow system to be shutdown without having to log on	</p><p><a href="http://technet.microsoft.com/en-us/library/cc776336%28v=ws.10%29.aspx">http://technet.microsoft.com/en-us/libr … 10%29.aspx</a></p><p>+</p><p>В настройках электропитания - действие при нажатии кнопки электропитания - завершение работы.<br />И отключи скринсейвер.</p><p>+</p><p>В редакторе групповой политики таймаут на закрытие сессий<br />Конфигурация компьютера\Административные шаблоны\Компоненты Windows\Службы терминалов\Сервер терминалов ...</p><p>+</p><p>Можно через редактор групповых политик задать сценарии запуска/завершения, и через скрипт прибивать сессии, и т. п.</p><br /><p>P.S.: И я таки не понял, зачем выключать сервер?</p>]]></description>
			<author><![CDATA[null@example.com (max7)]]></author>
			<pubDate>Sat, 31 Aug 2013 09:05:51 +0000</pubDate>
			<guid>https://forum.script-coding.com/viewtopic.php?pid=75111#p75111</guid>
		</item>
		<item>
			<title><![CDATA[Re: JScript: отлов выключения компьютера]]></title>
			<link>https://forum.script-coding.com/viewtopic.php?pid=75110#p75110</link>
			<description><![CDATA[<p>Хочу что бы, при нажатии кнопки выключения сервака, он завершал все активные задачи, отрубал соединения и выключался.</p>]]></description>
			<author><![CDATA[null@example.com (DnsIs)]]></author>
			<pubDate>Sat, 31 Aug 2013 08:32:42 +0000</pubDate>
			<guid>https://forum.script-coding.com/viewtopic.php?pid=75110#p75110</guid>
		</item>
		<item>
			<title><![CDATA[Re: JScript: отлов выключения компьютера]]></title>
			<link>https://forum.script-coding.com/viewtopic.php?pid=75109#p75109</link>
			<description><![CDATA[<p>Я таки не понял, что в итоге требуется. Опиши конечную задачу и текущее положение.</p><p>Если нужно закрывать сеансы, настрой их закрытие по таймауту при отсутствии подключения, например через пару секунд.<br />Если нужно запретить выключение при активных сеансах, засунь сервер в шкаф-сейф или отключи коннектор power от материнки.</p>]]></description>
			<author><![CDATA[null@example.com (max7)]]></author>
			<pubDate>Sat, 31 Aug 2013 07:27:44 +0000</pubDate>
			<guid>https://forum.script-coding.com/viewtopic.php?pid=75109#p75109</guid>
		</item>
		<item>
			<title><![CDATA[Re: JScript: отлов выключения компьютера]]></title>
			<link>https://forum.script-coding.com/viewtopic.php?pid=75107#p75107</link>
			<description><![CDATA[<p><strong>max7</strong>, суть в том, что сервак с win2003 пашет в уголке без монитора и клавы. Бывает, что остальные компы выключены, но сессии висят и комп отключают кнопкой выключения. Но там появляется злобное окошко, которое не позволяет завершить работу. Вот такие вот дела.</p>]]></description>
			<author><![CDATA[null@example.com (DnsIs)]]></author>
			<pubDate>Sat, 31 Aug 2013 05:02:21 +0000</pubDate>
			<guid>https://forum.script-coding.com/viewtopic.php?pid=75107#p75107</guid>
		</item>
		<item>
			<title><![CDATA[Re: JScript: отлов выключения компьютера]]></title>
			<link>https://forum.script-coding.com/viewtopic.php?pid=75105#p75105</link>
			<description><![CDATA[<p>Можно почитать здесь:<br /><a href="https://hpc.name/thread/46575/p1.html">https://hpc.name/thread/46575/p1.html</a></p><p>И здесь (особенно хорош последний комментарий): <br /><a href="http://www.sql.ru/forum/993760/kak-obrabotat-situaciu-zaversheniya-raboty-ili-perezagruzki">http://www.sql.ru/forum/993760/kak-obra … rezagruzki</a></p>]]></description>
			<author><![CDATA[null@example.com (max7)]]></author>
			<pubDate>Fri, 30 Aug 2013 22:31:07 +0000</pubDate>
			<guid>https://forum.script-coding.com/viewtopic.php?pid=75105#p75105</guid>
		</item>
		<item>
			<title><![CDATA[JScript: отлов выключения компьютера]]></title>
			<link>https://forum.script-coding.com/viewtopic.php?pid=75094#p75094</link>
			<description><![CDATA[<p>Доброго дня.</p><p>Нужно перехватить нажатие кнопки выключения компа.</p><div class="codebox"><pre><code>wsh = WScript.CreateObject(&quot;WScript.Shell&quot;)
wmi = GetObject(&quot;winmgmts:\\\\.\\root\\CIMV2&quot;)
evts = wmi.ExecNotificationQuery(&quot;Select * from Win32_ComputerShutdownEvent&quot;)

while (true) {

    objEvent = evts.NextEvent();

    var enumItems = new Enumerator(objEvent);
    for (; !enumItems.atEnd(); enumItems.moveNext()) {
        if (enumItems.item().Type == 1) {
            wsh.Run(&quot;c:\\Windows\\System32\\shutdown.exe /a&quot;, 1, true)
        }

    }
}</code></pre></div><p>Не работает.&nbsp; Что я делаю не так?</p>]]></description>
			<author><![CDATA[null@example.com (DnsIs)]]></author>
			<pubDate>Fri, 30 Aug 2013 16:16:56 +0000</pubDate>
			<guid>https://forum.script-coding.com/viewtopic.php?pid=75094#p75094</guid>
		</item>
	</channel>
</rss>
