exec sys.xp_fixeddrives
六,执行DOS命令操作文件
存储过程sys.xp_cmdshell 用于执行DOS命令,该功能对应SQL Server系统的xp_cmdshell高级选项,默认情况下,该选项是禁用的,执行该存储过程,系统会抛出错误消息:
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’, search for ‘xp_cmdshell’ in SQL Server Books Online.
因此,在执行该存储过程之前,必须启用xp_cmdshell选项,由于启用该选项有潜在的风险,建议用户在执行代码之后,禁用该选项。
1,启用/禁用xp_cmdshell选项
xp_cmdshell选项属于系统的高级选项,执行以下代码,允许用户修改高级选项:
-- 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 使用以下代码启用xp_cmdshell选项:
-- To enable the feature.
exec sp_configure 'xp_cmdshell', 1;
go
-- To update the currently configured value for this feature.
reconfigure;
go使用以下代码禁用xp_cmdshell选项:
-- To disable the feature.
exec sp_configure 'xp_cmdshell', 0;
go
-- To update the currently configured value for this feature.
reconfigure;
go2,常用的DOS命令
该存储过程使得用户可以通过TSQL命令执行DOS命令,
exec sys.xp_cmdshell 'command_string'2.1 建立新文件或增加文件内容
格式:ECHO 文件内容>file_name
exec master.dbo.xp_cmdshell 'echo abc > D:sharetest.txt'2.2 查看文件内容
格式:TYPE file_name
exec master.dbo.xp_cmdshell 'type D:sharetest.txt'2.3 复制文件
格式: COPY file_name new_folder
exec master.dbo.xp_cmdshell 'copy D:testtest.txt D:share'2.4 显示目录
格式:DIR folder
exec master.dbo.xp_cmdshell 'dir D:share'










