Меню Закрыть

Exec master xp cmdshell

Содержание

ОБЛАСТЬ ПРИМЕНЕНИЯ: SQL Server База данных SQL Azure Azure Synapse Analytics (хранилище данных SQL) Parallel Data Warehouse APPLIES TO: SQL Server Azure SQL Database Azure Synapse Analytics (SQL DW) Parallel Data Warehouse

Увеличивает число процессов командного ядра Windows в строке для выполнения. Spawns a Windows command shell and passes in a string for execution. Любые выходные данные возвращаются в виде текстовых строк. Any output is returned as rows of text.

Синтаксические обозначения в Transact-SQL Transact-SQL Syntax Conventions

Синтаксис Syntax

Аргументы Arguments

" command_string " command_string
Строка, содержащая команду для передачи операционной системе. Is the string that contains a command to be passed to the operating system. command_stringvarchar(8000) или nvarchar(4000) , не имеет значения по умолчанию. command_string is varchar(8000) or nvarchar(4000), with no default. command_string не может содержать более одного набора двойных кавычек. command_string cannot contain more than one set of double quotation marks. Одной пары кавычек является обязательным, если все пробелы в пути к файлам или именах программ в аргументе command_string. A single pair of quotation marks is required if any spaces are present in the file paths or program names referenced in command_string. Если входящие пробелы вызывают неполадки, то следует присваивать файлам имена в формате FAT 8.3. If you have trouble with embedded spaces, consider using FAT 8.3 file names as a workaround.

no_output no_output
Необязательный параметр, указывающий, что клиенту не следует возвращать выходные данные. Is an optional parameter, specifying that no output should be returned to the client.

Значения кода возврата Return Code Values

0 (успешное завершение) или 1 (неуспешное завершение) 0 (success) or 1 (failure)

Результирующие наборы Result Sets

Выполнение следующей процедуры xp_cmdshell возвращает листинг текущего каталога. Executing the following xp_cmdshell statement returns a directory listing of the current directory.

Строки возвращаются в nvarchar(255) столбца. The rows are returned in an nvarchar(255) column. Если no_output используется параметр, будут возвращены только следующие: If the no_output option is used, only the following will be returned:

Примечания Remarks

Процесс Windows, сформированными xp_cmdshell имеет те же права, как SQL Server SQL Server учетной записи службы. The Windows process spawned by xp_cmdshell has the same security rights as the SQL Server SQL Server service account.

xp_cmdshell работает синхронно. xp_cmdshell operates synchronously. Управление не возвращается участнику до завершения команды ядра. Control is not returned to the caller until the command-shell command is completed.

xp_cmdshell можно включать и отключать с помощью управления на основе политик или путем выполнения sp_configure. xp_cmdshell can be enabled and disabled by using the Policy-Based Management or by executing sp_configure. Дополнительные сведения см. в разделе настройки контактной зоны и параметр конфигурации сервера xp_cmdshell. For more information, see Surface Area Configuration and xp_cmdshell Server Configuration Option.

Читайте также:  Разбор букв по звукам все буквы

Если xp_cmdshell выполняется в пакете и возвращает сообщение об ошибке пакета завершится ошибкой. If xp_cmdshell is executed within a batch and returns an error, the batch will fail. Это изменение поведения. This is a change of behavior. В более ранних версиях Microsoft Microsoft SQL Server SQL Server пакета продолжилось бы для выполнения. In earlier versions of Microsoft Microsoft SQL Server SQL Server the batch would continue to execute.

Учетная запись-посредник для процедуры xp_cmdshell xp_cmdshell Proxy Account

Если он вызывается пользователем, который не является членом sysadmin предопределенной роли сервера, xp_cmdshell подключается к Windows, используя имя учетной записи и пароль хранятся в учетных данных с именем ## #xp_cmdshell_proxy_account ## . 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 the account name and password stored in the credential named ##xp_cmdshell_proxy_account##. Если эти посреднические учетные данные не существует, xp_cmdshell завершится ошибкой. If this proxy credential does not exist, xp_cmdshell will fail.

Учетные данные учетной записи прокси-сервера можно создать, выполнив sp_xp_cmdshell_proxy_account. The proxy account credential can be created by executing sp_xp_cmdshell_proxy_account. В качестве аргумента эта хранимая процедура обрабатывает имя пользователя Windows и пароль. As arguments, this stored procedure takes a Windows user name and password. Например, следующая команда создает посреднические учетные записи-посредники для пользователя домена Windows SHIPPINGKobeR с паролем Windows sdfh%dkc93vcMt0 . For example, the following command creates a proxy credential for Windows domain user SHIPPINGKobeR that has the Windows password sdfh%dkc93vcMt0 .

Разрешения Permissions

Поскольку иногда пользователи-злоумышленники пытаются повысить свои полномочия с помощью xp_cmdshell, xp_cmdshell отключен по умолчанию. Because malicious users sometimes attempt to elevate their privileges by using xp_cmdshell, xp_cmdshell is disabled by default. Используйте sp_configure или управления на основе политик Чтобы включить его. Use sp_configure or Policy Based Management to enable it. Дополнительные сведения см. в разделе Параметр конфигурации сервера xp_cmdshell. For more information, see xp_cmdshell Server Configuration Option.

