Как использовать sudo в windows

Open notepad and paste this code:

@echo off
powershell -Command "Start-Process cmd -Verb RunAs -ArgumentList '/c cd /d %CD% && %*'"
@echo on

Then, save the file as sudo.cmd. Copy this file and paste it at C:\Windows\System32 or add the path where sudo.cmd is to your PATH Environment Variable.

When you open command prompt, you can now run something like sudo start ..

If you want the admin command prompt window to stay open when you run the command, change the code in notepad to this:

@echo off
powershell -Command "Start-Process cmd -Verb RunAs -ArgumentList '/k cd /d %CD% && %*'"
@echo on

Explanation:

powershell -Command runs a powershell command.

Start-Process is a powershell command that starts a process, in this case, command prompt.

-Verb RunAs runs the command as admin.

-Argument-List runs the command with arguments.

Our arguments are '/c cd /d %CD% && %*'. %* means all arguments, so if you did sudo foo bar, it would run in command prompt foo bar because the parameters are foo and bar, and %* returns foo bar. cd /d %CD% is a command to go to the current directory. This will ensure that when you open the elevated window, the directory will be the same as the normal window. the && means that if the first command is successful, run the second command.

The /c is a cmd parameter for closing the window after the command is finished, and the /k is a cmd parameter for keeping the window open.

Credit to Adam Plocher for the staying in the current directory code.

Open notepad and paste this code:

@echo off
powershell -Command "Start-Process cmd -Verb RunAs -ArgumentList '/c cd /d %CD% && %*'"
@echo on

Then, save the file as sudo.cmd. Copy this file and paste it at C:\Windows\System32 or add the path where sudo.cmd is to your PATH Environment Variable.

When you open command prompt, you can now run something like sudo start ..

If you want the admin command prompt window to stay open when you run the command, change the code in notepad to this:

@echo off
powershell -Command "Start-Process cmd -Verb RunAs -ArgumentList '/k cd /d %CD% && %*'"
@echo on

Explanation:

powershell -Command runs a powershell command.

Start-Process is a powershell command that starts a process, in this case, command prompt.

-Verb RunAs runs the command as admin.

-Argument-List runs the command with arguments.

Our arguments are '/c cd /d %CD% && %*'. %* means all arguments, so if you did sudo foo bar, it would run in command prompt foo bar because the parameters are foo and bar, and %* returns foo bar. cd /d %CD% is a command to go to the current directory. This will ensure that when you open the elevated window, the directory will be the same as the normal window. the && means that if the first command is successful, run the second command.

The /c is a cmd parameter for closing the window after the command is finished, and the /k is a cmd parameter for keeping the window open.

Credit to Adam Plocher for the staying in the current directory code.

I always work on a non-administrator account on my Windows computer. Sometimes I need to install programs which requires administrator access. As I mostly use the Windows command prompt, is there a Windows command to escalate privileges, similar to the Linux terminal command sudo?

Paul's user avatar

Paul

4,76429 silver badges41 bronze badges

asked Sep 17, 2009 at 9:24

ukanth's user avatar

5

The runas command.

runas [{/profile|/noprofile}] [/env] [/netonly] [/smartcard] [/showtrustlevels] [/trustlevel] /user:UserAccountName program

Just run:

runas /noprofile /user:Administrator cmd 

to start a command shell as a administrator

patricktokeeffe's user avatar

answered Sep 17, 2009 at 9:29

Davy Landman's user avatar

Davy LandmanDavy Landman

4,5121 gold badge20 silver badges10 bronze badges

15

Elevate«executes a command with UAC privilege elevation. This is useful for working inside command prompts or with batch files.» It’s not the same as sudo, it changes the executing user to Administrator, but its syntax is a lot more straightforward to use than runas, and it can keep the current directory, enabling the use of relative paths.

Synopsis:
  elevate [(-c | -k) [-n] [-u]] [-w] command

Options:
  -c  Launches a terminating command processor; equivalent to "cmd /c command".
  -k  Launches a persistent command processor; equivalent to "cmd /k command".
  -n  When using -c or -k, do not pushd the current directory before execution.
  -u  When using -c or -k, use Unicode; equivalent to "cmd /u".
  -w  Waits for termination; equivalent to "start /wait command".

Elevate’s purpose isn’t to work around or bypass UAC (User Account Control), but to work with it. As long as UAC is enabled there has to be some kind of prompt at some point in the process. If you need to get rid of prompting altogether you have to disable UAC.

