Xp_CmdShell enables us to run cmd commands within T-SQL environment. The Windows process spawned by xp_cmdshell has the same security rights as the SQL Server service account. It requires SysAdmin rights to use Xp_CmdShell. 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 proxy account. As a security measure by default Xp_CmdShell is disabled and we have to enable it explicitly before use. If disabled then following error message will be used when tried to use
SQL Server blocked access to procedure ‘sys.xp_cmdshell’ of component ‘xp_cmdshell’ because this component is turned off as part of the security configuration for this server. A system administrator can enable the use of ‘xp_cmdshell’ by using sp_configure. For more information about enabling ‘xp_cmdshell’, see “Surface Area Configuration” in SQL Server Books Online.
We may enable Xp_CmdShell through SSMS GUI or T-SQL. So let us explore both the ways to enable Xp_CmdShell.
To enable Xp_CmdShell through SSMS GUI perform following steps.
- Right click on server instance
- Click on Facets
- Choose Surface Area Configuration from facets drop down list
- Find Xp_cmdShell from the properties and set enabled to true
- Click OK and Xp_CmdShell is enabled now
Following snaps will help you to perform above mentioned steps for enabling Xp_CmdShell through SSMS GUI.
To enable the Xp_CmdShell through T-SQL
-- To allow advanced options to be changed. EXEC sp_configure 'show advanced options', 1 GO -- To update the currently configured value for advanced options. RECONFIGURE GO -- To enable the feature. EXEC sp_configure 'xp_cmdshell', 1 GO -- To update the currently configured value for this feature. RECONFIGURE GO
verify the current option
To verify the current status of xp_cmdshell you may use following T-SQL
-- Verify the current status of xp_cmdshell SELECT * FROM sys.configurations where name = 'xp_cmdshell' GO
Using the Xp_CmdShell
Here i will quote a simple example of xp_cmdshell usage from BOL.
Executing the following xp_cmdshell statement returns a directory listing of the current directory.
EXEC xp_cmdshell 'dir *.exe'; GO