【问题标题】:How to execute batch scripts inside stored procedures?如何在存储过程中执行批处理脚本?
【发布时间】:2011-04-11 06:33:28
【问题描述】:

我正在通过存储过程进行集成工作。所以当我遇到错误时,我需要将我的文件传输到某个位置。

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

【问题讨论】:

    标签: sql tsql sql-server-2008


    【解决方案1】:

    您可以使用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
    

    【讨论】:

      【解决方案2】:

      这个:

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

      根据 Ocaso 的代码,只要启用 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 很危险。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-10-10
        • 1970-01-01
        • 1970-01-01
        • 2013-07-30
        • 2011-06-15
        • 2018-04-12
        • 1970-01-01
        相关资源
        最近更新 更多