The pain point Elevate alleviates is escalating a particular process from a non-privileged shell and then carrying on as normal. Without this you need to start a privileged command prompt with right-click > «Run as Administrator» before attempting the privileged command, which can’t be easily scripted.

This works well with «Elevate without prompting» in secpol.msc. Together, they do the same as %wheel ALL=(ALL) NOPASSWD: ALL in sudo

A known limitation is that it does not return the error code from the program it is elevating.

If your muscle memory is stuck on sudo, create an alias using Doskey:
doskey sudo=elevate -w

or batchfile in PATH:
@elevate -w %*

Elevate is 3rd party tool written by Johannes Passing. It’s an 11kb download and portable (no install needed): http://code.kliu.org/misc/elevate/

answered Apr 12, 2011 at 6:42

matt wilkie's user avatar

matt wilkiematt wilkie

5,03523 gold badges58 silver badges85 bronze badges

18

You can use the runas command which is kind of similar, or you can check out the sudo for Windows project over at SourceForge which adds a sudo command.

The difference is subtle:

Let’s say you have two users. Bob is a normal user and James is an administrator.

If you log in as Bob and use «runas james acommand» the command is run as if it was run by James, so it accesses James’ user settings and any user changes go into James My Documents & settings folders, etc. So if you are installing an application, say, it will be installed as James, not as Bob.

If on the other hand Bob does «sudo acommand» the command is still run as Bob, but with elevated permissions — just like the Linux sudo command. To prevent any user from being able to sudo you have to define a sudoers user group that contains the list of the normal users that have permission to elevate using sudo. The users still have to provide credentials before elevation.

Sometimes the difference isn’t important, sometimes it is, and I find that both commands can be useful.

Peter Mortensen's user avatar

answered Sep 17, 2009 at 9:28

Simon P Stevens's user avatar

Simon P StevensSimon P Stevens

5,1831 gold badge28 silver badges36 bronze badges

5

Vinayak's user avatar

Vinayak

10.6k10 gold badges54 silver badges89 bronze badges

answered Sep 17, 2009 at 13:11

DDM's user avatar

DDMDDM

5493 silver badges6 bronze badges

12

If you are ready to switch to alternative consoles, there is ConEmu (I’m the author). One of its features — the ability to run both elevated and non-elevated tabs in the one ConEmu window. Tabs may be started with different credentials too.

For user comfort, there is batch-file csudo.cmd (which may be easily adopted to bash). Read full description in project’s wiki. In brief, when you run some command from existing non-elevated tab, for example

csudo dism /online /enable-feature /featurename:NetFX3 /All /Source:D:\sources\sxs /LimitAccess

ConEmu will starts dism in the new elevated console/tab (with preceding UAC prompt in Vista or Login box in XP).

By default csudo starts new console in a split (may be changes via editing of csudo.cmd contents).

And of course you may rename it to sudo.cmd if you like «classic» sudo word.

sudo in ConEmu/Windows

answered Oct 26, 2012 at 7:52

Maximus's user avatar

MaximusMaximus

20.6k16 gold badges91 silver badges116 bronze badges

4

Quick method:

Three steps to add sudo.

  1. Open PowerShell.

  2. Copy the following script (Ctrl+C) and paste it in PowerShell (Alt+Space+E+P):

$script_path="$HOME\Documents\Scripts"; if (!(test-path $script_path)) {New-Item -ItemType directory $script_path} if (!(test-path $profile)) { new-item -path $profile -itemtype file -force }". $script_path\sudo.ps1" | Out-File $profile -append; "function sudo(){if (`$args.Length -eq 1){start-process `$args[0] -verb `"runAs`"} if (`$args.Length -gt 1){start-process `$args[0] -ArgumentList `$args[1..`$args.Length] -verb `"runAs`"}}" | Out-File $script_path\sudo.ps1; powershell
  1. Hit Enter.

It will permanently enable sudo command in PowerShell.

Usage:

sudo <process-name> [param1 [param2 [param3]]]

Examples:

sudo explorer
sudo notepad
sudo powershell
sudo cmd
sudo taskmgr
sudo tasklist
sudo taskkill /IM Skype.exe /PID 8496

Long method for learning:

  • Read this article.
  • Read the comments.
  • Take a look at Stephen’s git repository and the readme file.

Note: I mixed the script from both articles to create the aforementioned script. Rather manually pasting the script in notepad I added the Out-File statements to save ps1 and $profile files from the script.

Tip: If you are not a very big fan of UAC popups (like me), save the following in *.reg file and run it:

Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System]
"ConsentPromptBehaviorAdmin"=dword:00000000

