Показать полную графическую версию : Visual Basic Script настройка
websssite
24-05-2019, 06:40
Добрый день! Ребят у меня есть скрипт, но я сам лично со скриптами мало работаю, помогите изменить путь так, чтобы скрипт скачивал установочные файлы с расшаренной папки, допустим у меня установочные лежат в windows server 2016 C:/fusioninventory в этой папке
Сам скрипт скачивает установочные с гитхаба, мне этого не надо, так как я пытаюсь запустить скрипт на всех компьютерах домена
Сам скрипт лежит здесь:
https://raw.githubusercontent.com/fusioninventory/fusioninventory-agent/2.4.x/contrib/windows/fusioninventory-agent-deployment.vbs
если SetupLocation (https://github.com/fusioninventory/fusioninventory-agent/blob/9bb787fc4194b713c318ffee62d0ad67c073c6c8/contrib/windows/fusioninventory-agent-deployment.vbs#L88) не http, то он запускается с cmd (https://github.com/fusioninventory/fusioninventory-agent/blob/9bb787fc4194b713c318ffee62d0ad67c073c6c8/contrib/windows/fusioninventory-agent-deployment.vbs#L413)
websssite
26-05-2019, 16:58
А как изменить путь, когда я изменяю вот эту строку вначале кода
SetupLocation = "https://github.com/fusioninventory/fusioninventory-agent/releases/download/" & SetupVersion, то скрипт не запускается пишет ошибку синтаксическую
Я изменяю так: SetupLocation = "C:/fusioninventory " & SetupVersion
Или я пишу неправильно?
Я изменяю так: SetupLocation = "C:/fusioninventory " & SetupVersion »
Указывать нужно путь к инсталляционному файлу, находящемуся на разделённом ресурсе на сервере, а не локальный путь сервера. Насколько я понимаю.
websssite
26-05-2019, 18:18
иснталляционных пакетов у меня 2, для 64 битных и для 86 битных
А как указать их обоих? Эти 2 инсталляционных пакета лежат в 1 папке: C:/fusioninventory
И еще при запуске скрипта у меня запрашивает админский пароль, а как запустить чтобы у обычных пользователей не спрашивали пароли админов? в фоновом режиме?
А как указать их обоих? »
«Обоих» — никак. Но Вам это и не нужно. Используемое по умолчанию SetupArchitecture = "Auto" и так выберет потребный пакет в зависимости от разрядности клиентской операционной системы.
Эти 2 инсталляционных пакета лежат в 1 папке: C:/fusioninventory »
Во-первых, в C:\fusioninventory (хоть NT и позволяет использовать прямой слэш вместо обратного, не следует сим злоупотреблять). Во-вторых, скрипту совершенно безразлично, где они находятся локально. Ему нужен путь, откуда скрипт, исполняющийся на клиентской машине, сможет взять эти пакеты. Посему он должен включать в себя путь к разделённому ресурсу на сервере, где будут находиться эти пакеты. В-третьих, SetupVersion:
' SetupVersion
' Setup version with the pattern <major>.<minor>.<release>[-<package>]
'
у Вас соответствует именам используемых пакетов?
И еще при запуске скрипта у меня запрашивает админский пароль, а как запустить чтобы у обычных пользователей не спрашивали пароли админов? в фоновом режиме? »
Вы не написали, как именно Вы делаете:
я пытаюсь запустить скрипт на всех компьютерах домена »
SetupLocation = "C:/fusioninventory " & SetupVersion »
дополню: пробел не нужен, и "& SetupVersion" тоже (а то получится C:\fusioninventory2.4\..)
В итоге выполняется такой путь: C:\fusioninventory\fusioninventory-agent_windows-Auto_2.4.exe" (Auto в имени файла меняется на GetSystemArchitecture() - x86/x64)
кроме того, в SetupOptions (https://github.com/fusioninventory/fusioninventory-agent/blob/9bb787fc4194b713c318ffee62d0ad67c073c6c8/contrib/windows/fusioninventory-agent-deployment.vbs#L105), наверное, нужно указать свой glpi-сервер.
websssite
28-05-2019, 11:11
А скрипт поймет этот путь? он точно выберет свою архитектуру?
C:\fusioninventory\fusioninventory-agent_windows-Auto_2.4.exe" (Auto в имени файла меняется на GetSystemArchitecture() - x86/x64)
websssite
28-05-2019, 11:43
Sham, Я по вашей последнему совету сделал все правильно
Теперь я когда наблюдаю после входа в систему на пользовательском компьютере win10x64 порядок действий скрипта, он сидит в диспетчере задач как выполняющиеся задача, а спустя 2 мин нет действий или изменений, вроде скрипт должен установить программу же в /program files?
Даже инфа не выходит в веб системе
Используемый скрипт написан без ошибок? вообще может у меня сам скрипт кривой?
websssite, пока Вы не начнёте отвечать на все озвученные вопросы, мы можем только гадать.
websssite
28-05-2019, 13:36
у Вас соответствует именам используемых пакетов? »
Да соответствует полностью! до пункта описания архитектуры
Вы не написали, как именно Вы делаете: »
На скрине показал
websssite, используйте установку в режиме не «на пользователя», а «на машину» (подраздел не User configuration, а Computer configuration).
Теперь покажите содержимое Вашего скрипта (обрамив его тэгом «code»).
websssite
28-05-2019, 14:31
Теперь покажите содержимое Вашего скрипта (обрамив его тэгом «code»). »
'
' ------------------------------------------------------------------------
' fusioninventory-agent-deployment.vbs
' Copyright (C) 2010-2017 by the FusionInventory Development Team.
'
' http://www.fusioninventory.org/ http://forge.fusioninventory.org/
' ------------------------------------------------------------------------
'
' LICENSE
'
' This file is part of FusionInventory project.
'
' This file is free software; you can redistribute it and/or modify it
' under the terms of the GNU General Public License as published by the
' Free Software Foundation; either version 2 of the License, or (at your
' option) any later version.
'
'
' This file is distributed in the hope that it will be useful, but WITHOUT
' ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
' FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
' more details.
'
' You should have received a copy of the GNU General Public License
' along with this program; if not, write to the Free Software Foundation,
' Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA,
' or see <http://www.gnu.org/licenses/>.
'
' ------------------------------------------------------------------------
'
' @package FusionInventory Agent
' @file .\contrib\windows\fusioninventory-agent-deployment.vbs
' @author(s) Benjamin Accary <meldrone@orange.fr>
' Christophe Pujol <chpujol@gmail.com>
' Marc Caissial <marc.caissial@zenitique.fr>
' Tomas Abad <tabadgp@gmail.com>
' Guillaume Bougard <gbougard@teclib.com>
' @copyright Copyright (c) 2010-2017 FusionInventory Team
' @license GNU GPL version 2 or (at your option) any later version
' http://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html
' @link http://www.fusioninventory.org/
' @link http://forge.fusioninventory.org/projects/fusioninventory-agent
' @since 2012
'
' ------------------------------------------------------------------------
'
'
'
' Purpose:
' FusionInventory Agent Unatended Deployment.
'
'
Option Explicit
Dim Force, Verbose
Dim Setup, SetupArchitecture, SetupLocation, SetupOptions, SetupVersion
'
'
' USER SETTINGS
'
'
' SetupVersion
' Setup version with the pattern <major>.<minor>.<release>[-<package>]
'
SetupVersion = "2.5"
' SetupLocation
' Depending on your needs or your environment, you can use either a HTTP or
' CIFS/SMB.
'
' If you use HTTP, please, set to SetupLocation a URL:
'
' SetupLocation = "http://host[:port]/[absolut_path]" or
' SetupLocation = "https://host[:port]/[absolut_path]"
'
' If you use CIFS, please, set to SetupLocation a UNC path name:
'
' SetupLocation = "\\host\share\[path]"
'
' You also must be sure that you have removed the "Open File Security Warning"
' from programs accessed from that UNC.
'
' Location for Release Candidates
' SetupLocation = "https://github.com/TECLIB/fusioninventory-agent-windows-installer/releases/download/" & SetupVersion
SetupLocation = "\\test.kz\fusioninventory\fusioninventory-agent_windows-Auto_" & SetupVersion
' SetupArchitecture
' The setup architecture can be 'x86', 'x64' or 'Auto'
'
' If you set SetupArchitecture = "Auto" be sure that both installers are in
' the same SetupLocation.
'
SetupArchitecture = "Auto"
' SetupOptions
' Consult the installer documentation to know its list of options.
'
' You should use simple quotes (') to set between quotation marks those values
' that require it; double quotes (") doesn't work with UNCs.
'
SetupOptions = "/acceptlicense /runnow /server='http://glpi.test.kz/plugins/fusioninventory/' /S"
' Setup
' The installer file name. You should not have to modify this variable ever.
'
Setup = "fusioninventory-agent_windows-" & SetupArchitecture & "_" & SetupVersion & ".exe"
' Force
' Force the installation even whether Setup is previously installed.
'
Force = "No"
' Verbose
' Enable or disable the information messages.
'
' It's advisable to use Verbose = "Yes" with 'cscript //nologo ...'.
'
Verbose = "No"
'
'
' DO NOT EDIT BELOW
'
'
Function AdvanceTime(nMinutes)
Dim nMinimalMinutes, dtmTimeFuture
' As protection
nMinimalMinutes = 5
If nMinutes < nMinimalMinutes Then
nMinutes = nMinimalMinutes
End If
' Add nMinutes to the current time
dtmTimeFuture = DateAdd ("n", nMinutes, Time)
' Format the result value
' The command AT accepts 'HH:MM' values only
AdvanceTime = Hour(dtmTimeFuture) & ":" & Minute(dtmTimeFuture)
End Function
Function baseName (strng)
Dim regEx, ret
Set regEx = New RegExp
regEx.Global = true
regEx.IgnoreCase = True
regEx.Pattern = ".*[/\\]([^/\\]+)$"
baseName = regEx.Replace(strng,"$1")
End Function
Function GetSystemArchitecture()
Dim strSystemArchitecture
Err.Clear
' Get operative system architecture
On Error Resume Next
strSystemArchitecture = CreateObject("WScript.Shell").ExpandEnvironmentStrings("%PROCESSOR_ARCHITECTURE%")
If Err.Number = 0 Then
' Check the operative system architecture
Select Case strSystemArchitecture
Case "x86"
' The system architecture is 32-bit
GetSystemArchitecture = "x86"
Case "AMD64"
' The system architecture is 64-bit
GetSystemArchitecture = "x64"
Case Else
' The system architecture is not supported
GetSystemArchitecture = "NotSupported"
End Select
Else
' It has been not possible to get the system architecture
GetSystemArchitecture = "Unknown"
End If
End Function
Function isHttp(strng)
Dim regEx, matches
Set regEx = New RegExp
regEx.Global = true
regEx.IgnoreCase = True
regEx.Pattern = "^(http(s?)).*"
If regEx.Execute(strng).count > 0 Then
isHttp = True
Else
isHttp = False
End If
Exit Function
End Function
Function IsInstallationNeeded(strSetupVersion, strSetupArchitecture, strSystemArchitecture)
Dim strCurrentSetupVersion
' Compare the current version, whether it exists, with strSetupVersion
If strSystemArchitecture = "x86" Then
' The system architecture is 32-bit
' Check if the subkey 'SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\FusionInventory Agent' exists
' This subkey is now deprecated
On error resume next
strCurrentSetupVersion = WshShell.RegRead("HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\FusionInventory Agent\DisplayVersion")
If Err.Number = 0 Then
' The subkey 'SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\FusionInventory Agent' exists
If strCurrentSetupVersion <> strSetupVersion Then
ShowMessage("Installation needed: " & strCurrentSetupVersion & " -> " & strSetupVersion)
IsInstallationNeeded = True
End If
Exit Function
Else
' The subkey 'SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\FusionInventory Agent' doesn't exist
Err.Clear
' Check if the subkey 'SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\FusionInventory-Agent' exists
On error resume next
strCurrentSetupVersion = WshShell.RegRead("HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\FusionInventory-Agent\DisplayVersion")
If Err.Number = 0 Then
' The subkey 'SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\FusionInventory-Agent' exists
If strCurrentSetupVersion <> strSetupVersion Then
ShowMessage("Installation needed: " & strCurrentSetupVersion & " -> " & strSetupVersion)
IsInstallationNeeded = True
End If
Exit Function
Else
' The subkey 'SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\FusionInventory-Agent' doesn't exist
Err.Clear
ShowMessage("Installation needed: " & strSetupVersion)
IsInstallationNeeded = True
End If
End If
Else
' The system architecture is 64-bit
' Check if the subkey 'SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\FusionInventory Agent' exists
' This subkey is now deprecated
On error resume next
strCurrentSetupVersion = WshShell.RegRead("HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\FusionInventory Agent\DisplayVersion")
If Err.Number = 0 Then
' The subkey 'SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\FusionInventory Agent' exists
If strCurrentSetupVersion <> strSetupVersion Then
ShowMessage("Installation needed: " & strCurrentSetupVersion & " -> " & strSetupVersion)
IsInstallationNeeded = True
End If
Exit Function
Else
' The subkey 'SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\FusionInventory Agent' doesn't exist
Err.Clear
' Check if the subkey 'SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\FusionInventory-Agent' exists
On error resume next
strCurrentSetupVersion = WshShell.RegRead("HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\FusionInventory-Agent\DisplayVersion")
If Err.Number = 0 Then
' The subkey 'SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\FusionInventory-Agent' exists
If strCurrentSetupVersion <> strSetupVersion Then
ShowMessage("Installation needed: " & strCurrentSetupVersion & " -> " & strSetupVersion)
IsInstallationNeeded = True
End If
Exit Function
Else
' The subkey 'SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\FusionInventory-Agent' doesn't exist
Err.Clear
' Check if the subkey 'SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\FusionInventory-Agent' exists
On error resume next
strCurrentSetupVersion = WshShell.RegRead("HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\FusionInventory-Agent\DisplayVersion")
If Err.Number = 0 Then
' The subkey 'SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\FusionInventory-Agent' exists
If strCurrentSetupVersion <> strSetupVersion Then
ShowMessage("Installation needed: " & strCurrentSetupVersion & " -> " & strSetupVersion)
IsInstallationNeeded = True
End If
Exit Function
Else
' The subkey 'SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\FusionInventory-Agent' doesn't exist
Err.Clear
ShowMessage("Installation needed: " & strSetupVersion)
IsInstallationNeeded = True
End If
End If
End If
End If
End Function
Function IsSelectedForce()
If LCase(Force) <> "no" Then
ShowMessage("Installation forced: " & SetupVersion)
IsSelectedForce = True
Else
IsSelectedForce = False
End If
End Function
' http://www.ericphelps.com/scripting/samples/wget/index.html
Function SaveWebBinary(strSetupLocation, strSetup)
Const adTypeBinary = 1
Const adSaveCreateOverWrite = 2
Const ForWriting = 2
Dim web, varByteArray, strData, strBuffer, lngCounter, ado, strUrl
strUrl = strSetupLocation & "/" & strSetup
'On Error Resume Next
'Download the file with any available object
Err.Clear
Set web = Nothing
Set web = CreateObject("WinHttp.WinHttpRequest.5.1")
If web Is Nothing Then Set web = CreateObject("WinHttp.WinHttpRequest")
If web Is Nothing Then Set web = CreateObject("MSXML2.ServerXMLHTTP")
If web Is Nothing Then Set web = CreateObject("Microsoft.XMLHTTP")
web.Open "GET", strURL, False
web.Send
If Err.Number <> 0 Then
SaveWebBinary = False
Set web = Nothing
Exit Function
End If
If web.Status <> "200" Then
SaveWebBinary = False
Set web = Nothing
Exit Function
End If
varByteArray = web.ResponseBody
Set web = Nothing
'Now save the file with any available method
On Error Resume Next
Set ado = Nothing
Set ado = CreateObject("ADODB.Stream")
If ado Is Nothing Then
Set fs = CreateObject("Scripting.FileSystemObject")
Set ts = fs.OpenTextFile(baseName(strUrl), ForWriting, True)
strData = ""
strBuffer = ""
For lngCounter = 0 to UBound(varByteArray)
ts.Write Chr(255 And Ascb(Midb(varByteArray,lngCounter + 1, 1)))
Next
ts.Close
Else
ado.Type = adTypeBinary
ado.Open
ado.Write varByteArray
ado.SaveToFile CreateObject("WScript.Shell").ExpandEnvironmentStrings("%TEMP%") & "\" & strSetup, adSaveCreateOverWrite
ado.Close
End If
SaveWebBinary = True
End Function
Function ShowMessage(strMessage)
If LCase(Verbose) <> "no" Then
WScript.Echo strMessage
End If
End Function
'
'
' MAIN
'
'
Dim nMinutesToAdvance, strCmd, strSystemArchitecture, strTempDir, WshShell
Set WshShell = WScript.CreateObject("WScript.shell")
nMinutesToAdvance = 5
' Get system architecture
strSystemArchitecture = GetSystemArchitecture()
If (strSystemArchitecture <> "x86") And (strSystemArchitecture <> "x64") Then
ShowMessage("The system architecture is unknown or not supported.")
ShowMessage("Deployment aborted!")
WScript.Quit 1
Else
ShowMessage("System architecture detected: " & strSystemArchitecture)
End If
' Check and auto detect SetupArchitecture
Select Case LCase(SetupArchitecture)
Case "x86"
' The setup architecture is 32-bit
SetupArchitecture = "x86"
Setup = Replace(Setup, "x86", SetupArchitecture, 1, 1, vbTextCompare)
ShowMessage("Setup architecture: " & SetupArchitecture)
Case "x64"
' The setup architecture is 64-bit
SetupArchitecture = "x64"
Setup = Replace(Setup, "x64", SetupArchitecture, 1, 1, vbTextCompare)
ShowMessage("Setup architecture: " & SetupArchitecture)
Case "auto"
' Auto detection of SetupArchitecture
SetupArchitecture = strSystemArchitecture
Setup = Replace(Setup, "Auto", SetupArchitecture, 1, 1, vbTextCompare)
ShowMessage("Setup architecture detected: " & SetupArchitecture)
Case Else
' The setup architecture is not supported
ShowMessage("The setup architecture '" & SetupArchitecture & "' is not supported.")
WScript.Quit 2
End Select
' Check the relation between strSystemArchitecture and SetupArchitecture
If (strSystemArchitecture = "x86") And (SetupArchitecture = "x64") Then
' It isn't possible to execute a 64-bit setup on a 32-bit operative system
ShowMessage("It isn't possible to execute a 64-bit setup on a 32-bit operative system.")
ShowMessage("Deployment aborted!")
WScript.Quit 3
End If
If IsSelectedForce() Or IsInstallationNeeded(SetupVersion, SetupArchitecture, strSystemArchitecture) Then
If isHttp(SetupLocation) Then
ShowMessage("Downloading: " & SetupLocation & "/" & Setup)
If SaveWebBinary(SetupLocation, Setup) Then
strCmd = WshShell.ExpandEnvironmentStrings("%ComSpec%")
strTempDir = WshShell.ExpandEnvironmentStrings("%TEMP%")
ShowMessage("Running: """ & strTempDir & "\" & Setup & """ " & SetupOptions)
WshShell.Run """" & strTempDir & "\" & Setup & """ " & SetupOptions, 0, True
ShowMessage("Scheduling: DEL /Q /F """ & strTempDir & "\" & Setup & """")
WshShell.Run "AT.EXE " & AdvanceTime(nMinutesToAdvance) & " " & strCmd & " /C ""DEL /Q /F """"" & strTempDir & "\" & Setup & """""", 0, True
ShowMessage("Deployment done!")
Else
ShowMessage("Error downloading '" & SetupLocation & "\" & Setup & "'!")
End If
Else
ShowMessage("Running: """ & SetupLocation & "\" & Setup & """ " & SetupOptions)
WshShell.Run "CMD.EXE /C """ & SetupLocation & "\" & Setup & """ " & SetupOptions, 0, True
ShowMessage("Deployment done!")
End If
Else
ShowMessage("It isn't needed the installation of '" & Setup & "'.")
End If
используйте установку в режиме не «на пользователя», а «на машину» (подраздел не User configuration, а Computer configuration). »
до входа пользователя это значит да?
Точно сработает по вашему указанию?
Кстати как туда добавить чтобы тестировался только 1 компьютер? с АД
Кстати как туда добавить чтобы тестировался только 1 компьютер? с АД »
Проще всего — создайте отдельную политику, привяжите её к подразделению, в котором будет только одна машина.
до входа пользователя это значит да? »
Можно и так сказать.
Точно сработает по вашему указанию? »
Точно не сработает при привязке к простым пользователям.
websssite
28-05-2019, 15:04
Iska, а сам код правильный? нет там баяна? :)
используйте установку в режиме не «на пользователя», а «на машину» (подраздел не User configuration, а Computer configuration). »
Можете написать полный путь примерно > Конфигурация компьютера> Политика или Настройка?, полный путь можете написать?
SetupLocation = "\\test.kz\fusioninventory" '(только папка без слеша) ибо "CMD.EXE /C """ & SetupLocation & "\" & Setup & """ " & SetupOptions, где Setup - конечное нередактируемое имя файла.
Iska, а сам код правильный? »
Смотреть надо.
Теперь покажите в Проводнике содержимое разделённого ресурса \\test.kz\fusioninventory.
Можете написать полный путь примерно > Конфигурация компьютера> Политика или Настройка?, полный путь можете написать? »
Конфигурация компьютера, да. Путь — аналогичный же, как в Конфигурации пользователя, только скрипты там будут именоваться не Logon/Logoff, а Startup/Shutdown:
https://i.imgur.com/gQ59JPt.png
websssite
29-05-2019, 11:44
Теперь покажите в Проводнике содержимое разделённого ресурса \\test.kz\fusioninventory. »
Вот мой путь \\ad\fusioninventory\
websssite
29-05-2019, 12:32
Конфигурация компьютера, да. Путь — аналогичный же, как в Конфигурации пользователя, только скрипты там будут именоваться не Logon/Logoff, а Startup/Shutdown: »
Здесь да?
websssite
29-05-2019, 14:27
Вот смотрите, когда я запускаю скрипт через Конфигурация компьютера, да. Путь — аналогичный же, как в Конфигурации пользователя, только скрипты там будут именоваться не Logon/Logoff, а Startup/Shutdown: » как вы говорили, скрипт не работает
А если запустить как пользователь Конфигурация Пользователя>Политики>Конфигурация Windows>Вход в систему, скрипт оттуда работает локально видит установщик, но запрашивает логин и пароль админа скрин прилагаю
© OSzone.net 2001-2012
vBulletin v3.6.4, Copyright ©2000-2025, Jelsoft Enterprises Ltd.