ORACLE常用的与会话相关的查询
- ORACLE常用的与会话相关的查询
- 查看当前锁的信息:
- 查看当前正在执行的sql
- ORACLE的监听日志(listener.log)
- Listener log location
- For oracle 9i/10g
- For oracle 11g/12c
- 或者通过 lsnrctl status 也可以查看位置
- 或者11g可以通过 adrci 命令
- Listener log日志文件清理
- 清理shell脚本
- 统计不同IP连接的次数
- 过滤监听日志。看每分钟连了多少次
- 每个ip在指定时间段的连接次数
- Listener log location
- 查看连接失败的用户信息
查看当前锁的信息:
查询当前活动的事务:
set linesize240 pages999;
select inst_id as instance,event,sum(decode(wait_time, 0, 1, 0)) "Curr",sum(decode(wait_time, 0, 0, 1)) "Prev",count(*) "Total"from gv$session_waitwhere event not in ('smon timer','pmon timer','rdbms ipc message','SQL*Net message from client','gcs remote message')and event not like '%idle%'and event not like '%Idle%'and event not like '%Streams AQ%'group by inst_id, eventorder by inst_id, count(*) desc;通过事务类型,查询对应的会话的信息:set linesize 300 pages 999col USERNAME for a12col MACHINE for a20col PROGRAM for a20col PREV_SQL_ID for a13col STATUS for a7col SQL_ID for a13col EVENT for a30col osuser for a15col SPID for a8SELECT a.INST_ID,a.SID,a.SERIAL#,b.spid,a.osuser,a.USERNAME,a.PREV_SQL_ID,a.SQL_ID,a.EVENT#,a.EVENT,a.STATUS,a.BLOCKING_INSTANCE AS blk_in,a.BLOCKING_SESSION AS blk_sid
FROM gv$session a,gv$process b
WHERE a.PADDR = b.ADDRAND a.INST_ID = b.INST_IDAND a.EVENT ='&event';根据set linesize 300 pages 999col USERNAME for a12col MACHINE for a20col PROGRAM for a20col PREV_SQL_ID for a13col STATUS for a7col SQL_ID for a13col EVENT for a30col osuser for a15col SPID for a8
col P123 for a30;SELECT S.SID,S.SERIAL#,P.SPID,S.USERNAME,S.MACHINE,s.osuser,S.STATUS,p.PGA_USED_MEM / 1024 / 1024 pga_use_MB,trunc(p.PGA_ALLOC_MEM / 1024 / 1024) PGA_ALLOC_MB,S.WAIT_TIME WT,NVL(SQL_ID, S.PREV_SQL_ID) SQL_ID,s.BLOCKING_INSTANCE,s.BLOCKING_SESSION blk_sidFROM V$PROCESS P,V$SESSION SWHERE P.ADDR = S.PADDRAND P.BACKGROUND IS NULLand S.SID=&sidORDER BY event;通过sql_id查看对应的sqlselect SQL_TEXT from v$sql where sql_id='65agvq7dd1j43';最终得到的结果是被阻塞的sql查看锁定关系
SELECT s1.username
|| '@'
|| s1.machine
|| ' ( SID='
|| s1.sid
|| ' ) is blocking '
|| s2.username
|| '@'
|| s2.machine
|| ' ( SID='
|| s2.sid
|| ' ) '
AS blocking_status
FROM v$lock l1,
v$session s1,
v$lock l2,
v$session s2
WHERE s1.sid = l1.sid
AND s2.sid = l2.sid
AND l1.BLOCK = 1
AND l2.request > 0
AND l1.id1 = l2.id1
AND l2.id2 = l2.id2;select sn.USERNAME ||'@'||sn.machine,'|SID->' || m.SID,'|Serial->'|| sn.SERIAL#,'|Lock Type->'||m.TYPE,decode(LMODE,1, 'Null',2, 'Row-S (SS)',3, 'Row-X (SX)',4, 'Share',5, 'S/Row-X (SSX)',6, 'Exclusive') lock_type,decode(REQUEST,0, 'None',1, 'Null',2, 'Row-S (SS)',3, 'Row-X (SX)',4, 'Share',5, 'S/Row-X (SSX)',6, 'Exclusive') lock_requested,'|Time (Sec)->'||m.CTIME "Time(sec)",'|ID1->'||m.ID1,'|ID2->'||m.ID2,'|SQL Text->'||t.SQL_TEXT
from v$session sn,v$lock m ,v$sqltext t
where t.ADDRESS =sn.SQL_ADDRESS
and t.HASH_VALUE =sn.SQL_HASH_VALUE
and ((sn.SID =m.SID and m.REQUEST !=0)
or (sn.SID =m.SID and m.REQUEST =0 and LMODE !=4 and (ID1, ID2) in(select s.ID1, s.ID2from v$lock Swhere REQUEST !=0and s.ctime > 5and s.ID1 =m.ID1and s.ID2 =m.ID2)))
order by sn.USERNAME, sn.SID, t.PIECE
查看当前会话状态和锁信息:
单机:
SELECT LPAD(' ',5*(LEVEL-1))||S."USERNAME" AS user_name , LPAD(' ',5*(LEVEL-1))||S."SID" AS session_id,S."SERIAL#",S."SQL_ID", S."ROW_WAIT_OBJ#",S."WAIT_CLASS",S."EVENT",S."P1",S."P2",S."P3",S."SECONDS_IN_WAIT"
FROM V$SESSION S
WHERE S."BLOCKING_SESSION" IS NOT NULL
OR S.SID IN(SELECT DISTINCT BLOCKING_SESSION FROM V$SESSION)
START WITH S."BLOCKING_SESSION" IS NULL
CONNECT BY PRIOR S."SID" = S."BLOCKING_SESSION";rac或者单机:
col SQL_TEXT format a20
col ORACLE_USERNAME format a10
col TERMINAL format a10
col MACHINE format a10
col P1 format a5
col USERNAME format a10
SELECT LPAD(' ',5*(LEVEL-1))||S."USERNAME" , LPAD(' ',5*(LEVEL-1))||S."INST_ID"||','||S."SID" ,S.sid,S."SERIAL#" ,S."SQL_ID", S."ROW_WAIT_OBJ#",S."WAIT_CLASS",S."EVENT",S."TYPE",l.locked_mode,S."P1",S."P2",S."P3",S."SECONDS_IN_WAIT",s."BLOCKING_INSTANCE"||','||s."BLOCKING_SESSION",s.machine,s.terminal,a.sql_text, a.action,l.oracle_username,s.user#,s.status
FROM GV$SESSION S
join v$sqlarea a on S.prev_sql_addr = a.address
join v$locked_object l on l.session_id = S.sid
WHERE S."BLOCKING_SESSION" IS NOT NULL
OR (S."INST_ID"||','||S."SID") IN(SELECT DISTINCT BLOCKING_INSTANCE||','||BLOCKING_SESSION FROM GV$SESSION)
START WITH (s."BLOCKING_INSTANCE"||','||s."BLOCKING_SESSION") = ','
CONNECT BY PRIOR (S."INST_ID"||','||S."SID") = (s."BLOCKING_INSTANCE"||','||s."BLOCKING_SESSION");
以上表示第一个会话阻塞了下面的会话,第二个会话在争夺一个TX锁,也就是等待第一个会话释放这个锁(TX - row lock contention)。
解决方案:
ALTER SYSTEM KILL SESSION '24,201';
或者
kill -9 spid
kill -9 13771
简洁版
col SQL_TEXT format a20
col ORACLE_USERNAME format a10
col TERMINAL format a10
col MACHINE format a10
col STATUS format a6
col USERNAME format a10
SELECT LPAD(' ',5*(LEVEL-1))||S."USERNAME" USERNAME, S.sid,S."SQL_ID", t2.spid,S."SERIAL#" ,S."EVENT",l.locked_mode,S."SECONDS_IN_WAIT",s.machine,s.terminal,a.sql_text, a.action,s.status
FROM GV$SESSION S
join v$sqlarea a on S.prev_sql_addr = a.address
join v$locked_object l on l.session_id = S.sid
join gv$process t2 on S.paddr=t2.addr
WHERE S."BLOCKING_SESSION" IS NOT NULL
OR (S."INST_ID"||','||S."SID") IN(SELECT DISTINCT BLOCKING_INSTANCE||','||BLOCKING_SESSION FROM GV$SESSION)
START WITH (s."BLOCKING_INSTANCE"||','||s."BLOCKING_SESSION") = ','
CONNECT BY PRIOR (S."INST_ID"||','||S."SID") = (s."BLOCKING_INSTANCE"||','||s."BLOCKING_SESSION");
以上查询可以看到阻塞整个的源头和被阻塞的会话信息
可通过下面的查询获取到备阻塞的会话信息:
查看当前正在执行的sql
set linesize 300
col ACTION format a10
col SQL_ID format a20
col LOGINTIME format a20
col EXETIME format a20
col SQL_FULLTEXT format a40select t.BLOCKING_SESSION,t.SQL_ID,t.SID,t.SERIAL#,t.ACTION,t.LOGON_TIME , --登录时间trunc((sysdate - t.LOGON_TIME) * 24 * 60 * 60) || 's' as logintime, --登录时长trunc(nvl(s.ELAPSED_TIME / decode(s.EXECUTIONS, 0, 1, s.EXECUTIONS) /1000000,0),2) || 's' as exetime, --当前SQL每次执行平均耗时s.sql_fulltextFROM gv$session tleft join v$sql son s.sql_id = t.sql_idand s.CHILD_NUMBER = t.SQL_CHILD_NUMBERWHERE t.STATUS = 'ACTIVE'and t.WAIT_CLASS <> 'Idle'order by t.SID, t.MACHINE;
ORACLE的监听日志(listener.log)
在ORACLE数据库中,如果不对监听日志文件(listener.log)进行截断,那么监听日志文件(listener.log)会变得越来越大.
Listener log location
For oracle 9i/10g
在下面的目录下:
$ORACLE_HOME/network/log/listener_$ORACLE_SID.log
For oracle 11g/12c
在下面的目录下:
$ORACLE_BASE/diag/tnslsnr/主机名称/listener/trace/listener.log
或者通过 lsnrctl status 也可以查看位置
[oracle@oracle trace]$ lsnrctl statusLSNRCTL for Linux: Version 11.2.0.4.0 - Production on 29-JUL-2021 19:47:29Copyright (c) 1991, 2013, Oracle. All rights reserved.Connecting to (DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=oracle)(PORT=1521)))
STATUS of the LISTENER
------------------------
Alias LISTENER
Version TNSLSNR for Linux: Version 11.2.0.4.0 - Production
Start Date 29-JUL-2021 19:35:13
Uptime 0 days 0 hr. 12 min. 16 sec
Trace Level off
Security ON: Local OS Authentication
SNMP OFF
Listener Parameter File /u01/app/oracle/product/11.2.0/dbhome_1/network/admin/listener.ora
Listener Log File /u01/app/oracle/diag/tnslsnr/oracle/listener/alert/log.xml
这里展示的是 xml格式的日志,跟.log并无区别。
或者11g可以通过 adrci 命令
oracle@entel2:[/oracle]$adrciADRCI: Release 11.2.0.4.0 - Production on Wed Nov 30 20:56:28 2016Copyright (c) 1982, 2011, Oracle and/or its affiliates. All rights reserved.ADR base = "/oracle"
adrci> help --help可以看帮助命令。输入help show alert,可以看到show alert的详细用法HELP [topic]Available Topics:CREATE REPORTECHOEXITHELPHOSTIPSPURGERUNSET BASESET BROWSERSET CONTROLSET ECHOSET EDITORSET HOMES | HOME | HOMEPATHSET TERMOUTSHOW ALERTSHOW BASESHOW CONTROLSHOW HM_RUNSHOW HOMES | HOME | HOMEPATHSHOW INCDIRSHOW INCIDENTSHOW PROBLEMSHOW REPORTSHOW TRACEFILESPOOLThere are other commands intended to be used directly by Oracle, type"HELP EXTENDED" to see the listadrci> show alert --显示alert信息Choose the alert log from the following homes to view:1: diag/clients/user_oracle/host_880756540_80
2: diag/tnslsnr/procsdb2/listener_cc
3: diag/tnslsnr/entel2/sid_list_listener
4: diag/tnslsnr/entel2/listener_rb
5: diag/tnslsnr/entel2/listener
6: diag/tnslsnr/entel2/listener_cc
7: diag/tnslsnr/procsdb1/listener_rb
8: diag/rdbms/ccdg/ccdg
9: diag/rdbms/rb/rb
10: diag/rdbms/cc/cc
Q: to quitPlease select option: 5 --输入数字,查看对应日志
Output the results to file: /tmp/alert_13187_1397_listener_3.ado2016-06-27 09:15:45.164000 -04:00
Create Relation ADR_CONTROL
Create Relation ADR_INVALIDATION
Create Relation INC_METER_IMPT_DEF
2016-06-27 09:15:46.444000 -04:00
Create Relation INC_METER_PK_IMPTS
System parameter file is /oracle/product/112/network/admin/listener.ora
Log messages written to /oracle/diag/tnslsnr/entel2/listener/alert/log.xml
Trace information written to /oracle/diag/tnslsnr/entel2/listener/trace/ora_16175_140656975550208.trc
Trace level is currently 0Started with pid=16175
Listening on: (DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=10.45.7.198)(PORT=1521)))
Listening on: (DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=192.168.123.1)(PORT=1521)))
Listener completed notification to CRS on start
......
......
......
Listener log日志文件清理
需要对监听日志文件(listener.log)进行定期清理。
1:监听日志文件(listener.log)变得越来越大,占用额外的存储空间
2:监听日志文件(listener.log)变得太大会带来一些问题,查找起来也相当麻烦
3:监听日志文件(listener.log)变得太大,给写入、查看带来的一些性能问题、麻烦
定期对监听日志文件(listener.log)进行清理,另外一种说法叫截断日志文件。
列举一个错误的做法
oracle@entel2:[/oracle]$mv listener.log listener.log.20161201
oracle@entel2:[/oracle]$cp /dev/null listener.log
oracle@entel2:[/oracle]$more listener.log
如上所示,这样截断监听日志(listener.log)后,监听服务进程(tnslsnr)并不会将新的监听信息写入listener.log,而是继续写入listener.log.20161201
正确的做法
1:首先停止监听服务进程(tnslsnr)记录日志。
oracle@entel2:[/oracle]$lsnrctl set log_status off
2:将监听日志文件(listener.log)复制一份,以listener.log.yyyymmdd格式命名
oracle@entel2:[/oracle]$cp listener.log listener.log.20161201
3:将监听日志文件(listener.log)清空。清空文件的方法有很多
oracle@entel2:[/oracle]$echo “” > listener.log
或者
oracle@entel2:[/oracle]$cp /dev/null listener.log
或者
oracle@entel2:[/oracle]$echo /dev/null > listener.log
或者
oracle@entel2:[/oracle]$>listener.log
4:开启监听服务进程(tnslsnr)记录日志
oracle@entel2:[/oracle]$lsnrctl set log_status on
当然也可以移走监听日志文件(listener.log),数据库实例会自动创建一个listener.log文件。
oracle@entel2:[/oracle]$ lsnrctl set log_status off
oracle@entel2:[/oracle]$mv listener.log listener.yyyymmdd
oracle@entel2:[/oracle]$lsnrctl set log_status on
清理shell脚本
当然这些操作应该通过shell脚本来处理,然后结合crontab作业定期清理、截断监听日志文件。
简单一点的(核心部分)
rq=` date +"%d" `
cp $ORACLE_HOME/network/log/listener.log $ORACLE_BACKUP/network/log/listener_$rq.log
su - oracle -c "lsnrctl set log_status off"
cp /dev/null $ORACLE_HOME/network/log/listener.log
su - oracle -c "lsnrctl set log_status on"
这样的脚本还没有解决一个问题,就是截断的监听日志文件保留多久的问题。比如我只想保留这些截断的监听日志一个月时间,我希望作业自动维护。不需要我去手工操作。有这样一个脚本cls_oracle.sh可以完全做到这个,当然它还会归档、清理其它日志文件,例如告警文件(alert_sid.log)等等。功能非常强大。
#!/bin/bash
#
# Script used to cleanup any Oracle environment.
#
# Cleans: audit_log_dest
# background_dump_dest
# core_dump_dest
# user_dump_dest
#
# Rotates: Alert Logs
# Listener Logs
#
# Scheduling: 00 00 * * * /home/oracle/_cron/cls_oracle/cls_oracle.sh -d 31 > /home/oracle/_cron/cls_oracle/cls_oracle.log 2>
&1
#
# Created By: Tommy Wang 2012-09-10
#
# History:
#RM="rm -f"
RMDIR="rm -rf"
LS="ls -l"
MV="mv"
TOUCH="touch"
TESTTOUCH="echo touch"
TESTMV="echo mv"
TESTRM=$LS
TESTRMDIR=$LSSUCCESS=0
FAILURE=1
TEST=0
HOSTNAME=`hostname`
ORAENV="oraenv"
TODAY=`date +%Y%m%d`
ORIGPATH=/usr/local/bin:$PATH
ORIGLD=$LD_LIBRARY_PATH
export PATH=$ORIGPATH# Usage function.
f_usage(){echo "Usage: `basename $0` -d DAYS [-a DAYS] [-b DAYS] [-c DAYS] [-n DAYS] [-r DAYS] [-u DAYS] [-t] [-h]"echo " -d = Mandatory default number of days to keep log files that are not explicitly passed as parameters."echo " -a = Optional number of days to keep audit logs."echo " -b = Optional number of days to keep background dumps."echo " -c = Optional number of days to keep core dumps."echo " -n = Optional number of days to keep network log files."echo " -r = Optional number of days to keep clusterware log files."echo " -u = Optional number of days to keep user dumps."echo " -h = Optional help mode."echo " -t = Optional test mode. Does not delete any files."
}if [ $# -lt 1 ]; thenf_usageexit $FAILURE
fi# Function used to check the validity of days.
f_checkdays(){if [ $1 -lt 1 ]; thenecho "ERROR: Number of days is invalid."exit $FAILUREfiif [ $? -ne 0 ]; thenecho "ERROR: Number of days is invalid."exit $FAILUREfi
} # Function used to cut log files.
f_cutlog(){# Set name of log file.LOG_FILE=$1CUT_FILE=${LOG_FILE}.${TODAY}FILESIZE=`ls -l $LOG_FILE | awk '{print $5}'`# Cut the log file if it has not been cut today.if [ -f $CUT_FILE ]; thenecho "Log Already Cut Today: $CUT_FILE"elif [ ! -f $LOG_FILE ]; thenecho "Log File Does Not Exist: $LOG_FILE"elif [ $FILESIZE -eq 0 ]; thenecho "Log File Has Zero Size: $LOG_FILE"else# Cut file.echo "Cutting Log File: $LOG_FILE"$MV $LOG_FILE $CUT_FILE$TOUCH $LOG_FILEfi
}# Function used to delete log files.
f_deletelog(){# Set name of log file.CLEAN_LOG=$1# Set time limit and confirm it is valid.CLEAN_DAYS=$2f_checkdays $CLEAN_DAYS# Delete old log files if they exist.find $CLEAN_LOG.[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9] -type f -mtime +$CLEAN_DAYS -exec $RM {} \; 2>/dev/null
}# Function used to get database parameter values.
f_getparameter(){if [ -z "$1" ]; thenreturnfiPARAMETER=$1sqlplus -s /nolog <<EOF | awk -F= "/^a=/ {print \$2}"
set head off pagesize 0 feedback off linesize 200
whenever sqlerror exit 1
conn / as sysdba
select 'a='||value from v\$parameter where name = '$PARAMETER';
EOF
}# Function to get unique list of directories.
f_getuniq(){if [ -z "$1" ]; thenreturnfiARRCNT=0MATCH=Nx=0for e in `echo $1`; doif [ ${#ARRAY[*]} -gt 0 ]; then# See if the array element is a duplicate.while [ $x -lt ${#ARRAY[*]} ]; doif [ "$e" = "${ARRAY[$x]}" ]; thenMATCH=Yfidonefiif [ "$MATCH" = "N" ]; thenARRAY[$ARRCNT]=$eARRCNT=`expr $ARRCNT+1`fix=`expr $x + 1`doneecho ${ARRAY[*]}
}# Parse the command line options.
while getopts a:b:c:d:n:r:u:th OPT; docase $OPT ina) ADAYS=$OPTARG;;b) BDAYS=$OPTARG;;c) CDAYS=$OPTARG;;d) DDAYS=$OPTARG;;n) NDAYS=$OPTARG;;r) RDAYS=$OPTARG;;u) UDAYS=$OPTARG;;t) TEST=1;;h) f_usageexit 0;;*) f_usageexit 2;;esac
done
shift $(($OPTIND - 1))# Ensure the default number of days is passed.
if [ -z "$DDAYS" ]; thenecho "ERROR: The default days parameter is mandatory."f_usageexit $FAILURE
fi
f_checkdays $DDAYSecho "`basename $0` Started `date`."# Use test mode if specified.
if [ $TEST -eq 1 ]
thenRM=$TESTRMRMDIR=$TESTRMDIRMV=$TESTMVTOUCH=$TESTTOUCHecho "Running in TEST mode."
fi# Set the number of days to the default if not explicitly set.
ADAYS=${ADAYS:-$DDAYS}; echo "Keeping audit logs for $ADAYS days."; f_checkdays $ADAYS
BDAYS=${BDAYS:-$DDAYS}; echo "Keeping background logs for $BDAYS days."; f_checkdays $BDAYS
CDAYS=${CDAYS:-$DDAYS}; echo "Keeping core dumps for $CDAYS days."; f_checkdays $CDAYS
NDAYS=${NDAYS:-$DDAYS}; echo "Keeping network logs for $NDAYS days."; f_checkdays $NDAYS
RDAYS=${RDAYS:-$DDAYS}; echo "Keeping clusterware logs for $RDAYS days."; f_checkdays $RDAYS
UDAYS=${UDAYS:-$DDAYS}; echo "Keeping user logs for $UDAYS days."; f_checkdays $UDAYS# Check for the oratab file.
if [ -f /var/opt/oracle/oratab ]; thenORATAB=/var/opt/oracle/oratab
elif [ -f /etc/oratab ]; thenORATAB=/etc/oratab
elseecho "ERROR: Could not find oratab file."exit $FAILURE
fi# Build list of distinct Oracle Home directories.
OH=`egrep -i ":Y|:N" $ORATAB | grep -v "^#" | grep -v "\*" | cut -d":" -f2 | sort | uniq`# Exit if there are not Oracle Home directories.
if [ -z "$OH" ]; thenecho "No Oracle Home directories to clean."exit $SUCCESS
fi# Get the list of running databases.
SIDS=`ps -e -o args | grep pmon | grep -v grep | awk -F_ '{print $3}' | sort`# Gather information for each running database.
for ORACLE_SID in `echo $SIDS`
do# Set the Oracle environment.ORAENV_ASK=NOexport ORACLE_SID. $ORAENVif [ $? -ne 0 ]; thenecho "Could not set Oracle environment for $ORACLE_SID."elseexport LD_LIBRARY_PATH=$ORACLE_HOME/lib:$ORIGLDORAENV_ASK=YESecho "ORACLE_SID: $ORACLE_SID"# Get the audit_dump_dest.ADUMPDEST=`f_getparameter audit_dump_dest`if [ ! -z "$ADUMPDEST" ] && [ -d "$ADUMPDEST" 2>/dev/null ]; thenecho " Audit Dump Dest: $ADUMPDEST"ADUMPDIRS="$ADUMPDIRS $ADUMPDEST"fi# Get the background_dump_dest.BDUMPDEST=`f_getparameter background_dump_dest`echo " Background Dump Dest: $BDUMPDEST"if [ ! -z "$BDUMPDEST" ] && [ -d "$BDUMPDEST" ]; thenBDUMPDIRS="$BDUMPDIRS $BDUMPDEST"fi# Get the core_dump_dest.CDUMPDEST=`f_getparameter core_dump_dest`echo " Core Dump Dest: $CDUMPDEST"if [ ! -z "$CDUMPDEST" ] && [ -d "$CDUMPDEST" ]; thenCDUMPDIRS="$CDUMPDIRS $CDUMPDEST"fi# Get the user_dump_dest.UDUMPDEST=`f_getparameter user_dump_dest`echo " User Dump Dest: $UDUMPDEST"if [ ! -z "$UDUMPDEST" ] && [ -d "$UDUMPDEST" ]; thenUDUMPDIRS="$UDUMPDIRS $UDUMPDEST"fifi
done# Do cleanup for each Oracle Home.
for ORAHOME in `f_getuniq "$OH"`
do# Get the standard audit directory if present.if [ -d $ORAHOME/rdbms/audit ]; thenADUMPDIRS="$ADUMPDIRS $ORAHOME/rdbms/audit"fi# Get the Cluster Ready Services Daemon (crsd) log directory if present.if [ -d $ORAHOME/log/$HOSTNAME/crsd ]; thenCRSLOGDIRS="$CRSLOGDIRS $ORAHOME/log/$HOSTNAME/crsd"fi# Get the Oracle Cluster Registry (OCR) log directory if present.if [ -d $ORAHOME/log/$HOSTNAME/client ]; thenOCRLOGDIRS="$OCRLOGDIRS $ORAHOME/log/$HOSTNAME/client"fi# Get the Cluster Synchronization Services (CSS) log directory if present.if [ -d $ORAHOME/log/$HOSTNAME/cssd ]; thenCSSLOGDIRS="$CSSLOGDIRS $ORAHOME/log/$HOSTNAME/cssd"fi# Get the Event Manager (EVM) log directory if present.if [ -d $ORAHOME/log/$HOSTNAME/evmd ]; thenEVMLOGDIRS="$EVMLOGDIRS $ORAHOME/log/$HOSTNAME/evmd"fi# Get the RACG log directory if present.if [ -d $ORAHOME/log/$HOSTNAME/racg ]; thenRACGLOGDIRS="$RACGLOGDIRS $ORAHOME/log/$HOSTNAME/racg"fidone# Clean the audit_dump_dest directories.
if [ ! -z "$ADUMPDIRS" ]; thenfor DIR in `f_getuniq "$ADUMPDIRS"`; doif [ -d $DIR ]; thenecho "Cleaning Audit Dump Directory: $DIR"find $DIR -type f -name "*.aud" -mtime +$ADAYS -exec $RM {} \; 2>/dev/nullfidone
fi# Clean the background_dump_dest directories.
if [ ! -z "$BDUMPDIRS" ]; thenfor DIR in `f_getuniq "$BDUMPDIRS"`; doif [ -d $DIR ]; thenecho "Cleaning Background Dump Destination Directory: $DIR"# Clean up old trace files.find $DIR -type f -name "*.tr[c,m]" -mtime +$BDAYS -exec $RM {} \; 2>/dev/nullfind $DIR -type d -name "cdmp*" -mtime +$BDAYS -exec $RMDIR {} \; 2>/dev/nullfiif [ -d $DIR ]; then# Cut the alert log and clean old ones.for f in `find $DIR -type f -name "alert\_*.log" ! -name "alert_[0-9A-Z]*.[0-9]*.log" 2>/dev/null`; doecho "Alert Log: $f"f_cutlog $ff_deletelog $f $BDAYSdonefidone
fi# Clean the core_dump_dest directories.
if [ ! -z "$CDUMPDIRS" ]; thenfor DIR in `f_getuniq "$CDUMPDIRS"`; doif [ -d $DIR ]; thenecho "Cleaning Core Dump Destination: $DIR"find $DIR -type d -name "core*" -mtime +$CDAYS -exec $RMDIR {} \; 2>/dev/nullfidone
fi# Clean the user_dump_dest directories.
if [ ! -z "$UDUMPDIRS" ]; thenfor DIR in `f_getuniq "$UDUMPDIRS"`; doif [ -d $DIR ]; thenecho "Cleaning User Dump Destination: $DIR"find $DIR -type f -name "*.trc" -mtime +$UDAYS -exec $RM {} \; 2>/dev/nullfidone
fi# Cluster Ready Services Daemon (crsd) Log Files
for DIR in `f_getuniq "$CRSLOGDIRS $OCRLOGDIRS $CSSLOGDIRS $EVMLOGDIRS $RACGLOGDIRS"`; doif [ -d $DIR ]; thenecho "Cleaning Clusterware Directory: $DIR"find $DIR -type f -name "*.log" -mtime +$RDAYS -exec $RM {} \; 2>/dev/nullfi
done# Clean Listener Log Files.
# Get the list of running listeners. It is assumed that if the listener is not running, the log file does not need to be cut.
ps -e -o args | grep tnslsnr | grep -v grep | while read LSNR; do# Derive the lsnrctl path from the tnslsnr process path.TNSLSNR=`echo $LSNR | awk '{print $1}'`ORACLE_PATH=`dirname $TNSLSNR`ORACLE_HOME=`dirname $ORACLE_PATH`PATH=$ORACLE_PATH:$ORIGPATHLD_LIBRARY_PATH=$ORACLE_HOME/lib:$ORIGLDLSNRCTL=$ORACLE_PATH/lsnrctlecho "Listener Control Command: $LSNRCTL"# Derive the listener name from the running process.LSNRNAME=`echo $LSNR | awk '{print $2}' | tr "[:upper:]" "[:lower:]"`echo "Listener Name: $LSNRNAME"# Get the listener version.LSNRVER=`$LSNRCTL version | grep "LSNRCTL" | grep "Version" | awk '{print $5}' | awk -F. '{print $1}'`echo "Listener Version: $LSNRVER"# Get the TNS_ADMIN variable.echo "Initial TNS_ADMIN: $TNS_ADMIN"unset TNS_ADMINTNS_ADMIN=`$LSNRCTL status $LSNRNAME | grep "Listener Parameter File" | awk '{print $4}'`if [ ! -z $TNS_ADMIN ]; thenexport TNS_ADMIN=`dirname $TNS_ADMIN`elseexport TNS_ADMIN=$ORACLE_HOME/network/adminfiecho "Network Admin Directory: $TNS_ADMIN"# If the listener is 11g, get the diagnostic dest, etc...if [ $LSNRVER -ge 11 ]; then# Get the listener log file directory. LSNRDIAG=`$LSNRCTL<<EOF | grep log_directory | awk '{print $6}'
set current_listener $LSNRNAME
show log_directory
EOF`echo "Listener Diagnostic Directory: $LSNRDIAG"# Get the listener trace file name.LSNRLOG=`lsnrctl<<EOF | grep trc_directory | awk '{print $6"/"$1".log"}'
set current_listener $LSNRNAME
show trc_directory
EOF`echo "Listener Log File: $LSNRLOG"# If 10g or lower, do not use diagnostic dest.else# Get the listener log file location.LSNRLOG=`$LSNRCTL status $LSNRNAME | grep "Listener Log File" | awk '{print $4}'`fi# See if the listener is logging.if [ -z "$LSNRLOG" ]; thenecho "Listener Logging is OFF. Not rotating the listener log."# See if the listener log exists.elif [ ! -r "$LSNRLOG" ]; thenecho "Listener Log Does Not Exist: $LSNRLOG"# See if the listener log has been cut today.elif [ -f $LSNRLOG.$TODAY ]; thenecho "Listener Log Already Cut Today: $LSNRLOG.$TODAY"# Cut the listener log if the previous two conditions were not met.else# Remove old 11g+ listener log XML files.if [ ! -z "$LSNRDIAG" ] && [ -d "$LSNRDIAG" ]; thenecho "Cleaning Listener Diagnostic Dest: $LSNRDIAG"find $LSNRDIAG -type f -name "log\_[0-9]*.xml" -mtime +$NDAYS -exec $RM {} \; 2>/dev/nullfi# Disable logging.$LSNRCTL <<EOF
set current_listener $LSNRNAME
set log_status off
EOF# Cut the listener log file.f_cutlog $LSNRLOG# Enable logging.$LSNRCTL <<EOF
set current_listener $LSNRNAME
set log_status on
EOF# Delete old listener logs.f_deletelog $LSNRLOG $NDAYSfi
doneecho "`basename $0` Finished `date`."exit
在crontab中设置一个作业,每天晚上凌晨零点运行这个脚本,日志文件保留31天。
00 00 * * * /home/oracle/_cron/cls_oracle/cls_oracle.sh -d 31 > /home/oracle/_cron/cls_oracle/cls_oracle.sh.log 2>&1
统计不同IP连接的次数
cat listener.log | grep -v service_update | grep "12-JAN-2022 16:5" | grep -v status|grep -v ping | awk -F\HOST= '{print $3}' | awk -F\) '{print $1}' | awk '{count[$1" ---"]++}END{for(i in count)print i,count[i]}'
按照时间统计不同IP的连接次数
cat listener.log | grep -v service_update | grep "28-DEC-2021 17:2"|grep -v status|grep -v ping |awk -F\HOST= '{print $3}' | awk -F\) '{print $1}'|awk '{count[$1" ---"]++}END{for(i in count)print i,count[i]}'cat listener.log | grep -v service_update | grep "24-JAN-2022 13:" | grep -v status|grep -v ping |awk -F'[() ]' '{print $1" "$2"\t"$24}'|awk -F'HOST=' '{print $1 $2}'
过滤监听日志。看每分钟连了多少次
time=59
date="25-JAN-2022 14:"
ip=10.25.50.
for i in `seq $time`
do
num=`printf "%02d\n" $i`
result=`cat listener.log | grep "$date$num" | grep $ip | wc -l`
echo "$date:$num ($ip) count : $result"
done
每个ip在指定时间段的连接次数
cat listener.log | grep -v service_update | grep "25-JAN-2022 12:1" | grep -v status|grep -v ping | awk -F\HOST= '{print $3}' | awk -F\) '{print $1}' | awk '{count[$1" ---"]++}END{for(i in count)print i,count[i]}'
10分钟内的连接次数
查看连接失败的用户信息
aud$视图可以查出登录失败的时间、客户端等信息,
SELECTsessionid,userid,userhost,comment$text,spare1,to_char( ntimestamp#+ 1/3, 'yyyy-mm-dd hh24:mi:ss' )
FROMaud$
WHEREreturncode = 1017
ORDER BYntimestamp# DESC;