Oracle Tips : Use SYS_CONTEXT get Client’s Session Information
Oracle Tips : Use SYS_CONTEXT get Client’s Session Information
Good Morning….ครับ เช้านี้รับชมเกล็ดเล็กๆหลังอาหารเช้าสักหน่อยครับ เป็นเรื่องเบาๆที่มีประโยชน์ทั้งผู้ดูแลระบบฐานข้อมูล และผู้พัฒนาโปรแกรม โดยจะเน้นเรื่อง security หน่อย
โดยปกติเมื่อ client เข้ามาใช้บริการ server จะมีการสร้าง session เชื่อมต่อเข้ามา แม้ว่าจะเป็น client เดิมแต่ถ้าเปิดโปรแกรมเชื่อมต่อมาใหม่อย่างเช่น sqlplus เปิดหน้าต่างใหม่ server ก็จะสร้าง session ใหม่รองรับเสมอ
คราวนี้ถ้าเราอยากจะเก็บข้อมูลสถิติการเข้ามาใช้บริการจาก client บ้างล่ะ ปกติถ้าเป็นโปรแกรมเมอร์ก็สามารถใช้ appl. function อย่าง get_session() เป็นต้น แต่ถ้าเป็น DBA เราก็สามารถทำได้เช่นเดียวกันครับ เพราะ Oracle เตรียมฟังก์ชันให้เราเหมือนกัน ฟังก์ชันนี้คือ “SYS_CONTEXT” มีรูปแบบดังนี้
SELECT SYS_CONTEXT(‘<namespace>‘,’<parameter>‘, [<length>]) FROM DUAL; |
โดย <namespace> ในที่นี้จะกำหนดด้วย ‘USERENV’
<parameter> ในที่นี้จะยกตัวอย่างที่ใช่บ่อยๆครับ (โดยรายละเอียดสามารถเพิ่มเติมได้ที่ http://www.psoug.org/reference/sys_context.html?)
Parameter |
Explanation |
Return Length |
DB_NAME | Name of the database from the DB_NAME initialization parameter |
30 |
CURRENT_USERID | Userid of the current user |
30 |
CURRENT_USER | Name of the current user |
30 |
HOST | Name of the host machine from which the client has connected |
54 |
INSTANCE | The identifier number of the current instance |
30 |
IP_ADDRESS | IP address of the machine from which the client has connected |
30 |
ISDBA | Returns TRUE if the user has DBA privileges. Otherwise, it will return FALSE. |
30 |
LANG | The ISO abbreviate for the language |
62 |
LANGUAGE | The language, territory, and character of the session. In the following format: language_territory.characterset |
52 |
OS_USER | The OS username for the user logged in |
30 |
SESSION_USER | The database user name of the user logged in |
30 |
SESSION_USERID | The database identifier of the user logged in |
30 |
SESSIONID | The identifier of the auditing session |
30 |
TERMINAL | The OS identifier of the current session |
10 |
ตัวอย่าง??
SQL> SELECT SYS_CONTEXT(‘USERENV’,’IP_ADDRESS’) CLIENT_IP FROM DUAL; CLIENT_IP —————————— 127.0.0.1 |
หรือเราจะเขียน procedure ง่ายๆ ดังนี้
CREATE OR REPLACE PROCEDURE GET_CLIENT_INFO IS V_SESSION_ID VARCHAR2(30); V_IP_ADDRESS VARCHAR2(30); V_USERNAME VARCHAR2(30); V_HOST VARCHAR2(100); V_OS_USER VARCHAR2(100); BEGIN SELECT SYS_CONTEXT(‘USERENV’,’SESSIONID’) INTO V_SESSION_ID FROM DUAL; DBMS_OUTPUT.PUT_LINE(‘SessionID : ‘|| V_SESSION_ID); END; |
ลองทดสอบ procedure ดูครับ
SQL> set serveroutput on SQL> exec get_client_info; SessionID : 404 PL/SQL procedure successfully completed. |
เป็นยังไงครับสะดวกดีใช่มั้ยครับ เราสามารถประยุกต์เอาไปใช้ในการเก็บ audit log ได้ครับ
สนับสนุนบทความ โดย วลัญช์ ครองสัตย์