Меню Рубрики

Windows run bat as administrator

Runas (выполнить bat-файл под админом, не вводя пароля)

Избитая, наверное, уже тема, но все же
есть необходимость выполнить бат файл под админом не вводя пароля, нашёл такие решения, но что-то не взлетают

может я что-то не то пишу?

Runas, .bat и server 2k8
Собственно такая ситуация, нужно запустить программу требующую права админа с учетки имеющие права.

Как запустить runas в батнике без ввода пароля?
я заношу в батнике в буфер пароль(пароль 1), но команда runas не видит его echo 1 | runas.

Если ОС — Windows XP, то выполнить один BAT-файл, а если ОС — Windows 7, — другой BAT-файл
Доброго времени. Кто будет добр и подскажет решение. Надо чтобы bat определял версию ОС (XP или 7).

Runas не работает под системной учётной записью
здравствуйте. проблема такая: если в запущенной под системной уч. записью командной строке.

Phil,
Запуск от имени администратора без запросов
Вот здесь я описывал подробно принцип повышения прав.

Добавлено через 7 минут
Если речь идет об удаленном запуске скриптов, я бы наверное выбрал либо PSEXEC, либо Powershell(Invoke-command), либо планировщик (SCHTASKS)

При использовании RUNAS, вам все равно нужно будет ввести пароль хотя бы 1 раз (при использовании ключа \Savecred)
На вскидку не помню, как это работает при запуске на удаленных машинах. Вероятно, нужно будет сохранять их для каждого подключения.

Вариант с RUNAS мне вообще не нравится.

Нет, это окно подтверждения элевации UAC.

Я запускал скрипты при помощи PSEXEC, и не испытывал явных неудобств, при таком подходе вводить пароль необязательно, а можно указать в явном виде аргументом.
Единственное, в этом случае он будет виден в явном виде, это наверное, не так хорошо

Подключаем сетевой диск, скачиваем программу, отключаем диск, устанавливаем программу
вот только на установку нужны администраторские права.
поэтому через runas пытался установить под Администратором, но пароль не получается подсунуть.

Пытался сейчас через планировщик подсунуть выполнение своего батника, но..

Ошибка: Отказано в доступе

Добавлено через 2 минуты
v_svitere,

При таком подходе SCHTASKS должен запускаться с правами администратора
По гибридному варианту с VBS я вам ничего не подскажу, по VBS знаний нет.

Я правильно понимаю, что запуск скрипта должен быть с одного ПК на другие удаленные?

Нет, батник будет запускаться напрямую с каждого компьютера, где необходимо обновить программу.

Добавлено через 5 минут
v_svitere,

Так себе вариант. Врядли так теперь вообще кто-то делает, с учетом того, что теперь столько средств для удаленного запуска скриптов

В любом случае, я бы предложил вам уйти от решения на BAT, а реализовать, например через powershell.
Написать один общий на всех скрипт, в котором можно часть кода (установка программы) запустить в контексте пользователя «Администратор», в powershell это можно сделать при помощи командлета start-process и ключом -Runas, которому можно передать credential в неинтерактивном режиме.

Утилита из Sysinternals — стороннее ПО

Добавлено через 14 минут

Или загибридить BAT и POSH, если нужен именно BAT-файл

Добавлено через 4 минуты
Phil,

Можете прокомментировать, если Вас не затруднит, что делает каждая строка

Добавлено через 3 минуты
v_svitere, и ссылку дать на какой-нибудь пример скрипта из powershell похожего на выполнение моей задачи, попробую разобраться,

Просто этот скрипт ещё надо будет запустить и т.д.

Пока единственный вариант всё это провернуть, который мне кажется самым возможным.

Все пользователи 1с заходят со своих портативных ноутбуков в 1с и запускают внутреннюю обработку,
в ней сидит bat файл, он сохраняется на рабочий стол, 1с закрывается, файл запускается.
Как-то так,на большее фантазии не хватило)

Здесь, средствами CMD запускается powershell. Создается ScriptBlock(Набор команд Powershell).

Конвертируем пароль в защищенную строку.
Создаем объект Credential (Аутентификационные данные)
Запускаем процесс установки, с ключом -Runas , которому передаем ранее созданный объект

