您的当前位置:首页正文

Open***服务端中自定义用户访问日志

2024-11-13 来源:个人技术集锦

Openvpn服务端中自定义登陆登出操作日志

1.服务端配置文件

默认配置文件路径为:

/etc/openvpn/server/server.conf

需要在配置文件末尾追加入以下内容:

script-security 2 
client-connect /etc/openvpn/server/connect.sh
client-disconnect /etc/openvpn/server/dis-connect.sh

附:connect.sh脚本内容

#!/bin/bash
day=`date +%F`
if [ -f /opt/openvpn/etc/openvpn/server/logs/client-connect.log ];then
echo "`date '+%F %H:%M:%S'` User $common_name is logged in from $trusted_ip $trusted_port " >>/opt/openvpn/etc/openvpn/server/logs/client-connect.log
else
touch /opt/openvpn/etc/openvpn/server/logs/client-connect.log
echo "`date '+%F %H:%M:%S'` User $common_name is logged in from $trusted_ip $trusted_port" >>/opt/openvpn/etc/openvpn/server/logs/client-connect.log
fi

time=$(date '+%F %H:%M:%S')
oper="客户端登陆"
sql="INSERT INTO za_connection_history(connect_name,connect_time,trusted_ip,trusted_port,opt_type,ifconfig_pool_remote_ip) VALUES ('$common_name','$time','$trusted_ip','$trusted_port','$oper','$ifconfig_pool_remote_ip')"

mysql -h localhost -P 3306 -uroot --default-character-set=utf8 -p1234 dbname -e "$sql"

其中$common_name等环境变量来源详解:(为大家收集了一篇博客,很详细)

https:///Sindweller5530/article/details/115456135

附:dis-connect.sh脚本内容

#!/bin/bash
day=`date +%F`
if [ -f /opt/openvpn/etc/openvpn/server/logs/client-connect.log ];then
echo "`date '+%F %H:%M:%S'` User $common_name is logged off from $trusted_ip $trusted_port " >>/opt/openvpn/etc/openvpn/server/logs/client-connect.log
else
touch /opt/openvpn/etc/openvpn/server/logs/client-connect.log
echo "`date '+%F %H:%M:%S'` User $common_name is logged off from $trusted_ip $trusted_port " >>/opt/openvpn/etc/openvpn/server/logs/client-connect.log
fi

time=$(date '+%F %H:%M:%S')
oper="客户端退出连接"
sql="INSERT INTO za_connection_history(connect_name,connect_time,trusted_ip,trusted_port,opt_type,ifconfig_pool_remote_ip,bytes_received,bytes_sent) VALUES ('$common_name','$time','$trusted_ip','$trusted_port','$oper','$ifconfig_pool_remote_ip','$bytes_received','$bytes_sent')"

mysql -h localhost -P 3306 -uroot --default-character-set=utf8 -p1234 dbName -e "$sql"

echo VPN会话期间,从客户端收到的总字节数:$bytes_received
echo VPN会话期间,给客户端发送的总字节数:$bytes_sent

以上信息大致同上面shell脚本

这里的echo数据的输出将记录在openvpn.log中

2.建立日志文件

必须执行下方命令(避坑)否则无法正常连接

chmod +X ./logs
chown -R nobody ./logs

3.测试

[root@localhost server]# cat ./logs/client-connect.log 
2021-11-18 15:14:30 User 方 is logged off from 192.168.6.192 51739 
2021-11-18 15:14:34 User 方 is logged in from 192.168.6.192 51765 
2021-11-18 16:00:32 User 方 is logged off from 192.168.6.192 51765 
2021-11-18 16:02:09 User 方 is logged in from 192.168.6.192 51871 

注意:

(1)脚本中有错误时,客户端无法连接。

​ 解决:查看日志/var/log/openvpn.log中根据错误提示修改。

(2)在写入数据库时中文字符集乱码问题

​ 解决:mysql -h localhost -P 3306 -uroot --default-character-set=utf8 -p1234 dbName -e

​ 在执行mysql命令时加入参数–default-character-set=utf8

总结的不好不要喷 !!

唉 ~就是玩儿~~

2021-11-18记录 给个赞再走吧!!!

显示全文