Есть ли команда «sudo» для Windows?
Я всегда работаю над учетной записью, отличной от администратора, на моем компьютере под управлением Windows. Иногда мне нужно установить программы, требующие доступа администратора. Поскольку в основном я использую командную строку Windows, есть ли команда Windows для эскалации привилегий, аналогичная команде терминала Linux sudo ?
14 ответов
для запуска командной оболочки в качестве администратора
Я обнаружил поднять сегодня, когда «выполняет команду с повышением привилегий UAC. Это полезно для работы внутри командной строки или с пакетными файлами. » Это не то же самое, что sudo , он меняет исполняющего пользователя на Администратора, но его синтаксис намного проще использовать, чем runas , и он может поддерживать текущий каталог, позволяя использовать относительные пути.
Цель Elevate — не работать или обходить UAC (User Account Control), а работать с ним. Пока UAC включен, имеет , чтобы быть каким-то приглашением в some в процессе. Если вам нужно полностью избавиться от запроса, вы должны отключить UAC .
Устранение болевых точек повышает эскалацию определенного процесса из непривилегированной оболочки, а затем продолжается как обычно. Без этого вам нужно запустить привилегированное командное приглашение с помощью правой кнопкой мыши> «Запуск от имени администратора» , который не может быть легко написан сценарием, прежде чем пытаться выполнить привилегированную команду.
Вы можете использовать команду runas , которая является похожей, или вы можете проверить sudo для Windows над SourceForge , который добавляет команду sudo.
Предположим, у вас есть два пользователя. Боб — обычный пользователь, а Джеймс — администратор.
Если вы входите в систему как Bob и используете «runas james acommand», команда запускается так, как если бы ее запускал Джеймс, поэтому он обращается к пользовательским настройкам Джеймса, и любые изменения пользователя переходят в James My Documents & папок настроек и т. д. Поэтому, если вы устанавливаете приложение, скажем, оно будет установлено как Джеймс, а не как Боб.
Если, с другой стороны, Боб делает «sudo acommand», команда все еще выполняется как Bob, но с повышенными разрешениями — точно так же, как команда sudo для Linux. Чтобы пользователь не мог судиться, вы должны определить группу пользователей sudoers, которая содержит список обычных пользователей, у которых есть разрешение на повышение с помощью sudo. Пользователям по-прежнему необходимо предоставить учетные данные перед повышением.
Иногда разница не важна, иногда это так, и я считаю, что обе команды могут быть полезны.
Если вы готовы перейти на альтернативные консоли, ConEmu (я автор). Одна из его функций — возможность запускать как увеличенные, так и невыполненные вкладки в одном окне ConEmu. Вкладки могут запускаться с разными учетными данными.
Для удобства пользователя существует пакетный файл csudo.cmd (который может быть легко принят в bash). Прочтите полное описание в вики проекта . Вкратце, когда вы запускаете какую-либо команду из существующей вкладки с невыполнением, например
ConEmu запустит dism на новой повышенной консоли /вкладке (с предыдущим приглашением UAC в окне Vista или Login в XP).
По умолчанию csudo запускает новую консоль в расколе (могут быть изменения с помощью редактирования содержимого csudo.cmd ).
И, конечно, вы можете переименовать его в sudo.cmd , если вам нравится слово «classic» sudo .
Быстрый метод:
Три шага для добавления sudo.
Скопируйте следующий скрипт (Ctrl + C) и вставьте его в PowerShell (Alt + Space + E + P):
Он будет постоянно включать команду sudo в PowerShell.
Использование:
Длинный метод обучения:
- Прочитайте эту статью .
- Прочитайте комментарии.
- Взгляните на хранилище git репозитория Стивена и файл readme .
Примечание. Я смешал сценарий из обеих статей, чтобы создать вышеупомянутый скрипт. Скорее вручную вставив скрипт в блокнот, я добавил операторы Out-File для сохранения файлов ps1 и $profile из сценария.
Совет. Если вы не очень любите всплывающие окна UAC (например, я), сохраните следующее в файле * .reg и запустите его:
Если вы делаете это в Windows, то в дополнение к команде Run As, как упоминалось в нескольких других ответах, есть также способы сделать это с помощью мыши.
Если вы удерживаете клавишу Shift при щелчке правой кнопкой мыши по большинству исполняемых файлов в Windows, вы должны заметить еще несколько дополнительных опций. Один из них — это опция Run As. «(я думаю, что она называется« Run As Administrator »из Vista).
Вы также можете загрузить более продвинутую версию RunAs от Microsoft, называемую ShellRunAs , это улучшает встроенную команду RunAs, как в командной строке, так и в графическом режиме, в том числе позволяет вам сохранять учетные данные учетной записи
Surun — это бесплатное приложение с открытым исходным кодом, которое позволяет определенным программам работать с правами администратора, без предоставления пароля без изменения реестра пользователя или изменения переменных среды.
Когда я пользовался Windows XP, это приложение мне очень помогает. Beta работает под Windows 7.
Как вы, вероятно, обнаружили, runas позволит вам запускаться как другой пользователь, но он не может выполнять возвышение и не передает текущие каталоги, переменные окружения или длинные командные строки.
оболочка Hamilton C разрешает это с подлинным su и sudo. su позволяет запускать команду в качестве другого пользователя; sudo (на самом деле псевдоним su) позволяет вам выполнить команду повышенной. Вы также можете сделать то и другое, работая под повышенным уровнем как другой пользователь. Текущие каталоги, переменные окружения и длинные командные строки передаются посредством рукопожатия с общей памятью между su, выполняющимся в контексте вызывающего абонента, и копией самой работы, выполняемой как интерлюдия, с новыми учетными данными, которые затем запускают дочерние элементы. Полное раскрытие: я автор.
Этот скрипт выполняет задание:
Сохраните его как sudo.cmd , затем добавьте его в свой PATH
Примечание: runas означает в этом контексте «Запуск от имени администратора», а не «Запуск от имени другого пользователя»
взяты здесь и слегка отредактирован, чтобы удалить заголовок cscript.exe из вывода
Самое простое решение, на мой взгляд, заключается в том, чтобы использовать powershell для работы, которая является переносной и будет запрашивать пользователя с использованием UAC.
Вы можете просто запустить это в любой оболочке (cmd или powershell)
Замените рабочую замену sudo для терминала Cygwin mintty , чтобы поместить следующий скрипт в PATH пользователя:
Для меня это единственная жизнеспособная замена для повышения привилегий таких программ, как vim или cygrunsrv во время работы в терминале в Windows.
Следующий скрипт vbs делает трюк для меня. Я положил его на C:\Windows\System32
Пример использования в командной строке sudo net start service
Для него есть шоколадный пакет с удобным названием sudo . Вы можете установить пакет с шоколадным с помощью этой команды:
Затем в любой оболочке Windows /MS, которую вы должны использовать, вы можете использовать sudo , как ожидалось.
5 Windows Alternatives to the Linux sudo Command
In other words, pseudo sudo commands
If you’ve ever used Linux or know someone who uses Linux, then you’ve probably heard of the sudo command. The command is a critical component to just about every Linux distribution and what it does is let you run a command as a different user, most notably the root user. On certain Linux distributions, you can log in as the root user by using the su command, but this is considered highly risky and no one ever does it.
Actually, it’s so dangerous that it’s disabled by default on Linux distributions like Ubuntu. Instead, you have to use the sudo command if you want to run a command as the root user. So what about Windows? Well, unfortunately, most people are logged into Windows as Administrators, which is the same as root user in Linux. However, Microsoft has tried to lessen the dangerous effects of being logged in as an Administrator by enabling User Account Control or UAC.
That way, even if the user has Administrative privileges, applications running under that account will not inherit those privileges unless it’s manually authorized by the user. This helps prevent malware and spyware from infecting a Windows user who is logged in as an Administrator.
So while Linux users have the sudo command, what do Windows user have? Are there alternatives that Windows users can use to run commands with elevated privileges? Is there a sudo command for Windows? In this article, I’ll talk about five alternatives to the sudo command for Windows users.
Note: Some of these tools are quite old now, so they may or may not work with the latest versions of Windows.
Windows Runas Command
Windows has the runas command, which is the direct counterpart to sudo on Linux. Using the runas command, you can execute a script, program or command as a different user or as an administrator. The full syntax for the runas command is:
If you wanted to open an administrative command prompt, you could type the following:
/noprofile will not load the current user profile. You can remove that if you need access to the user environment variables. If you wanted to open a text file using Notepad with administrator privileges, you could use this command:
You can checkout the Technet page on runas for more information on how to use it.
Note that when using runas command, if you install a program or make changes to settings, etc., the changes will be made to the user account that you are running the command on. For example, let’s say you have user X who is a normal user and user Y, who is an administrator. If you log into X and then do a runas using the Administrator credentials, changes will be made to the Administrator’s settings, not user X.
So if you install an application by right-clicking on the EXE file and choosing Run as Administrator, it’ll get installed to the built-in Administrator user profile, not the one you are logged into. If you want true elevated privileges like sudo without the profile issues, check out the next alternative below.
Sudo for Windows – Sourceforge
Sudo for Windows is a free program you can install that will give you the same experience of the sudo command on Linux for Windows. The only difference is that Sudo for Windows “preserves the user’s profile and ownership of created objects” as stated by the developer. This is really handy if you like to use elevated permissions for installing apps or making changes to user locations like My Documents, etc.
It’ll give you Administrative privileges, but will keep all the changes in the current profile instead of the account you’re using to run the command with. The program requires .NET version 2.0, which you can’t download individually. In order to get 2.0, you have to install .NET Framework 3.5, which include 2.0.
Once you install Sudo for Windows, you need to add the user accounts that you to allow to have elevated privileges to a specific group created by the program called Sudoers. Right-click on My Computer or This PC and click on Manage. Then expand Users and Groups and click on Groups. You should see one called Sudoers.
Double-click on Sudoers and click on the Add button.
On the next dialog, click the Advanced button and then click Find Now. This will list out all users and groups on the system. Double-click the user you want to add.
Repeat this step for however many users you want to add. Then click OK and you should see the members listed in the Members listbox shown above. Click OK and now you should be able to use the sudo GUI and command. If you right-click on a program, you’ll see the Sudo option.
You can also open a command prompt and type sudo to run command with elevated permissions.
Overall, it’s pretty nifty and works very well. However, note that this particular program is really useful for launching programs or processes either via right-click or via the command prompt, but it’s not meant for running command line apps. For example, if you wanted to do sudo mkdir “c:\Program Files\new”, this won’t work using Sudo for Windows. For that functionality, there is another program called the same thing, but by a different developer. Read below.
Sudo for Windows – Luke Sampson
There’s another developer who wrote another Sudo for Windows that lets you execute command line apps too. So let’s go back to the example about creating a new folder in C:\Program Files. You can’t really do this by default.
Above I’m using PowerShell, but you’ll get the same error using the command prompt also. However, once you install Sudo for Windows, just add the word sudo to the front of the command and it works perfectly with no errors!
To install it, you need to open PowerShell and then type in the following commands in order:
If everything works OK, you should see the following output in PowerShell after each command:
That’s it! Now you can start typing in commands and adding sudo in front. The only annoying thing about this program is that the UAC window still pops up and you have click Yes for it to work. Even with that slight annoyance, the benefits are well worth it.
Elevate
Elevate is a program that works with UAC and doesn’t work exactly like sudo. With Elevate, it will change the executing user to Administrator like the runas command does. However, it’s useful for working in the command line or with batch files.
The main purpose of elevate is not to get around UAC, but to start a process in an elevated state from a non-elevated shell and then continuing on as normal even after the command has completed. Elevate is useful for scripting because you don’t have to worry about trying to script the whole right-clicking and running a command prompt as Administrator process.
Elevation PowerToys for Windows
For those of you who do a lot of work on the command line or work with scripts and batch files, then the Elevation PowerToys for Windows page has quite a few useful tools and scripts.
The script elevation power toys were created to overcome the frustrating aspects of UAC when trying to elevate a program from the command line or running scripts as administrators.
Hopefully, that’s enough tools and programs for you to make you feel like you’re actually using sudo on Windows. There’s no perfect replacement for it, but there are quite a few options that come close. If you use something else to elevate programs, commands or scripts in Windows, let us know in the comments. Enjoy!
Founder of Help Desk Geek and managing editor. He began blogging in 2007 and quit his job in 2010 to blog full-time. He has over 15 years of industry experience in IT and holds several technical certifications. Read Aseem’s Full Bio