Добавлено через 13 минут
Phil,

Ранее предложенный вариант, вас устраивает.

Наверное, момент с Bat-файлом вы можете опустить, сразу сформировав powershell-скрипт (PS1-файл)
Переписываете вот эту часть на powershell
Подключаем сетевой диск, скачиваем программу, отключаем диск
А установку программы делаете как я вам показал в предыдущем посте, через start-process -runas

Phil, А это вы какой код запускали?

Сохраните вот этот код как BAT-файл

Поменяйте учетные данные и путь к EXE-файлу
Попробуйте запустить

Посмотрите с какими правами запустился EXE-файл

это походу на моё ругается.

v_svitere, да сейчас попробую, я просто кусок воткнул который был до этого рабочий в ваш Код.

Добавлено через 50 секунд

v_svitere,
Пишет неверный логин или пароль, но логин и пароль верные

Добавлено через 11 минут

Phil,
Вы уверены? Потому что, Powershell-код точно рабочий, я никогда ничего не скидывают, предварительно не проверив у себя.

Попробуйте открыть powershell и ввести команды

В процессе выполнения у вас запросятся данные введите их.
Далее должен открыться блокнот под введенным пользователем

v_svitere, ввожу рабочий логин пароль, не подключается.
Домена нет
Вошел..учетная запись отличается от имени пользователя, под которым подключаюсь

Добавлено через 11 минут
Теперь не верно задано имя файла или папки, как? я копирую его из имени объекта, где полный windows путь прописан.

v_svitere, из PowerShell запускается

Добавлено через 4 минуты

Заказываю контрольные, курсовые, дипломные и любые другие студенческие работы здесь.

Не сохраняет файлы не под админом
Здравствуйте. Поставил FreePascal на XP с правами админа. В этой же системе от пользователя с.

Как создать ехе под файл bat?
Поскажите пожалуйста как создать ехешник под файлы bat, для запуска например с флешки

запуск приложения не под админом невозможен
Добрый день. Поставил приложение на сервер 2012. я его установил и оно работает нормальнопод.

https работает только под админом
Https работает только под админом. Браузер ie8. Пробовал другие установить, но не запускаются.

Windows 2000 не пускает под админом
Есть windows 2000 Есть 3 пользователя: 1)гость, 2)ht1, 3) администратор. Если входить под «ht1» -.

Источник

Automatically running a batch file as an administrator

How do I run a batch file from another batch file with administrator rights?

I have tried the RUNAS command, but it requires the administrator password.

I am searching for an alternative for running a batch file by right clicking on it and running as an administrator. I want to automate it from another batch file.

7 Answers 7

Create a shortcut to that batch file

Right click on that shortcut file and choose Properties

Click the Advanced button to find a checkbox for running as administrator

Check the screenshot below

Put each line in cmd or all of theme in the batch file:

it works fine for me.

You can use PowerShell to run b.bat as administrator from a.bat :

It will prompt the user with a confirmation dialog. The user chooses YES , and then b.bat will be run as administrator.

It will ask for the password the first time only. It will not ask for password again, unless the password is changed, etc.

Runas.exe won’t work here. You can use VBScript to invoke the «Run as Administrator» shell verb. The Elevation Powertoys contain a batchfile that allows you to invoke an elevated command:

If you’re trying to invoke a Windows UAC prompt (the one that puts the whole screen black and asks if you’re granting administrator privileges to the following task), RUNAS is not the smoothest way to do it, since:

  1. You’re not going to get prompted for UAC authorization, even if logged in as the administrator and
  2. RUNAS expects that you have the administrator password, even if your user is setup as a local administrator, in which case the former password is not a sound security practice, specially in work environments.

Instead, try to copy & paste the following code to ensure that your batch file runs with administrator privileges:

This solution works 100% under Windows 7, 8.1 and 10 setups with UAC enabled.

Источник

Is it possible to automatically run a batch file as administrator

I am wondering whether it is possible to automatically open a batch file as admin when you double-click on the batch file, because the commands need to be run with administrative rights.

