I'm executing the following command to stop a service on a remote server from within a stored procedure in SQL Server.

-- Stop Service
SET @Command = 'sc \\' + @Server + ' stop ' + @ServiceName;
EXEC master.dbo.xp_cmdshell @Command;

Depending on the service sometimes this executes successfully but other times I receive the following error:

[SC] OpenService FAILED 5:
Access is denied.

Im curious what user executes the command. Is it the user I login/connect with to the database? Or is it the user Im logged onto the physical server with? Can I pass in different authentication with the xp_cmdshell?

  • 3
    You can see who it's running as via EXEC sys.xp_cmdshell 'whoami'; Apr 30, 2016 at 1:12
  • Also, does sometimes mean sometimes on the same server, or does sometimes really mean on some servers? Apr 30, 2016 at 1:43
  • @AaronBertrand - in all scenarios the service is running on a different server, and both instances the remote service was run as 'Local System'. However on one of the servers, the user ID that was running SQL Server was also an admin on the remote server. So I believe _tpet was correct. May 2, 2016 at 14:48

1 Answer 1


From xp_cmdshell (Transact-SQL) in the product documentation:

The Windows process spawned by xp_cmdshell has the same security rights as the SQL Server service account.

When it is called by a user that is not a member of the sysadmin fixed server role, xp_cmdshell connects to Windows by using the account name and password stored in the credential named ##xp_cmdshell_proxy_account##. If this proxy credential does not exist, xp_cmdshell will fail.

See the full entry for the steps you need to take to set up the xp_cmdshell proxy account.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.