[oracle] How can I kill all sessions connecting to my oracle database?

I need to quickly (and forcibly) kill off all external sessions connecting to my oracle database without the supervision of and administrator.

I don't want to just lock the database and let the users quit gracefully.

How would I script this?

This question is related to oracle session sqlplus kill database-administration

The answer is


If Oracle is running in Unix /Linux then we can grep for all client connections and kill it

grep all oracle client process:

ps -ef | grep LOCAL=NO | grep -v grep | awk '{print $2}' | wc -l

Kill all oracle client process :

kill -9 ps -ef | grep LOCAL=NO | grep -v grep | awk '{print $2}'


To answer the question asked, here is the most accurate SQL to accomplish the job, you can combine it with PL/SQL loop to actually run kill statements:

select ses.USERNAME,
    substr(MACHINE,1,10) as MACHINE, 
    substr(module,1,25) as module,
    status, 
    'alter system kill session '''||SID||','||ses.SERIAL#||''';' as kill
from v$session ses LEFT OUTER JOIN v$process p ON (ses.paddr=p.addr)
where schemaname <> 'SYS'
    and not exists
    (select 1 
        from DBA_ROLE_PRIVS 
        where GRANTED_ROLE='DBA' 
            and schemaname=grantee)
    and machine!='yourlocalhostname' 
order by LAST_CALL_ET desc;

I've been using something like this for a while to kill my sessions on a shared server. The first line of the 'where' can be removed to kill all non 'sys' sessions:

BEGIN
  FOR c IN (
      SELECT s.sid, s.serial#
      FROM v$session s
      WHERE (s.Osuser = 'MyUser' or s.MACHINE = 'MyNtDomain\MyMachineName')
      AND s.USERNAME <> 'SYS'
      AND s.STATUS <> 'KILLED'
  )
  LOOP
      EXECUTE IMMEDIATE 'alter system kill session ''' || c.sid || ',' || c.serial# || '''';
  END LOOP;
END;

If you want to stop new users from connecting, but allow current sessions to continue until they are inactive, you can put the database in QUIESCE mode:

ALTER SYSTEM QUIESCE RESTRICTED;

From the Oracle Database Administrator's Guide:

Non-DBA active sessions will continue until they become inactive. An active session is one that is currently inside of a transaction, a query, a fetch, or a PL/SQL statement; or a session that is currently holding any shared resources (for example, enqueues). No inactive sessions are allowed to become active...Once all non-DBA sessions become inactive, the ALTER SYSTEM QUIESCE RESTRICTED statement completes, and the database is in a quiesced state


Try trigger on logon

Insted of trying disconnect users you should not allow them to connect.

There is and example of such trigger.

CREATE OR REPLACE TRIGGER rds_logon_trigger
AFTER LOGON ON DATABASE
BEGIN
  IF SYS_CONTEXT('USERENV','IP_ADDRESS') not in ('192.168.2.121','192.168.2.123','192.168.2.233') THEN
    RAISE_APPLICATION_ERROR(-20003,'You are not allowed to connect to the database');
  END IF;

  IF (to_number(to_char(sysdate,'HH24'))< 6) and (to_number(to_char(sysdate,'HH24')) >18) THEN
    RAISE_APPLICATION_ERROR(-20005,'Logon only allowed during business hours');
  END IF;

END;

I found the below snippet helpful. Taken from: http://jeromeblog-jerome.blogspot.com/2007/10/how-to-unlock-record-on-oracle.html

select
owner||'.'||object_name obj ,
oracle_username||' ('||s.status||')' oruser ,
os_user_name osuser ,
machine computer ,
l.process unix ,
s.sid||','||s.serial# ss ,
r.name rs ,
to_char(s.logon_time,'yyyy/mm/dd hh24:mi:ss') time
from v$locked_object l ,
dba_objects o ,
v$session s ,
v$transaction t ,
v$rollname r
where l.object_id = o.object_id
and s.sid=l.session_id
and s.taddr=t.addr
and t.xidusn=r.usn
order by osuser, ss, obj
;

Then ran:

Alter System Kill Session '<value from ss above>'
;

To kill individual sessions.


As SYS:

startup force;

Brutal, yet elegant.


Before killing sessions, if possible do

ALTER SYSTEM ENABLE RESTRICTED SESSION;

to stop new sessions from connecting.


Additional info

Important Oracle 11g changes to alter session kill session

Oracle author Mladen Gogala notes that an @ sign is now required to kill a session when using the inst_id column:

alter system kill session '130,620,@1';

http://www.dba-oracle.com/tips_killing_oracle_sessions.htm


Examples related to oracle

concat yesterdays date with a specific time ORA-28001: The password has expired how to modify the size of a column How to create a blank/empty column with SELECT query in oracle? Find the number of employees in each department - SQL Oracle Query to display all tablespaces in a database and datafiles When or Why to use a "SET DEFINE OFF" in Oracle Database How to insert date values into table error: ORA-65096: invalid common user or role name in oracle In Oracle SQL: How do you insert the current date + time into a table?

Examples related to session

What is the best way to manage a user's session in React? Spring Boot Java Config Set Session Timeout PHP Unset Session Variable How to kill all active and inactive oracle sessions for user Difference between request.getSession() and request.getSession(true) PHP - Session destroy after closing browser Get Current Session Value in JavaScript? Invalidating JSON Web Tokens How to fix org.hibernate.LazyInitializationException - could not initialize proxy - no Session How can I get session id in php and show it?

Examples related to sqlplus

When or Why to use a "SET DEFINE OFF" in Oracle Database SQLPLUS error:ORA-12504: TNS:listener was not given the SERVICE_NAME in CONNECT_DATA sqlplus: error while loading shared libraries: libsqlplus.so: cannot open shared object file: No such file or directory How do I resolve this "ORA-01109: database not open" error? How to echo text during SQL script execution in SQLPLUS PL/SQL ORA-01422: exact fetch returns more than requested number of rows how to pass variable from shell script to sqlplus Connect to Oracle DB using sqlplus sqlplus how to find details of the currently connected database session How to output oracle sql result into a file in windows?

Examples related to kill

How to kill a nodejs process in Linux? What does 'killed' mean when a processing of a huge CSV with Python, which suddenly stops? how to kill hadoop jobs Why number 9 in kill -9 command in unix? How to kill a process on a port on ubuntu How to kill a child process by the parent process? How to kill all processes matching a name? How do I kill an Activity when the Back button is pressed? Terminating idle mysql connections How can I stop a running MySQL query?

Examples related to database-administration

How do I resolve this "ORA-01109: database not open" error? ORA-12528: TNS Listener: all appropriate instances are blocking new connections. Instance "CLRExtProc", status UNKNOWN extract date only from given timestamp in oracle sql Find out the history of SQL queries Frontend tool to manage H2 database How to replace a string in a SQL Server Table Column How can I kill all sessions connecting to my oracle database?