Note: I already know about the solution of right-clicking on the file and clicking on Run As Administrator , but this is not an automatic solution.

9 Answers 9

Yes, you’re able to run a batch file with administrative rights. Unfortunately, you can’t do this directly from the batch file it self. You would need to first create a shortcut of that batch file and change the properties for that shortcut in order to make this work.

To create a shortcut, there are many ways but the simplest and the fastest way is by using the Send to option in the context menu.

Of course you can send the shortcut to where ever you would like. To elevate the batch file to run as admin, follow the steps below:

  1. Right-click the shortcut you just created (should be on the desktop or where ever you send it)
  2. Under the Shortcut tab, click the Advanced. button.
  3. Check the Run as administrator checkbox and press OK to both the modal window and the main properties window.
  4. Run the shortcut by double-clicking it and the batch file should run as administrator.

1″ == «» start %USERPROFILE%\Desktop\Shortcut.lnk && GOTO :EOF right below @echo off , and make the shortcut link to program.bat a instead of just program.bat . – trlkly Jul 28 ’14 at 5:20

As posted in an answer by Ben Gripka to another question:

Create a shortcut to that Batch file

Right-click the shortcut file

Click advance button to find a checkbox for running as administrator

Check the screenshot below

The accepted answer does indeed work. But I found that in Windows 7, I had to endure the UAC dialog each time the shortcut is clicked. This IMHO detracts significantly from the «automatically» in this question!

Then I found that in my own situation, the .bat file in question is to be run by Task Scheduler. In this case, checking the Run with highest privileges option on the General tab of the task, nicely takes care of the problem. The .bat is then run as administrator without any hassles.

PS: I didn’t realize I couldn’t upload images on this answer, ’cause I have a nice little screenshot sitting right with me now! Or can I?

You can use my script Batch_Admin to automatically elevate the Administrator for use in any type of Batch own script, or BAT or .CMD. This function ensures the work on a standard environment, with standard tools and in the same way in different Windows systems. It uses several standard and built-in Windows commands. Do not use any other external scripts. It can be used to call any program as Administrator, not just scripts Batch. It suffices to create a small script, which then call the program that requires permission Administartor. Place this in any search PATH folder (from %PATH%).

To use it, you simply insert the following line (exactly as) in its parent Batch script, which is to be run as Administrator. This is best done at the top of our parent script and it is best that first, which will be called via the CALL further, some sub-scripts (see detailed explanation below).

This can be inserted inside any child scripts, called by CALL syntax. To display a message while it is still does not have Administrator privileges, eg. for 5 seconds before calling Batch_Admin set the variable «ShowAdminInfo» on the number of seconds

So how it works:

• Calls UAC.ShellExecute through VBScript to pick up user permissions

• Batch runs the script, or BAT or CMD

• Script caller can have a long name spaces included in the call in quotes

• Give back all the parameters call the master script passed from the command line, as if there was no transmission of the call and start something from scratch, also with special characters, like exclamation marks (!) and percentage (%), and also with parentheses ()

• Holds a master script location if the call took place in the directory where this script is the master

• Auxiliary displays a message if we set before ourselves the variable «ShowAdminInfo», eg. for 5 seconds which can prevent the immediate passage of the rights of the Administrator giving additional information and the possibility of an informed decision. Examples of setting that must be set: SET ShowAdminInfo=5 By default, because this variable is not defined, it does not display.

• The script is calling also in the system search path % PATH% and from network resource, such as: \Computer\share\test.bat

• Prevents misunderstandings in writing the necessary auxiliary files when the script calls several Batch_Admin almost at the same time. It uses the random number from 1 to 100

• But, the best is to use it on parent script. The transition to Administrator rights always requires that you run the script completely again, in a new window, in a new environment, without recourse to the the variables are set previously in our script and values of these variables did not pass then to call as Administrator. Just the script will be executed again.

Below a complete script Batch_Admin. Extended information about this is on my site.

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

  • Windows ruby on rails установка windows
  • Windows rt запуск десктопных приложений
  • Windows rt surface характеристики
  • Windows rsat windows 10 1703
  • Windows rsat windows 7 sp1