--}}
Новая тема
Вы не можете создавать новые темы.
Т.к. вы неавторизованы на сайте. Пожалуйста назовите себя или зарегистрируйтесь.
Список тем

VMware: скрипт для автоматического перехода в режим паузы всех работающих машин

24
3
С друзьями на NN.RU
В социальных сетях
Поделиться
Перед Вами модифицированный пример-скрипт из поставки дистрибутива VMware.

Алгоритм работы:

1. Проверка всех зарегистрированных машин (определенных в inventory).
1.1. Машина работает.
1.1.1 Ставим на паузу
1.1.2 Проверяем встала или нет.

check_vm.vbs — основной скрипт

'
' VmCOM VBScript Sample Script (sample2)
' Copyright 1998 VMware, Inc. All rights reserved. — VMware Confidential
'
' Permission is hereby granted, free of charge, to any person obtaining a
' copy of the software in this file (the «Software»), to deal in the
' Software without restriction, including without limitation the rights to
' use, copy, modify, merge, publish, distribute, sublicense, and/or sell
' copies of the Software, and to permit persons to whom the Software is
' furnished to do so, subject to the following conditions:
'
' The above copyright notice and this permission notice shall be included in
' all copies or substantial portions of the Software.
'
' The names «VMware» and «VMware, Inc.» must not be used to endorse or
' promote products derived from the Software without the prior written
' permission of VMware, Inc.
'
' Products derived from the Software may not be called «VMware», nor may
' «VMware» appear in their name, without the prior written permission of
' VMware, Inc.
'
' THE SOFTWARE IS PROVIDED «AS IS», WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
' IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
' FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
' VMWARE, INC. BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
' IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
' CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
'
' ------
'
' This program is for educational purposes only.
' It is not to be used in production environments.
'
' Description:
'
' This script displays the virtual machines on the local server.
' It prints the configuration file path and current execution
' state of each VM. If a VM is in the stuck state, the current
' question and its choices are also printed.
' Additionally, if a VM is stuck on an undoable disk related
' question, the script automatically answers 'Keep' on a power-off
' and 'Append' on a power-on.
'
' NOTE: the question-answering logic used is language and product
' dependent, and is only provided for illustration purposes only!
'
' Instructions for Windows 2000 and later operating systems:
'
' - save the contents of this file to a file named 'sample2.vbs'
' unless it's already named that way
'
' - there should be an accompanying file named 'sample2.wsf'
' It is placed in the same directory as this file during
' product installation. This file is responsible for setting
' up the Windows Script Host environment and loading the
' VmCOM type library, thereby enabling this script to
' reference symbolic constants such as vmExecutionState_On
'
' - in a command line window, type:
' cscript //nologo sample2.wsf

'


Set cp = CreateObject(«VmCOM.VmConnectParams»)
Set server = CreateObject(«VmCOM.VmServerCtl»)

server.Connect cp
Set vmCollection = server.RegisteredVmNames

for each vmName in vmCollection
Set vm = CreateObject(«VmCOM.VmCtl»)
s = «path=» & vmName
On error resume next ' Clear error object
vm.Connect cp, vmName
if err.Number = vmErr_VMBUSY then
s = s & « UNAVAILABLE (controlled by local console)»
elseif err.Number <> 0 then
s = s & « ERROR CONNECTING desc='» & err.Description & «'»
else
On error goto 0 'Make errors fatal past this point
s = s & « state=» & State2Str(vm) & « os=» & vm.Config(«guestos»)
if vm.ExecutionState = vmExecutionState_Stuck then
Set q = vm.PendingQuestion
Set choices = q.choices
s = s & « question= '» & q.text & «' choices=»
for each choice in choices
s = s & «[» & choice & «] „
next

' If this looks like an undoable disk save question,
' automatically answer 'Append' or 'Keep'
'
' NOTE: this code makes alot of assumptions about the product
' and the language used, and may break under some environments.
' It is shown for illustration purposes only!


Set r = new RegExp
r.pattern = “undoable disk»„
r.ignorecase = True
Set matches = r.Execute(q.text)

if matches.count > 0 then
for i = 1 to choices.count
if choices(i) = «Append» or choices(i) = «Keep» then
WScript.Echo(s)
s = « --> Automatically selecting '» & q.choices(i) & «' as answer»
vm.AnswerQuestion q, i
exit for
end if end if next
end if
end if
end if
WScript.Echo(s)
Recheck(vm) 'добавляем вызов функции
next

function State2Str(vm)
select case vm.ExecutionState
case vmExecutionState_On
State2Str = «ON»
case vmExecutionState_Off
State2Str = «OFF»
case vmExecutionState_Suspended
State2Str = «SUSPENDED»
case vmExecutionState_Stuck
State2Str = «STUCK»
case else
State2Str = «UNKNOWN»
end select
end function
' Вот и сама функция, выставления ее на паузу и повторной проверки статуса машины
function Recheck(vm)
if vm.ExecutionState = vmExecutionState_On then 'Проверка работы машины
vm.Suspend (vmPowerOpMode_Hard) ' Установка паузы. В документации описаны дполнительные режимы паузы (можно использовать другие)

WScript.Echo «Recheck this VM_machine state=» & State2Str(vm) 'вывод в лог повторной проверки
WScript.Sleep(10000) 'Таймаут, даем время все закрыть
end if
end function*
Далее запускаемый скрипт check_vm.wsf, от которого передается управление к основному check_vm.vbs:

<job id=«Check_vm»>
<reference object=«VmCOM.VmCtl» />
<script language=«VBScript» src=«check_vm.vbs» />
</job>
Ну и наконец bat файл, который вы можете поставить выполнение, например на 22 часа рабочего времени. При таком использовании, никто не забудет, правильно выключить ваш любимый и горячо любимый парк.

cscript check_vm.wsf >> log.txt
shutdown -s -f -t 100


В bat происходит вызов скрипта, с перенаправлением в лог.
Ну shutdown, это как тюнинг на выключение. Можно попробовать поиграть в параметрами.

Пример лога:

path=E:\vmware\Ubuntu\Ubuntu.vmx state=ON os=ubuntu
Recheck this VM_machine state=SUSPENDED
path=E:\vmware\Ubuntu_Kde_4\Ubuntu.vmx state=OFF os=ubuntu
path=E:\development\FreeBSD\FreeBSD.vmx state=ON os=freebsd
Recheck this VM_machine state=SUSPENDED

(c) найдено на хабре, автор remix9
Новая тема
Вы не можете создавать новые темы.
Т.к. вы неавторизованы на сайте. Пожалуйста назовите себя или зарегистрируйтесь.
Список тем
Последние темы форумов
Дорого куплю новые картриджи от лазерных и струйных

РЕАЛЬНО Дорого куплю новые картриджи от лазерных и струйных принтеров и копиров (НР, Canon, Samsung, Xerox, OCE и др.) всех моделей....
Цена: 7 777 руб.

Материнские платы на запчасти и не только

Материнские платы на запчасти и не только Материнские платы и другие комплектующие Отправка в регионы после оплаты. Транспортной...
Цена: 3 000 руб.

Продаю факс (ы) Panasonic– FT932/982

Продаю факс (ы) Panasonic– FT932/982: термоперенос, термобумага, А4
Цена: 350 руб.

Принтер лазерный Avision AP30A

Avision AP30A лазерный принтер черно-белая печать формат A4, 33 стр/мин, 128 Мб, дуплекс, лоток 250 листов и многоцелевой лоток с...
Цена: 9 900 руб.