SQLSERVER记录登录用户的登录时间(自写脚本)

前一阵子经理问我能不能把用户最后一次登录我们的业务数据库的时间记录下来,因为之前有人修改过数据库sa用户的登录密码,所以我们要记录一下。

我查了一下资料,好像不能记录谁登录过业务库,只能记录谁登录过sqlserver

数据库版本是sql2005 ,操作系统:windows7

下面是本人写的一个脚本,我的实现原理是使用触发器,触发器是登录触发器,范围是整个服务器范围,如果有人登录过,就使用 bcp命令把登录信息记录日志文件

1、如果原来数据库已经存在触发器把他删掉


复制代码 代码如下:

use master

go

drop trigger trg_logon_attempttest on all server

go

2、在d盘新建一个文本文件 d:\logondata.txt 这个文本文件用来记录登录信息

3、创建一个登录触发器审核登录事件


复制代码 代码如下:

create trigger trg_logon_attempttest

on all server

with execute as’sa’

for logon,alter_login

as

begin

declare

@cmd nvarchar(4000)

select

@cmd = ‘echo ‘

+ original_login()+ char(9) + convert(varchar(100), getdate(), 121)

+ ‘ >> d:\logondata.txt’

declare @tb_re table(re varchar(4000));

insert @tb_re exec master.. xp_cmdshell @cmd

end

go

这样当每次登录sqlserver的时候就会记录登录时间和登录用户名

在创建触发器前,需要开启xp_cmdshell扩展存储过程,并且不要禁用sa用户

不然会遇到下面这种情况,登录不了服务器,我的计算机名是joe

 

如果遇到这种情况可以使用sqlserver的专用管理员连接(dac)连接进服务器,并把触发器先删除掉

日志的样式是这样的:


复制代码 代码如下:

nt authority\system 2013-02-08 16:49:04.140

nt authority\system 2013-02-08 16:49:14.210

nt authority\system 2013-02-08 16:49:24.277

joe\administrator 2013-02-08 16:49:31.753

joe\administrator 2013-02-08 16:49:31.963

nt authority\system 2013-02-08 16:49:34.327

joe\administrator 2013-02-08 16:49:35.777

sa 2013-02-08 16:51:39.930

nt authority\system 2013-02-08 16:52:03.147

nt authority\system 2013-02-08 16:52:13.337

nt authority\system 2013-02-08 16:52:23.410

nt authority\system 2013-02-08 16:52:33.830

nt authority\system 2013-02-08 16:52:44.703

nt authority\system 2013-02-08 16:52:54.407

nt authority\system 2013-02-08 16:52:54.623

nt authority\system 2013-02-08 16:52:54.797

nt authority\system 2013-02-08 16:52:54.823

nt authority\system 2013-02-08 16:52:54.893

nt authority\system 2013-02-08 16:52:55.147

nt authority\system 2013-02-08 16:52:55.277

现在还有两个问题没有解决:

(1)我只想记录非windows验证方式的用户登录,不想记录windows验证方式的 ,现在还没有找到方法

(2)修改登录用户密码的动作要记录,但是找了很久也没有找到使用什么函数

可能这篇文章还有错误,欢迎大家拍砖o(∩_∩)o !!

(0)
上一篇 2022年3月21日
下一篇 2022年3月21日

相关推荐