phuclv's user avatar

phuclv

26.7k15 gold badges115 silver badges235 bronze badges

answered Aug 28, 2012 at 10:36

vulcan raven's user avatar

6

If you’re doing this on Windows, then in addition to the Run As command as mentioned in a couple of other answers, there are also ways to do this with the mouse.

If you hold down the Shift key as you right-click on most executable files in Windows you should notice a few more advanced options. One of these is the «Run As...» option (I think it’s called «Run As Administrator» from Vista onwards).

You can also download a more advanced version of RunAs from Microsoft, called ShellRunAs, this has enhancements over the built-in RunAs command, both in command line and graphical modes, including letting you save account credentials

answered Sep 17, 2009 at 11:22

GAThrawn's user avatar

GAThrawnGAThrawn

4,3362 gold badges22 silver badges42 bronze badges

3

I wrote gsudo, a sudo for windows that feels like *nix sudo and has a few killer features:

  • Run within the current console (attached) without breaking tab-key auto-complete. Or add -n to launch in a new window.
  • Handles all scenarios reliably to be used on scripts. (ExitCodes, StdIn/Out/Err Redirection/Capture)
  • Supports Cmd/PowerShell/PowerShell Core
  • Credentials cache: If gsudo is invoked several times within minutes it only shows the UAC pop-up once.

gsudo demo

Usage

gsudo Opens an elevated shell in the current console.

gsudo [options] {command} [arguments]
Executes the specified command with elevated permissions.

Most relevant [options]:

  • -n | --new Starts the command in a new console with elevated rights (and returns immediately).
  • -w | --wait Force wait for the process to end (and return the exitcode).
  • -s | --system Run As Local System account («NT AUTHORITY\SYSTEM»).

Installation

  • Using Scoop: scoop install gsudo
  • Using Chocolatey: choco install gsudo
  • Using Winget: winget install gsudo
  • Or check the docs and latest release

answered Nov 7, 2019 at 16:12

Gerardo Grignoli's user avatar

2

Surun is free, open-source application that allows certain programs to run with administrative rights, without providing a password without changing the user registry or modify environment variables.

When I was using Windows XP this app helps me a lot. Beta works under Windows 7.

answered Nov 17, 2011 at 15:24

diimdeep's user avatar

diimdeepdiimdeep

8122 gold badges9 silver badges15 bronze badges

2

The simplest solution in my view is to leverage powershell to do the work, which is portable and will prompt the user using the UAC.

You can just run this in any shell (cmd or powershell)

powershell Start-Process -verb runAs path-to-your.exe "-all -args -in -quotes"

answered Nov 20, 2017 at 19:58

twall's user avatar

twalltwall

2733 silver badges10 bronze badges

There is a chocolatey package for it with the convenient name sudo. You can install the package with chocolatey using this command:

choco install -y sudo

Then in whatever Windows/MS shell you have to use, you can use sudo as expected.

answered Jun 14, 2018 at 18:44

ypid's user avatar

ypidypid

3432 silver badges6 bronze badges

1

As you’ve probably discovered, runas will let you run as another user but it cannot do elevation and it doesn’t pass current directories, environment variables or long command lines.

Hamilton C shell solves that with a genuine su and sudo. su lets you run a command as another user; sudo (actually an alias to su) lets you run a command elevated. You can also do both, running elevated as a different user. Current directories, environment variables and long command lines are passed by way of a shared memory handshake between su running in the caller’s context and a copy of itself running as an interlude with the new credentials that then starts the child. Full disclosure: I’m the author.

Destroy666's user avatar

Destroy666

5,6248 gold badges16 silver badges36 bronze badges

answered Sep 6, 2012 at 15:01

Nicole Hamilton's user avatar

Nicole HamiltonNicole Hamilton

9,9451 gold badge22 silver badges43 bronze badges

A while ago I created wsudo, an open-source sudo-like CLI tool for Windows to run programs or commands with elevated rights, in the context of the current directory. It’s freely available as a Chocolatey package.

I use it a lot for things like configuring build agents, admin stuff like sfc /scannow, dism /online /cleanup-image /restorehealth or simply for installing/updating my local Chocolatey packages (e.g., wasudo cup all -y). Use at your own risk.

Installation

choco install wsudo

Chocolatey must be already installed.

Purpose

wsudo is a Linux sudo-like tool for Windows to invoke a program with elevated rights (as Administrator) from a non-admin shell command prompt and keeping its current directory.