При первом включении xp_cmdshell требуется разрешение CONTROL SERVER для выполнения и процесс Windows, созданных xp_cmdshell имеет тот же контекст безопасности, как SQL Server SQL Server учетной записи службы. When first enabled, xp_cmdshell requires CONTROL SERVER permission to execute and the Windows process created by xp_cmdshell has the same security context as the SQL Server SQL Server service account. SQL Server SQL Server Учетной записи службы часто имеет больше разрешений, чем это необходимо для работы, выполняемой процессом, созданные xp_cmdshell. The SQL Server SQL Server service account often has more permissions than are necessary for the work performed by the process created by xp_cmdshell. В целях повышения безопасности доступа к xp_cmdshell должны быть только пользователи с высоким уровнем привилегий. To enhance security, access to xp_cmdshell should be restricted to highly privileged users.

Читайте также:  Лучшие недорогие строительные пылесосы

Чтобы разрешить пользователям без прав администратора использовать xp_cmdshellи разрешить SQL Server SQL Server создавать дочерние процессы с маркером безопасности, менее привилегированной учетной записи, выполните следующие действия: To allow non-administrators to use xp_cmdshell, and allow SQL Server SQL Server to create child processes with the security token of a less-privileged account, follow these steps:

Создайте и настройте локальную учетную запись Windows или учетную запись домена с меньшими правами доступа, чем требуется процессу. Create and customize a Windows local user account or a domain account with the least privileges that your processes require.

Используйте sp_xp_cmdshell_proxy_account системной процедуры для настройки xp_cmdshell использовать эту учетную запись с минимальными правами доступа. Use the sp_xp_cmdshell_proxy_account system procedure to configure xp_cmdshell to use that least-privileged account.

Можно также настроить этот прокси-сервер использует учетную запись SQL Server Management Studio SQL Server Management Studio щелкните правой кнопкой мыши свойства на сервере, имя в обозревателе объектов и посмотрев безопасности вкладке сервера Учетная запись-посредник раздел. You can also configure this proxy account using SQL Server Management Studio SQL Server Management Studio by right-clicking Properties on your server name in Object Explorer, and looking on the Security tab for the Server proxy account section.

В Среда Management Studio Management Studio , с помощью базы данных master, выполните GRANT exec ON xp_cmdshell TO ‘ ‘ инструкцию, чтобы предоставить конкретным отличныхsysadmin пользователям возможность выполнять xp_cmdshell. In Среда Management Studio Management Studio , using the master database, execute the GRANT exec ON xp_cmdshell TO ‘ ‘ statement to give specific non-sysadmin users the ability to execute xp_cmdshell. Указанное имя входа необходимо сопоставить с пользователем в базе данных master. The specified login must be mapped to a user in the master database.

Теперь пользователям без прав администратора могут запускать процессы операционной системы с xp_cmdshell и эти процессы будут запускаться с правами учетной записи-посредника, который вы настроили. Now non-administrators can launch operating system processes with xp_cmdshell and those processes run with the permissions of the proxy account that you have configured. Пользователи с разрешением CONTROL SERVER (члены sysadmin предопределенной роли сервера) продолжит получать разрешения SQL Server SQL Server учетная запись службы для дочерних процессов, которые запускаются с xp_cmdshell . Users with CONTROL SERVER permission (members of the sysadmin fixed server role) will continue to receive the permissions of the SQL Server SQL Server service account for child processes that are launched by xp_cmdshell.

Читайте также:  Cannot initialize 3d engine

Для определения учетной записи Windows, которая используется xp_cmdshell при запуске процессов операционной системы, выполните следующую инструкцию: To determine the Windows account being used by xp_cmdshell when launching operating system processes, execute the following statement:

Чтобы определить контекст безопасности для другого имени входа, выполните следующее: To determine the security context for another login, execute the following:

Примеры Examples

A. A. Возвращение списка исполняемых файлов Returning a list of executable files

В следующем примере показано, как расширенная хранимая процедура xp_cmdshell выполняет команду каталога. The following example shows the xp_cmdshell extended stored procedure executing a directory command.

Б. B. Применение без возврата данных Returning no output

В следующем примере процедура xp_cmdshell применяется для выполнения командной строки без возвращения данных клиенту. The following example uses xp_cmdshell to execute a command string without returning the output to the client.

В. C. Применение возвращаемого состояния Using return status

В следующем примере xp_cmdshell расширенной хранимой процедуры также предлагает возвращаемое состояние. In the following example, the xp_cmdshell extended stored procedure also suggests return status. Значение кода возврата хранится в переменной @result . The return code value is stored in the variable @result .

Wednesday, April 9, 2008

Выполнение команд операционной системы в MS SQL

MS SQL Server позволяет выполнять команды операционной системы и возвращать результат в виде текстовых строк. Например, прямо из SQL Server можно запустить bat-файл, любую программу и вообще использовать все возможности командной строки.

Для этого используется системная хранимая процедура xp_cmdshell. Запуск этой процедуры по умолчанию запрещен. Чтобы включить эту возможность нужно выполнить следующий код:

— Включение разрешения изменения расширенных опций.
EXEC sp_configure ‘show advanced options’, 1
GO
— Обновление текущих настроек расширенных опций.
RECONFIGURE
GO
— Включение возможности запуска внешних программ.
EXEC sp_configure ‘xp_cmdshell’, 1
GO
— Обновление текущих настроек для запуска внешних программ.
RECONFIGURE
GO

Теперь для запуска bat-файла достаточно выполнить следующую команду:

EXEC master..xp_cmdshell ‘test.bat’

Или эту, если вы хотите подавить вывод результатов:

I’m trying to delete a excel file using xp_cmdshell, but is not working. I check the other questions of here but I can’t solve my issue, I activated the advanced options of SQL SERVER to allow this sintax, but it show’s me a error message like this:

Can anybody tell me what I do wrong, or how can I solve this issue.

Рекомендуем к прочтению

Добавить комментарий

Ваш адрес email не будет опубликован.