Execute xp_cmdshell command as specific user

shell, sql-server, t-sql, windows

Solution

Because you're connecting to SQL as a login in the sysadmin group, `xp_cmdshell` runs as the service account.

If you connect as a low-privilege login, then it will use the `xp_cmdshell_proxy_account` instead. So try doing `EXECUTE AS LOGIN='lowprivaccount'` first, to see if that helps.

Of course, what you're actually asking is not the expected use. Expected use is that the high-privilege accounts can allow `xp_cmdshell` to use the Service Account, whereas everyone else has to put up with the lower privilege proxy account.

Problem

I would like to run xp_cmdshell (TSQL procedure) in order to mount a network drive and then access remotes mdb files. I am administrator on the MS SQL server and I have allowed xp_cmdshell execution accordingly. However, there is still a problem: When I call xp_cmdshell, the user executing the command is the SQL SysAdmin, i.e. the account who run SQL Server process. I wish xp_cmdshell executes as the account with which I'm connected to SQL server, i.e Administrator Both of theses account are in administrator group, SQLAdmin group, and are granted to CONTROL SERVER. Both users belong to the same domain. All of this is run on the same machine. Because of this conflict, I cannot use a network drive because it is mounted for SysAdmin and not for Administrator I tried to use sp_ xp_ cmdshell_ proxy_ account to specify the account with which I want to run xp_cmdshell, but SysAdmin is still the used account. Therefore, this code : `select user_name(), suser_name;` `exec xp_cmdshell 'echo %username%';` displays : `Administrator Administrator` `SysAdmin` Does anybody knows how to impersonate well the xp_cmdshell command ? Is there something to (re)configure? Thanks for your help.

Original source