This implementation doesn’t depend on the legacy Windows Script Host (CScript). Instead, it uses a helper PowerShell 5.1 script that invokes "Start-Process -Wait -Verb runAs ..." cmdlet. Your system most likely already has PowerShell 5.x installed, otherwise you’ll be offered to install it as a dependency.

Usage

wsudo runs a program or an inline command with elevated rights in the current directory. Examples:

wsudo .\myAdminScript.bat 
wsudox "del C:\Windows\Temp\*.* && pause"
wasudo cup all -y
wasudox start notepad C:\Windows\System32\drivers\etc\hosts 

I often invoke it from the Windows Run box (Win+R), or by typing wasudo Enter in the Windows Explorer address bar (Alt+D). The latter opens an admin command prompt in the Explorer’s current folder.

For more details, visit the GitHub repro.

A working sudo replacement for Cygwin’s mintty terminal would be to place the following script in user’s PATH:

$!/bin/bash
cygstart --action=runas mintty -e `which bash` -lc \"$@\"

For me this is the only viable replacement to elevate privileges of programs like vim or cygrunsrv while working in a terminal on Windows.

answered Nov 26, 2014 at 9:45

karafior's user avatar

This script does the job:

@echo Set objShell = CreateObject("Shell.Application") > %temp%\sudo.tmp.vbs
@echo args = Right("%*", (Len("%*") - Len("%1"))) >> %temp%\sudo.tmp.vbs
@echo objShell.ShellExecute "%1", args, "", "runas" >> %temp%\sudo.tmp.vbs
@cscript //NoLogo %temp%\sudo.tmp.vbs

Save it as sudo.cmd then add it to your PATH

Note: the runas means in this context «Run as administrator» and not «Run as other user»

Taken from here and slightly edited to remove cscript.exe header from output

answered Jan 10, 2016 at 21:08

Charles Milette's user avatar

3

The following vbs script allows to launch a given command with arguments with elevation and mimics the behavior of the original unix sudo command for a limited set of used cases (it will not cache credentials nor it allows to truly execute commands with different credentials). I put it on C:\Windows\System32.

Set objArgs = WScript.Arguments
exe = objArgs(0)
args = ""
IF objArgs.Count >= 2 Then
   args = args & objArgs(1)
End If
For it = 2 to objArgs.Count - 1
   args = args & " " & objArgs(it)
Next
Set objShell = CreateObject( "WScript.Shell")
windir=objShell.ExpandEnvironmentStrings("%WINDIR%")
Set objShellApp = CreateObject("Shell.Application")
objShellApp.ShellExecute exe, args, "", "runas", 1
set objShellApp = nothing

Example use on a command prompt sudo net start service

answered Feb 1, 2018 at 21:29

ceztko's user avatar

ceztkoceztko

1621 silver badge8 bronze badges

3

Another option is TakeCommand’s START /ELEVATED … switch.

The noninteractive (TCC-RT) version of the suite is offered for free.
The «sudo.btm» batch file would look like

@START "" /ELEVATED %*

which would also support the form sudo /wait <someprogram> /params

answered Mar 25, 2020 at 9:49

AnrDaemon's user avatar

AnrDaemonAnrDaemon

2031 silver badge5 bronze badges

You must log in to answer this question.

Not the answer you’re looking for? Browse other questions tagged

.

Cover image for How to use Sudo in Windows 10 Powershell

Many of us may face a small problem with windows terminal (command line) when going to execute some commands that require an admin privilege while the shell is opened in normal user privilege, so we have to restart the shell using Run As Administrator in order to proceed, whilst in Linux we simply use sudo command to execute whatever we want as a root user.
Here we have solution for this issue in Windows, just follow the following steps:
1- Using PowerShell terminal execute the following command line to install scoop package installer:

C:\>iwr -useb get.scoop.sh | iex

Enter fullscreen mode

Exit fullscreen mode

2- Then after installing «scoop» in your system install «sudo» package:

C:\>scoop install sudo

Enter fullscreen mode

Exit fullscreen mode

Now you will be able to use sudo command same as in Linux, for example in order to install npm package globally we have to run npm install in a privilege mode:

C:\>sudo npm install –g bootstrap

Enter fullscreen mode

Exit fullscreen mode

As well as having a sudo option in Windows, we will have the ability to install packages in Windows using «scoop» similar to apt & apt-get in Linux.
For more information how to use scoop visit :

  1. https://scoop.sh/
  2. https://github.com/lukesampson/scoop/wiki

