2011-04-11 168 views
2

我正在通过存储过程进行集成工作。所以当我遇到错误时,我需要将我的文件传输到某个位置。如何在存储过程中执行批处理脚本?

我有一个Windows批处理文件,我需要使用存储过程来执行该批处理文件,这意味着我需要在该存储过程中使用查询来执行该批处理文件。任何建议?

回答

0

您可以使用xp_cmdshell,例如, xp_cmdshell 'dir *.*'

也许你需要激活SP:

-- 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 
0

此:

exec master..xp_cmdshell 'c:\path\file.bat' 

应该xp_cmdshell的启动就好了,只要工作,按照奥卡索的代码。当然xp_cmdshell是一个可怕的小野兽,只有在所有其他选项都用尽的情况下才能启用它。考虑这一点非常可怕的批处理文件,是否存在:

@ECHO OFF 
REM Database info 
REM User must have xp_cmdshell exec privileges 
SET "user=username" 
SET "pass=password" 
set "servername=192.168.1.100" 
set "database=database_name" 
IF EXIST thiscmd.sql DEL /F /Q thiscmd.sql 

ECHO SET NOCOUNT ON > thiscmd.sql 
ECHO create table #result (outputrow varchar(200)) >> thiscmd.sql 
ECHO Insert into #result >> thiscmd.sql 
ECHO exec master..xp_cmdshell '%~1' >> thiscmd.sql 
ECHO declare @thisline varchar(200) >> thiscmd.sql 
ECHO declare output_cursor CURSOR FOR >> thiscmd.sql 
ECHO select * from #result >> thiscmd.sql 
ECHO OPEN output_cursor >> thiscmd.sql 
ECHO FETCH NEXT FROM output_cursor into @thisline >> thiscmd.sql 
ECHO WHILE @@FETCH_STATUS = 0 >> thiscmd.sql 
ECHO BEGIN >> thiscmd.sql 
ECHO print @thisline >> thiscmd.sql 
ECHO FETCH NEXT FROM output_cursor into @thisline >> thiscmd.sql 
ECHO END >> thiscmd.sql 
ECHO CLOSE output_cursor >> thiscmd.sql 
ECHO DEALLOCATE output_cursor >> thiscmd.sql 
ECHO drop table #result >> thiscmd.sql 

.\osql -n -U%user% -P%pass% -S%servername% -d%database% -w200 -i thiscmd.sql 

IF EXIST thiscmd.sql DEL /F /Q thiscmd.sql 

假设所提供的用户名和密码的xp_cmdshell访问,该批处理文件基本上是给你一个远程命令提示符下运行的任何用户拥有SQL服务。这意味着如果有人妥协了一个SQL用户,他们已经损害了整个服务器。我有类似的批处理文件,可以自动执行net命令来回移动文件,我保证任何值得他/她的盐的攻击者也会这样做。

TL; DR:小心使用! xp_cmdshell是危险的。