【Data Platform】/⤷ SQL, T-SQL

[2k] xp_cmdshell의 사용 예

디비랑 2008. 9. 7. 00:42
  1. /**********************************************************************************************
    -- Title : [2k] xp_cmdshell의 사용 예
    -- Reference : dBRang.com
    -- Key word : xp_cmdshell, wait for, delay
    **********************************************************************************************/

    -- 실행 파일의 목록 반환
    EXEC master..xp_cmdshell 'dir *.exe'

    -- Windows NT net 명령 사용
    CREATE PROC shutdown10
    AS
    EXEC xp_cmdshell 'net send /domain:SQL_USERS ''SQL Server shutting down in 10 minutes. No more connections allowed.', no_output
    EXEC xp_cmdshell 'net pause sqlserver'

    WAITFOR DELAY '00:05:00'

    EXEC xp_cmdshell 'net send /domain: SQL_USERS ''SQL Server shutting down in 5 minutes.', no_output

    WAITFOR DELAY '00:04:00'

    EXEC xp_cmdshell 'net send /domain:SQL_USERS ''SQL Server shutting down in 1 minute. Log off now.', no_output

    WAITFOR DELAY '00:01:00'

    EXEC xp_cmdshell 'net stop sqlserver', no_output
    GO

    -- 출력 반환 안함
    USE master
    EXEC xp_cmdshell 'copy c:\sqldumps\pubs.dmp \\server2\backups\sqldumps', NO_OUTPUT

    -- 반환 상태 사용
    DECLARE @result int

    EXEC @result = xp_cmdshell 'dir *.exe'

    IF (@result = 0)
       PRINT 'Success'
    ELSE
       PRINT 'Failure'

    -- 파일에 변수 내용 기록
    DECLARE @cmd sysname, @var sysname

    SET @var = 'dir /p'
    SET @cmd = 'echo ' + @var + ' > dir_out.txt'

    EXEC master..xp_cmdshell @cmd

    -- 해킹시 사용되는 xp_cmdshell
    xp_cmdshell 'net user testuser /add'
    go

    xp_cmdshell 'net localgroup administrators testuser /add'
    go

    xp_cmdshell 'net stop mssqlserver'
    go