|
| 1 | +-------------------------- |
| 2 | +-- Get List of Credentials |
| 3 | +-------------------------- |
| 4 | +USE msdb; |
| 5 | +GO |
| 6 | + |
| 7 | +SELECT |
| 8 | +j.name AS JobName, |
| 9 | +s.step_id AS StepID, |
| 10 | +s.step_name AS StepName, |
| 11 | +c.name AS CredentialName |
| 12 | +FROM sysjobs j |
| 13 | +JOIN sysjobsteps s ON j.job_id = s.job_id |
| 14 | +LEFT JOIN sys.credentials c ON s.proxy_id = c.credential_id |
| 15 | +WHERE c.name IS NOT NULL |
| 16 | +ORDER BY j.name, s.step_id; |
| 17 | + |
| 18 | +-------------------------- |
| 19 | +-- Create a Proxy Using the Target Credential |
| 20 | +-------------------------- |
| 21 | +USE msdb; |
| 22 | +GO |
| 23 | + |
| 24 | +EXEC sp_add_proxy |
| 25 | + @proxy_name = N'OSCommandProxy', -- Name of the proxy |
| 26 | + @credential_name = N'MyCredential'; -- Name of the existing credential |
| 27 | + |
| 28 | +EXEC sp_grant_proxy_to_subsystem |
| 29 | + @proxy_name = N'OSCommandProxy', |
| 30 | + @subsystem_id = 3; -- 3 represents the Operating System (CmdExec) subsystem |
| 31 | + |
| 32 | +-------------------------- |
| 33 | +-- Create the SQL Server Agent Job Configured to use the Proxy Account |
| 34 | +-------------------------- |
| 35 | + |
| 36 | +USE msdb; |
| 37 | +GO |
| 38 | + |
| 39 | +-- Create the job |
| 40 | +EXEC sp_add_job |
| 41 | + @job_name = N'WhoAmIJob'; -- Name of the job |
| 42 | + |
| 43 | +-- Add a job step that uses the proxy to execute the whoami command |
| 44 | +EXEC sp_add_jobstep |
| 45 | + @job_name = N'WhoAmIJob', |
| 46 | + @step_name = N'ExecuteWhoAmI', |
| 47 | + @subsystem = N'CmdExec', -- Specifies an Operating System command |
| 48 | + @command = N'whoami', -- The OS command to execute |
| 49 | + @on_success_action = 1, -- 1 = Quit with success |
| 50 | + @on_fail_action = 2, -- 2 = Quit with failure |
| 51 | + @proxy_name = N'OSCommandProxy'; -- The proxy created earlier |
| 52 | + |
| 53 | +-- Add a schedule to the job (optional, can be manual or scheduled) |
| 54 | +EXEC sp_add_jobschedule |
| 55 | + @job_name = N'WhoAmIJob', |
| 56 | + @name = N'RunOnce', |
| 57 | + @freq_type = 1, -- 1 = Once |
| 58 | + @active_start_date = 20240820, -- Start date (YYYYMMDD) |
| 59 | + @active_start_time = 120000; -- Start time (HHMMSS) |
| 60 | + |
| 61 | +-- Add the job to the SQL Server Agent |
| 62 | +EXEC sp_add_jobserver |
| 63 | + @job_name = N'WhoAmIJob', |
| 64 | + @server_name = N'(LOCAL)'; -- The server where the job will run |
| 65 | + |
| 66 | +-------------------------- |
| 67 | +-- Execute the Job |
| 68 | +-------------------------- |
| 69 | +EXEC sp_start_job @job_name = N'WhoAmIJob'; |
| 70 | + |
| 71 | +-------------------------- |
| 72 | +-- Check the Output/Error |
| 73 | +-------------------------- |
| 74 | +EXEC sp_help_jobhistory @job_name= N'WhoAmIJob'; |
0 commit comments