I wrote this simplistic script (I'm not very familiar with TSQL and dynamic SQL) to revoke all connections from guest accounts:
DECLARE @database_id int, @database_name nvarchar(100);
DECLARE database_cursor CURSOR FOR
SELECT name
FROM [master].sys.databases
WHERE name NOT IN ('master', 'tempdb')
AND state = 0
OPEN database_cursor
FETCH NEXT FROM database_cursor
INTO @database_name
while (@@FETCH_STATUS <> -1)
BEGIN
Print @database_name
exec('USE [' + @database_name + ']')
REVOKE CONNECT FROM 'guest'
FETCH NEXT FROM database_cursor
INTO @database_name
END
CLOSE database_cursor
DEALLOCATE database_cursor
But apparently the REVOKE was still being applied to the master database.
So then I modified the script to this:
DECLARE @database_id int, @database_name nvarchar(100);
DECLARE database_cursor CURSOR FOR
SELECT name
FROM [master].sys.databases
WHERE name NOT IN ('master', 'tempdb')
AND state = 0
OPEN database_cursor
FETCH NEXT FROM database_cursor
INTO @database_name
while (@@FETCH_STATUS <> -1)
BEGIN
Print @database_name
EXEC('USE [' + @database_name + '];'+
'REVOKE CONNECT FROM GUEST;'
);
FETCH NEXT FROM database_cursor
INTO @database_name
END
CLOSE database_cursor
DEALLOCATE database_cursor
The script runs, but the changes aren't be saved for some reason because the guest account is not revoked when I check for it afterwards.
Sorry, if I'm missing any other details. I'm so unfamiliar to this realm, I'm not even sure how to frame the question.
Thanks in advance!
Update 1:
I'm checking that it's been revoked using this script from the DISA STIGs:
SELECT COUNT(grantee_principal_id)
FROM sys.database_permissions
WHERE grantee_principal_id = 2
AND state = 'G'
AND permission_name = 'CONNECT'
Best Answer
I ran your script with no problems so my guess is that something is wrong with your conformation script. I don't see anything specifically wrong with it but here are a couple of links with additional information about disabling guest.
http://blog.sqlauthority.com/2012/02/24/sql-server-guest-user-and-msdb-database-enable-guest-user-on-msdb-database/
http://blog.sqlauthority.com/2012/02/20/sql-server-disable-guest-account-serious-security-issue/
Here is a a modified version of Pinal Dave's script that should help you confirm.