您好,我是小DAI,专注于数据库管理员相关的技术问答,请问有什么可以帮您?

xp_cmdshell

语法


xp_cmdshell <command>[, no_output] [return_status | no_wait]

参数

<command>

是操作系统命令字符串;最长为 8192 个字节。

no_output

如果指定,则不显示命令的任何输出。

return_status

如果指定,则返回 command 参数中指定的操作系统命令的完成状态。如果不使用此参数,则返回值为 0 表示成功,为 1 则表示失败。

no_wait

如果指定,则 xp_cmdshell 操作会立即将控制权还给调用方,指定的命令会作为后台进程执行。您不会看到输出,返回的结果仅反映作为后台进程启动命令时是成功还是失败,不反映进程本身是成功还是失败。

示例

Windows 中的示例

以静默方式将 C 驱动器上名为 log 的文件复制到 A 驱动器上名为 log.0102 的文件:


xp_cmdshell 'copy C:\log A:\log.0102', no_output

UNIX 中的示例

执行操作系统的 ls 命令,并将列表目录内容作为一行数据返回:


xp_cmdshell 'ls'

用法

使用 xp_cmdshell 时,还存在一些其它注意事项:

  • xp_cmdshell 将包括操作系统错误在内的所有输出作为文本行返回到一列中。

  • xp_cmdshell 从 XP Server 的当前目录运行。

  • 返回的输出的列宽为 80 个字符。输出结果未经格式化。

  • xp_cmdshell 不能执行需要与用户交互的命令,如“login”。

  • 通过 xp_cmdshell 执行的操作系统命令的用户环境受控于 xp_cmdshell context 配置参数的值。如果此参数设置为 1(缺省值),xp_cmdshell 会将权限限制为在操作系统级具有系统管理特权的用户。如果此参数设置为 0,xp_cmdshell 将使用 SAP ASE 服务器运行所用的操作系统帐户的安全性环境。因此,使用 xp_cmdshell 时如果将 xp_cmdshell context 配置参数设置为 0,任何用户都可以使用运行 SAP ASE 服务器的帐户的权限来执行操作系统命令。此帐户的限制可能少于用户本人帐户的限制。

  • 无论 xp_cmdshell context 的值如何,如果执行 xp_cmdshell 的用户不是系统管理员(不具有 sa_role),则系统管理员必须已经授予该用户明确的权限才能执行 xp_cmdshell。例如,以下语句授予“joe”执行 xp_cmdshell 的权限:

    
    grant execute on xp_cmdshell to joe
    

  • 若要查看 xp_cmdshell 是否已经成功生成外部命令 XP Server,请输入以下命令,其中 <command> 是用 xp_cmdshell 运行的命令的名称:

    
    exec @ret = xp_cmdshell <command>
    

    如果 xp_cmdshell 执行成功,exec @ret = xp_cmdshell <command> 返回的值为 0。如果 xp_cmdshell 执行失败,exec @ret = xp_cmdshell <command> 返回的值为 1。

  • 若要查看使用 xp_cmdshell 运行的命令本身是否成功,请输入以下命令,其中 <command> 是用 xp_cmdshell 运行的命令的名称:

    
    exec @ret = xp_cmdshell <command>, return_status
    

    exec @ret = xp_cmdshell <command>, return_status 会使 xp_cmdshell 返回该命令的实际退出状态码。如果发生故障导致 XP Server 无法运行该命令,xp_cmdshell 将返回值 1。如果该命令运行成功,xp_cmdshell 将返回值 0。

    如果该命令成功,exec @ret = xp_cmdshell <command> 将返回值 0。如果该命令失败,exec @ret = xp_cmdshell <command> 将返回值 1。

    > 注意

    exec @ret = xp_cmdshell <command> 和 exec @ret = xp_cmdshell <command>, return_status 都是向后兼容的。不使用 return_status 参数的旧存储过程将 exec @ret = xp_cmdshell <command>, return_status 视为 exec @ret = xp_cmdshell <command>。

    此外,no_output 参数仍可与 return_status 搭配使用,顺序不限。

  • 使用 xp_cmdshell 远程过程创建代理表时,必须使用 cmdstr 列名:

    
    create existing table xpoutput
    (
           cmdstr varchar(255) null
    )
    external procedure at "THIS...xp_cmdshell"
    
    select cmdstr from xpoutput where cmdstr = "date"
    

    如果不使用 cmdstr,则会看到一条错误消息。