Создание msi-пакетов и установка любого ПО средствами групповых политик Windows
Доброго времени суток, Хабр! Хочу представить интересный, по моему мнению, способ создания msi-инсталляторов для любого программного обеспечения и, как следствие, развертывание его средствами GPO. Подчеркну, что описанный метод не подразумевает создание «слепков» системы, а использует нативные инсталляторы софта, при чем для создания msi применяются только бесплатные для коммерческого использования продукты.
Введение, пара ссылок и дисклеймер
Каждый нормальный инсталлятор ПО имеет возможность автоматической установки с определенными или заложенными по умолчанию параметрами. Суть моего метода проста и заключается в том, чтобы запаковать нативный инсталлятор в «контейнер» msi и запустить его с необходимыми параметрами командной строки. В сети куча информации по автоматической установке того или иного приложения, и я не буду заострять на этом внимание. Наша цель, повторюсь, — установка ПО средствами групповых политик. Кстати, некоторые из вас могут возразить, что установку можно производить через ZAW, но, к сожалению, данный метод применим только для установки с правами текущего пользователя и не может применяться для централизованной автоматической установки приложений.
Интересный цикл статей по установке ПО через ГП. Для новичков рекомендую прочитать все, чтобы потом не спрашивать, чем отличается тип установки «назначенный» от «публичный».
Необходимый софт. Exe to MSI Converter freeware и всем известная orca Первый нужен для того, чтобы создать msi из exe, а вторая — чтобы получившийся msi-ник смог установиться через групповые политики.
Метод не претендует на полную уникальность и в некоторых местах могут встречаться излишества, которых можно было бы избежать, но это связанно отсутствием желания и необходимости слишком глубоко вникать в параметры таблиц msi-пакетов. Первоначальной целью ставилось быстро найти бесплатный способ создания msi и после нескольких часов, проведенных в чтении зарубежных форумов и бесконечных перезагрузках виртуальной машины, метод был найден. Также, статья — это не обзор интерфейса программ, и скриншотов вы не увидите.
Создание и подготовка пакета
- Запускаем exe to msi и указываем в нем путь к exe-установщику firefox. По ранее найденной в сети информации становится понятно, что по-тихому установить огнелиса можно с параметрами -ms -ira. Их-то и указываем во втором поле exe to msi и жмем «Build MSI».
- Казалось бы все, msi-пакет готов. Действительно, запустив получившийся результат мы получим установленный в системе firefox и в статье можно было бы ставить точку. К сожалению, не все так просто. Текущий пакет установки не пригоден для развертывания через GPO и при загрузке компьютера вы будете получать совершенно ничего не объясняющие ошибки в логах «произошла неисправимая ошибка. » А все дело в том, что разработчики exe to msi тоже хотят есть и их бесплатный продукт генерирует msi «не по правилам».
- Ну что ж, берем орку и открываем в ней наш эмсиайник.
- Первым делом находим в левом списке таблицу Property и обращаем внимания на два поля — ProductCode и UpgradeCode. Эти два поля должны быть уникальны для каждого продукта, а наш exe to msi генерит всегда одинаковые. Ну что ж, не беда, жмем в верхнем меню View -> Summary Information, находим поле PackageCode и жмем New GUID. Получившийся результат копируем в буфер обмена и вставляем в ProductCode. Повторяем для UpgradeCode и наконец для самого PackageCode. Тут же в Summary Information правим поле Title на Mozilla Firefox, остальное по желанию. Это, по сути, ни на что не влияет.
- Опять же в таблице Property меням ProductName на Mozilla Firefox (я до кучи меняю еще ARPCONTACT и Manufacturer). Можно так же поставить правильное значение для ProductVersion.
- Вроде бы GUID и прочие «IDы» поменяли, но как показывает практика, этого недостаточно. Жмите в orca Tools –> Validate, снимите птицу Show INFO Messages и нажимайте Go.
- Как видите, вылезла куча ошибок на наличие/отсутствие некоторых таблиц и значений. Я не стал заморачиваться и просто взял первый попавшийся (7zip x64 9.20) небольшой msi и скопировал оттуда 4 недостающие таблицы (через Export-Import, естественно): _Validation, AdminExecuteSequence, AdminUISequence и AdvtExecuteSequence. На самом деле, я уверен, что можно создать «правильный» msi-инсталлятор, без лишнего мусора, но не забывайте, наша цель всего лишь запустить родной setup приложения в тихую.
- После добавления таблиц проходим снова Tools –> Validate (к слову, первый раз проверку можно вообще не делать и сразу импортировать таблицы). Если вы тоже взяли за основу msi от 7zip, то результатом будет шесть эрроров, которые необходимо устранить. Жмите Close, удаляйте лишние поля, отмеченные красным.
- В конце можно еще раз проверить валидацию и убедиться что остались лишь ничем не мешающие варнинги. Сохраняем msi.
- Вот в принципе и все, осталось добавить msi в ГП и назначить необходимые свойства.
Нюансы
- При установке описанным выше методом у вас появятся как бы две копии софта. Первая — собственно нужное приложение, а вторая — исходный msi-ник, ведь мы же его как бы поставили. В принципе, это ни на что не влияет, кроме как на отображение в «Установка и удаление программ», и то, только в Windows XP (если вы ничего не меняли, кроме указанного мной). Минусом может быть появление лишних программ при автоматической инвентаризации софта, если вы ее используете.
- Автоматически удалить приложение теми же средствами развертывания не получится. Точнее получится, но удалится только и так не нужный msi-контейнер. Ну можно повозиться со свойствами msi при его создании, чтобы оно захватывало с собой установленное ранее приложение, так же втихую. Я такой задачи не ставил.
- При установке обновлений ПО нужно указывать в свойствах ГП приложения, чтобы оно заменяло предыдущее, т.е обязательно предварительно удаляло старое. Это гарантирует, что у вас не будут плодиться те самые никому не сдавшиеся левые дубли приложений в «установке и удалении программ».
- Чтобы установить приложение, имеющее дистрибутив из нескольких файлов, вам придется сначала упаковать его в exe, который при запуске сам распакуется и даст команду для тихой установки. Рекомендую создавать sfx-архивы средствами того же 7-zip.
- Ничего не мешает ставить ПО через скрипты автозагрузки. Более того, такой метод более гибкий, и я давно его использую через свои скрипты. Вот только использование родных средств ГП получается намного быстрее, т. к. простое создание msi из exe занимает пару минут.
- Windows 7 почему-то не пишет «Установка управляемого приложения. », а просто говорит «пожалуйста, подождите». При первом развертывании всей кучи софта разом или при установке тяжелого приложения это может сподвигнуть юзера на звонок админу или нажатие кнопки резет.
- групповые политики
- создание msi-пакета
Use Group Policy to remotely install software
This article describes how to use Group Policy to automatically distribute programs to client computers or users.
Applies to: Windows Server 2012 R2
Original KB number: 816102
Summary
You can use Group Policy to distribute computer programs by using the following methods:
- Assigning software You can assign a program distribution to users or computers. If you assign the program to a user, it’s installed when the user logs on to the computer. When the user first runs the program, the installation is completed. If you assign the program to a computer, it’s installed when the computer starts, and it’s available to all users who log on to the computer. When a user first runs the program, the installation is completed.
- Publishing software You can publish a program distribution to users. When the user logs on to the computer, the published program is displayed in the Add or Remove Programs dialog box, and it can be installed from there.
Windows Server 2003 Group Policy automated-program installation requires client computers that are running Microsoft Windows 2000 or a later version.
Create a distribution point
To publish or assign a computer program, create a distribution point on the publishing server by following these steps:
- Log on to the server as an administrator.
- Create a shared network folder where you’ll put the Windows Installer package (.msi file) that you want to distribute.
- Set permissions on the share to allow access to the distribution package.
- Copy or install the package to the distribution point. For example, to distribute a .msi file, run the administrative installation ( setup.exe /a ) to copy the files to the distribution point.
Create a Group Policy Object
To create a Group Policy Object (GPO) to use to distribute the software package, follow these steps:
- Start the Active Directory Users and Computers snap-in by clicking Start, pointing to Administrative Tools, and then clicking Active Directory Users and Computers.
- In the console tree, right-click your domain, and then click Properties.
- Click the Group Policy tab, and then click New.
- Type a name for this new policy, and then press Enter.
- Click Properties, and then click the Security tab.
- Clear the Apply Group Policy check box for the security groups that you don’t want this policy to apply to.
- Select the Apply Group Policy check box for the groups that you want this policy to apply to.
- When you’re finished, click OK.
Assign a package
To assign a program to computers that are running Windows Server 2003, Windows 2000, or Windows XP Professional, or to users who are logging on to one of these workstations, follow these steps:
- Start the Active Directory Users and Computers snap-in by clicking Start, pointing to Administrative Tools, and then clicking Active Directory Users and Computers.
- In the console tree, right-click your domain, and then click Properties.
- Click the Group Policy tab, select the policy that you want, and then click Edit.
- Under Computer Configuration, expand Software Settings.
- Right-click Software installation, point to New, and then click Package.
- In the Open dialog box, type the full Universal Naming Convention (UNC) path of the shared installer package that you want. For example, \\\\.msi .
Important Don’t use the Browse button to access the location. Make sure that you use the UNC path of the shared installer package.
Publish a package
To publish a package to computer users and make it available for installation from the Add or Remove Programs list in Control Panel, follow these steps:
- Start the Active Directory Users and Computers snap-in by clicking Start, pointing to Administrative Tools, and then clicking Active Directory Users and Computers.
- In the console tree, right-click your domain, and then click Properties.
- Click the Group Policy tab, click the policy that you want, and then click Edit.
- Under User Configuration, expand Software Settings.
- Right-click Software installation, point to New, and then click Package.
- In the Open dialog box, type the full UNC path of the shared installer package that you want. For example, \\file server\share\file name.msi .
Important Don’t use the Browse button to access the location. Make sure that you use the UNC path of the shared installer package.
Note Because there are several versions of Windows, the following steps may be different on your computer. If they are, see your product documentation to complete these steps.
- Log on to a workstation that is running Windows 2000 Professional or Windows XP Professional by using an account that you published the package to.
- In Windows XP, click Start, and then click Control Panel.
- Double-click Add or Remove Programs, and then click Add New Programs.
- In the Add programs from your network list, click the program that you published, and then click Add. The program is installed.
- Click OK, and then click Close.
Redeploy a package
In some cases, you may want to redeploy a software package (for example, if you upgrade or change the package). To redeploy a package, follow these steps:
- Start the Active Directory Users and Computers snap-in by clicking Start, pointing to Administrative Tools, and then clicking Active Directory Users and Computers.
- In the console tree, right-click your domain, and then click Properties.
- Click the Group Policy tab, click the Group Policy Object that you used to deploy the package, and then click Edit.
- Expand the Software Settings container that contains the software installation item that you used to deploy the package.
- Click the software installation container that contains the package.
- In the right-pane of the Group Policy window, right-click the program, point to All Tasks, and then click Redeploy application. You will receive the following message:
Redeploying this application will reinstall the application everywhere it is already installed. Do you want to continue?
Remove a package
To remove a published or assigned package, follow these steps:
- Start the Active Directory Users and Computers snap-in by clicking Start, pointing to Administrative Tools, and then clicking Active Directory Users and Computers.
- In the console tree, right-click your domain, and then click Properties.
- Click the Group Policy tab, click the Group Policy Object that you used to deploy the package, and then click Edit.
- Expand the Software Settings container that contains the software installation item that you used to deploy the package.
- Click the software installation container that contains the package.
- In the right-pane of the Group Policy window, right-click the program, point to All Tasks, and then click Remove.
- Perform one of the following actions:
- Click Immediately uninstall the software from users and computers, and then click OK.
- Click Allow users to continue to use the software but prevent new installations, and then click OK.
- Close the Group Policy snap-in, click OK, and then closet the Active Directory Users and Computers snap-in.
Troubleshoot
Published packages are displayed on a client computer after you use a Group Policy to remove them.
This situation can occur when a user has installed the program but hasn’t used it. When the user first starts the published program, the installation is finished. Group Policy then removes the program.
При подготовке материала использовались источники:
https://habr.com/ru/articles/141719/
https://learn.microsoft.com/en-us/troubleshoot/windows-server/group-policy/use-group-policy-to-install-software