The ‘sudo’ command is commonly used in Unix-based operating systems, such as Linux and macOS, to run a command with administrative privileges. However, this command is not available in Windows. Therefore, users who are familiar with ‘sudo’ and want to run it on their Windows machine may encounter difficulties.

Method 1: Use ‘Run as administrator’ option

To run a command with elevated privileges on Windows, you can use the «Run as administrator» option. Here are the steps to do it:

  1. Open the Start menu and search for the command prompt or PowerShell.
  2. Right-click on the result and select «Run as administrator».
  3. Enter the command you want to run with elevated privileges, such as sudo command.
  4. Press Enter to execute the command.

Here are some examples of how to use the «Run as administrator» option with different commands:

Example 1: Run a command as administrator

To run a command as an administrator, you can use the runas command with the /user:Administrator option:

runas /user:Administrator "command"

For example, to run the ipconfig command as an administrator, you can use:

runas /user:Administrator "ipconfig"

Example 2: Run PowerShell as administrator

To run PowerShell as an administrator, you can use the «Run as administrator» option as described above. Alternatively, you can open PowerShell and run the following command:

Start-Process powershell -Verb runAs

This will open a new instance of PowerShell with elevated privileges.

Example 3: Run Command Prompt as administrator

To run Command Prompt as an administrator, you can use the «Run as administrator» option as described above. Alternatively, you can open Command Prompt and run the following command:

start cmd.exe /k "cd /d %USERPROFILE%"

This will open a new instance of Command Prompt with elevated privileges and set the working directory to your user profile.

That’s it! Using the «Run as administrator» option is a simple and effective way to run commands with elevated privileges on Windows.

Method 2: Use ‘Windows PowerShell’ with elevated privileges

To run ‘sudo’ command in Windows, you can use ‘Windows PowerShell’ with elevated privileges. Follow these steps to do so:

  1. Press the ‘Windows’ key and type ‘PowerShell’ in the search bar.
  2. Right-click on ‘Windows PowerShell’ and select ‘Run as Administrator’.
  3. Type the command you want to run with elevated privileges, preceded by the command ‘sudo’. For example, if you want to install a package using Chocolatey, you can use the following command:
sudo choco install package-name
  1. Press ‘Enter’ to execute the command. You will be prompted to enter your administrator password.

Here is an example of how to use ‘Windows PowerShell’ with elevated privileges to create a new directory:

sudo New-Item -ItemType Directory -Path "C:\NewDirectory"

In this example, the ‘New-Item’ cmdlet is used to create a new directory. The ‘-ItemType’ parameter specifies the type of item to create, which in this case is a directory. The ‘-Path’ parameter specifies the path where the new directory should be created.

Another example of how to use ‘Windows PowerShell’ with elevated privileges is to stop a Windows service:

sudo Stop-Service -Name ServiceName

In this example, the ‘Stop-Service’ cmdlet is used to stop a Windows service. The ‘-Name’ parameter specifies the name of the service to stop.

By using ‘Windows PowerShell’ with elevated privileges, you can run any command that requires administrator privileges in Windows.

Method 3: Install and use ‘Windows Subsystem for Linux (WSL)’

To run ‘sudo’ command in Windows, you can install and use ‘Windows Subsystem for Linux (WSL)’. Here are the steps to do it:

  1. Enable WSL feature in Windows. Open PowerShell as Administrator and run the following command:

    dism.exe /online /enable-feature /featurename:Microsoft-Windows-Subsystem-Linux /all /norestart
  2. Restart your computer to complete the installation of WSL.

  3. Install a Linux distribution from Microsoft Store. For example, you can install Ubuntu.

  4. Open Ubuntu from Start menu or run ‘ubuntu’ command in PowerShell. This will launch a Linux terminal.

  5. Use ‘sudo’ command in the Linux terminal to execute commands with elevated privileges. For example, you can run the following command to update the package list:

  6. Enter your Linux user password when prompted.

That’s it! You can now use ‘sudo’ command in Windows with WSL. You can also install other Linux distributions and use them with WSL.

Here is an example of using ‘sudo’ command to install a package:

This command will install nginx web server in your Ubuntu installation with elevated privileges.

Note that WSL is not a full Linux distribution and some features may not work as expected. However, it provides a convenient way to run Linux commands and tools in Windows environment.

  • Как использовать python на windows
  • Как использовать ipad в качестве монитора для windows
  • Как искать файл по дате в windows 10
  • Как инициализировать ssd диск в windows 10 для установки windows
  • Как изменить ярлык файла на windows 10 на свой