পৃষ্ঠাসমূহ

এই ব্লগটি সন্ধান করুন

রবিবার, ২৪ সেপ্টেম্বর, ২০১৭

Ubuntu Port Open Process

Once you have installed an OpenSSH server, 
sudo apt-get install openssh-server
you will need to configure it by editing the sshd_config file in the /etc/sshdirectory.
IconsPage/tip.png
sshd_config is the configuration file for the OpenSSH serverssh_config is the configuration file for the OpenSSH client. Make sure not to get them mixed up.
First, make a backup of your sshd_config file by copying it to your home directory, or by making a read-only copy in /etc/ssh by doing:
sudo cp /etc/ssh/sshd_config /etc/ssh/sshd_config.factory-defaults
sudo chmod a-w /etc/ssh/sshd_config.factory-defaults
Creating a read-only backup in /etc/ssh means you'll always be able to find a known-good configuration when you need it.
Once you've backed up your sshd_config file, you can make changes with any text editor, for example; 
sudo gedit /etc/ssh/sshd_config
runs the standard text editor in Ubuntu 12.04 or more recent. For older versions replace "sudo" with "gksudo". Once you've made your changes (see the suggestions in the rest of this page), you can apply them by saving the file then doing:
sudo restart ssh
If you get the error, "Unable to connect to Upstart", restart ssh with the following:
sudo systemctl restart ssh

Configuring OpenSSH means striking a balance between security and ease-of-use. Ubuntu's default configuration tries to be as secure as possible without making it impossible to use in common use cases. This page discusses some changes you can make, and how they affect the balance between security and ease-of-use. When reading each section, you should decide what balance is right for your specific situation.

Short Cut Key - MS Office, Excel, Browser, Linux etc


















Oracle Date Calculation Technique

Description
Date Expression
Now
SYSDATE
Tomorow/ next day
SYSDATE + 1
Seven days from now
SYSDATE + 7
One hour from now
SYSDATE + 1/24
Three hours from now
SYSDATE + 3/24
A half hour from now
SYSDATE + 1/48
10 minutes from now
SYSDATE + 10/1440
30 seconds from now
SYSDATE + 30/86400
Tomorrow at 12 midnight
TRUNC(SYSDATE + 1)
Tomorrow at 8 AM
TRUNC(SYSDATE + 1) + 8/24
Next Monday at 12:00 noon
NEXT_DAY(TRUNC(SYSDATE), 'MONDAY') + 12/24
First day of the month at 12 midnight
TRUNC(LAST_DAY(SYSDATE ) + 1)
The next Monday, Wednesday or Friday at 9 a.m
TRUNC(LEAST(NEXT_DAY(sysdate, 'MONDAY'), NEXT_DAY(sysdate, 'WEDNESDAY'), NEXT_DAY(sysdate, 'FRIDAY'))) + 9/24

ORA-12899: value too large for column "SCHEME". "TABLE". "ROW" (actual: 51, maximum: 50)


Error: Error occurred when Oracle database import.


Column 12 LA APLICACION EN ESPA?A DEL CONVENIO DE LA HAYA DE...
IMP-00019: row Rejected due to Oracle error 12899
IMP-00003: ORACLE Error 12899 Encountered
ORA-12899: value too large for column "SCHEME". "TABLE". "ROW" (actual: 51, maximum: 50)

Solution:
It means source db and target db char set not same. Target table data type may be used as byte (which every special character consider two byte). It should be char. Flow the below process for solution.
Table definitions
Import only the definitions of the tables, no the rows
SQL> impdp system/password schemas=SCOTT directory=MY_BCK dumpfile=SCOTT.dmp logfile=impdpSCOTT.log content=metadata_only

SQL> imp system/password fromuser=SCOTT touser=SCOTT file=/u01/app/oracle/bck/SCOTT.dmp log=/u01/app/oracle/bck/expdpSCOTT.log ignore=Y ROWS=N


CHAR conversion

 

To facilitate this process, Oracle created this script. You only need to edit the name of your scheme:

Conn / as sysdba
set feedback off
set verify off
set serveroutput on
set termout on
exec dbms_output.put_line('Starting build select of columns to be altered');
drop table semantics$
/
create table semantics$(s_owner varchar2(40),
s_table_name varchar2(40),
s_column_name varchar2(40),
s_data_type varchar2(40),
s_char_length number)
/
insert into semantics$
select C.owner, C.table_name, C.column_name, C.data_type, C.char_length
from all_tab_columns C, all_tables T
where C.owner = T.owner
and T.owner in
('SCOTT')
-- All Oracle provided users
and C.table_name = T.table_name
and C.char_used = 'B'
-- only need to look for tables who are not yet CHAR semantics.
and T.partitioned != 'YES'
-- exclude partitioned tables
and C.table_name not in (select table_name from all_external_tables)
and C.data_type in ('VARCHAR2', 'CHAR')
-- You can exclude or include tables or shema's as you wish, by adjusting
-- "and T.owner not in" as per your requirements
/
commit
/
declare
cursor c1 is select * from semantics$;
v_statement varchar2(255);
v_nc number(10);
v_nt number(10);
begin
execute immediate
'select count(*) from semantics$' into v_nc;
execute immediate
'select count(distinct s_table_name) from semantics$' into v_nt;
dbms_output.put_line
('ALTERing ' || v_nc || ' columns in ' || v_nt || ' tables');
for r1 in c1 loop
v_statement := 'ALTER TABLE ' || r1.s_owner || '.' || r1.s_table_name;
v_statement := v_statement || ' modify (' || r1.s_column_name || ' ';
v_statement := v_statement || r1.s_data_type || '(' || r1.s_char_length;
v_statement := v_statement || ' CHAR))';
execute immediate v_statement;
end loop;
dbms_output.put_line('Done');
end;
/


Recompile the scheme to validate dependent objects:
SQL> EXECUTE UTL_RECOMP.RECOMP_PARALLEL(4);



Import Data


To finish importing the data scheme
SQL> impdp system/password schemas=SCOTT directory=MY_BCK dumpfile=SCOTT.dmp logfile=impdpSCOTT.log
 
SQL> imp system/password fromuser=SCOTT touser=SCOTT file=/u01/app/oracle/bck/SCOTT.dmp 


Another way:

Oracle: ORA-12899: value too large for column during imp from WE8MSWIN1252 to AL32UTF8

During migration/import from 9i(WE8ISO8859P1) to 11g(AL32UTF8), the import process crash because the special characters
during the conversion pass from one byte to two bytes:


IMP-00019: row Rejected due to Oracle error 12899
IMP-00003: ORACLE Error 12899 Encountered
ORA-12899: value too large for column "SCHEME". "TABLE". "ROW" (actual: 51, maximum: 50)


1- Export the schema you want to move:
exp system/password file=filename.dmp log=logfile.log owner=schemaname

2- Import only the table definitions into the new database, without inserting the rows (ROWS=N import)
imp system/password file=filename.dmp log=logfile.log rows=n fromuser=schemaname touser=schemaname

3- Converts columns to CHAR length semantics:
Follwoing query generate the scripts to change the CHAR length semantics

select 'ALTER TABLE ' || t.owner || '.' || c.table_name||' modify (' || c.column_name ||' '||c.data_type || '(' || c.char_length||' CHAR));'
from all_tab_columns C, all_tables T
where C.owner = T.owner
and T.owner in ('TEST1')
and C.table_name = T.table_name
and C.char_used = 'B'
-- only need to look for tables who are not yet CHAR semantics.
and T.partitioned != 'YES'
-- exclude partitioned tables
and C.table_name not in (select table_name from all_external_tables)
and C.data_type in ('VARCHAR2', 'CHAR');

After getting the scripts execute it on the new imported schema.  


4- Import the full schema with data now
imp system/password file=filename.dmp log=logfile.log fromuser=schemaname touser=schemaname



Oracle Database Link Practical

CREATE DATABASE LINK appstst1 CONNECT TO newasymodel IDENTIFIED BY secl2015 using
' (DESCRIPTION =
    (ADDRESS = (PROTOCOL = TCP)(HOST = 192.168.0.224)(PORT = 1521))
    (CONNECT_DATA =
      (SERVER = DEDICATED)
      (SERVICE_NAME = orcl)
    )
  )
';

CREATE DATABASE LINK test2 CONNECT TO dblnk IDENTIFIED BY dblnk123 using
'(DESCRIPTION =
    (ADDRESS = (PROTOCOL = TCP)(HOST = 192.168.5.133)(PORT = 1521))
    (CONNECT_DATA =
      (SERVER = DEDICATED)
      (SERVICE_NAME = orcl)
    )
  )';
 
  Select * from ap_test@ test2;  
select * from sad_gen@ appstst1;
Select * from all_db_link;
drop DATABASE LINK appstst3;

Send SMS Procedure in Oracle

CREATE OR REPLACE PROCEDURE sendSMSBD
  ( pRecipient IN VARCHAR2
  , pText      IN VARCHAR2
  )
IS
    NowSMS_USERNAME CONSTANT VARCHAR2(40) := '01722623382';
    NowSMS_PASSWORD CONSTANT VARCHAR2(40) := '*******';
    NowSMS_SENDER   CONSTANT VARCHAR2(40) := '';  /* set sender address if needed */
    NowSMS_SERVER   CONSTANT VARCHAR2(80) := 'https://panel.onnorokomsms.com/Client/SendSms/SendSms';  /* NowSMS server address */
    --
    vRequest      Utl_Http.req;
    vPostText     VARCHAR2(500);
    vResponse     Utl_Http.resp;
    vResponseText VARCHAR2(2000);
    vErrorText    VARCHAR2(200);
BEGIN
    ----------------------------------------------------------------------------
    -- Build text for the post action.
    -- For a field description, see
    -- http://www.nowsms.com/doc/submitting-sms-messages/url-parameters
    ----------------------------------------------------------------------------
    vPostText :=
      'User='           ||Utl_Url.escape(NowSMS_USERNAME, TRUE)||CHR(38)||
      'Password='       ||Utl_Url.escape(NowSMS_PASSWORD, TRUE)||CHR(38)||
      'Sender='         ||Utl_Url.escape(NowSMS_SENDER,  TRUE)||CHR(38)||
      'PhoneNumber='    ||Utl_Url.escape(pRecipient,       TRUE)||CHR(38)||
      'Text='           ||Utl_Url.escape(pText,            TRUE);
    ----------------------------------------------------------------------------
    -- Send SMS through the NowSMS SMS service.
    ----------------------------------------------------------------------------
    vRequest := Utl_Http.begin_request
                  ( url    => NowSMS_SERVER
                  , method => 'POST'
                  );
    Utl_Http.set_header
      ( r     => vRequest
      , name  => 'Content-Type'
      , value => 'application/x-www-form-urlencoded'
      );
    Utl_Http.set_header
      ( r     => vRequest
      , name  => 'Content-Length'
      , value => LENGTH(vPostText)
      );
    Utl_Http.write_text
      ( r    => vRequest
      , data => vPostText
      );
    vResponse := Utl_Http.get_response(vRequest);
    IF vResponse.status_code = '200'
    THEN
        Utl_Http.read_text(vResponse, vResponseText);
        --
        IF vResponseText NOT LIKE '%MessageID=%'
        THEN
            vErrorText := vResponseText;
        END IF;
    ELSE
        vErrorText := 'HTTP status: '||vResponse.status_code||'-'||vResponse.reason_phrase;
    END IF;
    --
    Utl_Http.end_response(vResponse);
    --
    IF vErrorText IS NOT NULL
    THEN
        RAISE_APPLICATION_ERROR(-20001, 'Sending SMS failed with '||vErrorText);
    END IF;
END sendSMSBD;



BEGIN
    sendSMSBD('+8801722623382','this is a test from Imam by using NowSMS');
END;

Send Mail Oracle Procedure

create or replace PROCEDURE "SEND_MAIL" (p_from       IN VARCHAR2,
                       p_to IN VARCHAR2,
                       p_cc IN VARCHAR2,
                       p_subject IN VARCHAR2,
                       p_message   IN VARCHAR2,
                       argUserId IN VARCHAR2 DEFAULT NULL,
                       p_returnReceipt IN CHAR DEFAULT 'N',
                       p_dispositionNotification IN CHAR DEFAULT 'N'
)
  as

  -- 6.1.0: Aspire #29648 - Added UserID, returnReceipt and dispositionNotification arguments to support acknowledgement mail in Messaging Service

     l_mailhost VarChar2(255);
     l_mail_conn utl_smtp.connection;
     crlf char(2) := chr(13)||chr(10);
     msg_data VarChar2(4000);
     p_recipient varChar2(4000);
     p_recipients varChar2(4000);
     l_EaiURL VarChar2(255);
     l_EaiUserid VarChar2(128);
     l_EaiPassword VarChar2(128);
     l_EaiEmailSaveFlag VarChar2(3);
     xml VarChar2(4000);
     result VarChar2(4000);
     l_returnRecipient VarChar2(255);  -- Aspire #29648 - Added l_returnRecipient variable to store the email notification type
  BEGIN
     SELECT  EmailHost,   EaiURL
       INTO l_mailhost, l_EaiURL
       FROM ValidSite;

     IF (l_mailhost > ' ') THEN
/* Setting the Email Header for Email Notification in msgdata */
        IF (p_dispositionNotification = 'Y') THEN
IF (p_returnReceipt = 'Y') THEN
l_returnRecipient := 'Return_Receipt_To: ' || p_from || crlf ||
                           'Disposition_Notification_To: ' || p_from || crlf;
ELSE
l_returnRecipient := 'Disposition_Notification_To: ' || p_from || crlf;
END IF;
ELSIF(p_returnReceipt = 'Y') THEN
l_returnRecipient := 'Return_Receipt_To: ' || p_from || crlf;
END IF;


        msg_data:= 'Date: ' || TO_CHAR( SYSDATE, 'dd Mon yy hh24:mi:ss' ) || crlf ||
                   'From:  <'|| p_from ||'>' || crlf ||
                   'Subject: '|| nvl( p_subject, '(no subject)' ) || crlf ||
                   'To: '|| p_to || crlf ||
                   'Cc: '|| p_cc || crlf ||
                   l_returnRecipient ||
                   '' || crlf || p_message;
        l_mail_conn := utl_smtp.open_connection(l_mailhost, 25);
        utl_smtp.helo(l_mail_conn, l_mailhost);
        utl_smtp.mail(l_mail_conn, p_from);
        p_recipients := p_to;
        WHILE ( p_recipients > ' ' ) LOOP
           IF (instr(p_recipients , ';') > 0) THEN
              p_recipient := substr(p_recipients , 1, instr(p_recipients , ';') - 1);
              p_recipients  := substr(p_recipients , instr(p_recipients , ';') + 1);
           ELSE
              p_recipient := p_recipients ;
              p_recipients  := ' ';
           END IF;
           utl_smtp.rcpt(l_mail_conn, p_recipient );
        END LOOP;
        p_recipients := p_cc;
        WHILE ( p_recipients > ' ' ) LOOP
           IF (instr(p_recipients , ';') > 0) THEN
              p_recipient := substr(p_recipients , 1, instr(p_recipients , ';') - 1);
              p_recipients  := substr(p_recipients , instr(p_recipients , ';') + 1);
           ELSE
              p_recipient := p_recipients ;
              p_recipients  := ' ';
           END IF;
           utl_smtp.rcpt(l_mail_conn, p_recipient );
        END LOOP;
        utl_smtp.data(l_mail_conn, msg_data);
        utl_smtp.quit(l_mail_conn);
     ELSE
/* changed the mail Sending throght EAI Since we implemented Sending mail thorugh Messaging Service */
           xml :=  '<Command>'
                || ' <Email>'
                || '  <To>' || p_to || '</To>'
                || '  <From>' || p_from || '</From>'
                || '  <CC>' || p_cc || '</CC>'
                || '  <Subject>' || p_subject || '</Subject>'
                || '  <Body>' || p_message || '</Body>'
                || '  <ReturnReceipt>' || p_returnReceipt || '</ReturnReceipt>'
                || '  <DispositionNotification>' || p_dispositionNotification || '</DispositionNotification>'
                || ' </Email>'
                || '</Command>';

        /* Insert the xml into Message table */
        INSERT INTO Message (MessageRSN, CommandXml, StatusCode, StampDate, StampUser)
        VALUES(MessageSeq.NextVal, xml, 0, SYSDATE, argUserId);
     END IF;
 end;

Manual Installation of Oracle 11g Release 2 (11.2) for Linux x86-64(RED HAT-6)

Step#. Login as root user
Step#. Execute the following command
1. yum update
2. yum install kernel-uek-devel
3. go to the following locaiton
cd /etc/yum.repos.d/
(This will install the rpm files specificaly in the following location.)
(Please maintain this convention in every rpm download further.)
(Execute the following command.)
wget http://pkgs.repoforge.org/rpmforge-release/rpmforge-release-0.5.3-1.el6.rf.x86_64.rpm
5. rpm -Uvh rpmforge-release-0.5.3-1.el6.rf.x86_64.rpm
cd /etc/yum.repos.d
wget http://public-yum.oracle.com/public-yum-ol6.repo

or oracle linux 5
rpm -Uhv http://apt.sw.be/redhat/el5/en/x86_64/rpmforge/RPMS//rpmforge-release-0.3.6-1.el5.rf.x86_64.rpm


Step#. Create User Group and Set Password
/usr/sbin/groupadd oinstall
/usr/sbin/groupadd dba
/usr/sbin/groupadd oper
/usr/sbin/useradd -g oinstall -G dba,oper oracle
/usr/bin/passwd oracle

Step#. Directory Create.
Go to root Directory
mkdir -p oracleinstallations
chown -R oracle:oinstall /oracleinstallations
chmod -R 0775 /oracleinstallations
mkdir -p /home/oracle/app/oracle/product/11.2.0/db_1
chown -R oracle:oinstall /home/oracle
chmod -R 0775 /home/oracle

Step#.  Copy Oracle11gR2-11.2.0.1-Linux-x86-64 installation file to oracleinstallations
Step#. Execute
chown -R oracle:oinstall /oracleinstallations
chmod -R 0775 /oracleinstallations

Step#.First we need to check up System Configurations which required for Oracle installation

-- Check Physical RAM. We need at least 1GB of physical RAM. In my case I have 2GB.
# grep MemTotal /proc/meminfo
output: MemTotal:      2075424 kB

-- Check Swap Space.
RAM between 1GB and 2GB then Swap = 1.5 times the size of RAM
RAM between 2GB and 16GB then Swap = equal to the size of RAM
RAM more than 16GB then Swap Size = 16GB
Since my RAM is 2GB, so I have 3GB of Swap Size.
# grep SwapTotal /proc/meminfo
output: SwapTotal:     3148732 kB

-- Check Shared Memory Space
What ever you are going to use your Automatic Memory Management
Targets later on this database, you need to have shared memory
file system size at lease equal to those settings. In my case I
have plans to use memory management targets lower then 1000M
so 1014 M of shared memory file system is sufficient for me.
But if you would like to have a bigger shared memory (/dev/shm)
size then do the following:
# df -h /dev/shm/
output: Filesystem            Size  Used Avail Use% Mounted on
       tmpfs                1014M     0 1014M   0% /dev/shm

-- Check space available in /tmp
You need to have at least 1GB of space in the /tmp directory.
Make sure you have 1GB in the column "Avail" in the above output.
In my case I have 1.4G space available in /tmp.
# df -h /tmp
output: Filesystem            Size  Used Avail Use% Mounted on
/dev/sda5             1.5G   35M  1.4G   3% /tmp

Step# Incase if memory extention is required execute the below line, to mount any required memory,
a. mount -t tmpfs tmpfs -o size=1500m /dev/shm
b. df -h /dev/shm/
output: Filesystem            Size  Used Avail Use% Mounted on
tmpfs                 1.5G     0  1.5G   0% /dev/shm

Step#--Check Kernel version (To install Oracle 11g Release 2 on RHEL 5 you should be running a kernel version 2.6.18 or later.)
a. uname -r
output: 2.6.18-194.el5

Step#. Open /etc/pam.d/login and add the following line if it is already not there.
session    required     pam_limits.so

Step#. Go to CD directory/packages and open terminal and execute following command from CD Packages

yum install binutils-* compat-libcap1-* compat-libstdc++-* compat-libstdc++-* gcc-* gcc-c++-* glibc-* glibc-devel-* glibc-devel-* ksh libgcc-* libgcc-* libstdc++-* libstdc++-* libstdc++-devel-* libstdc++-devel-* libaio-* libaio-* libaio-devel-* libaio-devel-* make-* sysstat-* -y



Step#.  Now open the file in edit mode: /etc/hosts
--- Add this following lines
[IP-address]  [fully-qualified-machine-name]  [machine-name]
example: 192.168.0.161 univerge.spectrum-bd.com univerge
/*
Where "fully-qualified-machine-name" is your
"machine_name"."domain_name"
*/

Step#.  Edit the /etc/sysctl.conf file and add the following lines and also need to check if those value is greater than
the given value then no need to change of the variable . kernel.shmmax value is greater then half of Ram size

fs.aio-max-nr = 1048576
fs.file-max = 6815744
kernel.shmall = 2097152
kernel.shmmax = 536870912
kernel.shmmni = 4096
kernel.sem = 250 32000 100 128
net.ipv4.ip_local_port_range = 9000 65500
net.core.rmem_default = 262144
net.core.rmem_max = 4194304
net.core.wmem_default = 262144
net.core.wmem_max = 1048576

-- To update this file
/sbin/sysctl -p

Step#. Edit the /etc/security/limits.conf file and add the following lines
oracle soft nproc 2047
oracle hard nproc 16384
oracle soft nofile 1024
oracle hard nofile 65536
oracle soft stack 10240

Step#. create a file name .oracle. Put the  file into /home/oracle directory.
Write put the following lines :

## Oracle settings
TMP=/tmp; export TMP
TMPDIR=$TMP; export TMPDIR

## If /tmp doesn't have 1G space free then you can workaround it by
# pointing the variables TMP AND TMPDIR to a location where you have
# sufficient space.

ORACLE_HOSTNAME=seclbidw.nbr.com; export ORACLE_HOSTNAME
ORACLE_BASE=/home/oracle/app/oracle; export ORACLE_BASE
ORACLE_HOME=$ORACLE_BASE/product/11.2.0/db_1; export ORACLE_HOME
ORACLE_SID=orcl; export ORACLE_SID
ORACLE_TERM=xterm; export ORACLE_TERM
PATH=$ORACLE_HOME/bin:/usr/bin:$PATH; export PATH

LD_LIBRARY_PATH=$ORACLE_HOME/lib:/lib:/usr/lib;
export LD_LIBRARY_PATH
CLASSPATH=$ORACLE_HOME/JRE:$ORACLE_HOME/jlib:$ORACLE_HOME/rdbms/jlib;
export CLASSPATH

if [ $USER = "oracle" ]; then
   if [ $SHELL = "/bin/ksh" ]; then
ulimit -p 16384
ulimit -n 65536
   else
ulimit -u 16384 -n 65536
   fi
fi

umask 022


Step#. Go to /etc/sysconfig/selinux
update the  SELINUX=disabled in the line.

Step#. System>Administrator>Firewall disable

Step#. System>Administrator>Service ip6tables and iptable disable

Step#. Logout from root user from the system. Login to the system as oracle user
Step#. Go to /home/oracle
execute . .oracle

Step#. Put Oracle Linux installation zip file in oracleinstallations directory.The zip files will be:
linux.x64_11gR2_database_1of2.zip
linux.x64_11gR2_database_2of2.zip

Step#. Unzip these file by following commands one by one.
cd /oracleinstallations
unzip linux.x64_11gR2_database_1of2.zip
unzip linux.x64_11gR2_database_2of2.zip

Step#. To start installation run these following command.
a) cd /oracleinstallations/database
b) ./runInstaller.sh

Step#. find /etc/oratab file and change value equal to Y instead of N
Step#. Go to /home/oracle/app/oracle/product/11.2.0/db_1/dbs and open init.ora file and update processes and open_cursors value is 800(Describe in RCU setup)
Step#. Run Enterprize Manager
a) go to /home/oracle and execute
b) . .oracle
c) dbstart
d) lsnrctl start
e) emctl start dbconsole

Step# To see the dbconsole using mozilla browser go to the following address.
https://127.0.0.1:1158/dbconsole
If you see the dbconsole running and you can login appropriatly. The Db console is installed.

Step#. This is for Oracle DB stop.
a) go to /home/oracle and execute
b) . .oracle
c) emctl stop dbconsole
d) dbshut
e) lsnrctl stop

Oracle DBA Related Important Technique

         Important DBA Script:
========================

====Extended Data Types in Oracle Database 12c Release 1 (12.1) ======
https://oracle-base.com/articles/12c/extended-data-types-12cR1

Login as "sys" user as sysdba role
conn / as sysdba
show parameter max_string_size
MAX_STRING_SIZE----> STANDARD
shutdown immediate;
startup upgrade;
ALTER SYSTEM SET max_string_size=extended;
@?/rdbms/admin/utl32k.sql
shutdown immediate;
startup;
showparameter MAX_STRING_SIZE
MAX_STRING_SIZE----> EXTENDED

======Change Oracle character set WE8MSWIN1252 to AL32UTF8 in 11g R2 and 12c ===
Dont forget to take full database backup before following below steps.

Login as: "sys" user

Check current character set
select * from nls_database_parameters ORDER BY PARAMETER;
NLS_CHARACTERSET----->WE8MSWIN1252
Target NLS_CHARACTERSET--->AL32UTF8

Stop the Database and startup in 'restrict' mode.
shutdown immediate;
startup restrict;

Now change to the desired character set.
alter database character set internal_use AL32UTF8;
alter database character set AL32UTF8;

Now stop the database and open as normal
shutdown immediate;
startup;
select * from nls_database_parameters ORDER BY PARAMETER;
NLS_CHARACTERSET----->  AL32UTF8

========= Kill datapump Export/Import ========
Identifying datapump jobs
Do a select from dba_datapump_jobs in sqlplus to get the job name:
> expdp system full=y

SELECT owner_name, job_name, operation, job_mode, state
FROM dba_datapump_jobs;

OWNER_NAME JOB_NAME             OPERATION  JOB_MODE   STATE
---------- -------------------- ---------- ---------- ------------
SYSTEM     SYS_EXPORT_FULL_01   EXPORT     FULL       EXECUTING

Or when you use the JOB_NAME parameter when datapumping, you already identified the job with a name. You don’t need to look up afterwards…
expdp system full=y JOB_NAME=EXP_FULL

OWNER_NAME JOB_NAME             OPERATION  JOB_MODE   STATE
---------- -------------------- ---------- ---------- ------------
SYSTEM     EXP_FULL             EXPORT     FULL       EXECUTING

Killing or stopping a running datapump job
The difference between Kill and Stop is simple to explain. When killing a job, you won’t be able to resume or start it again. Also logs and dumpfiles will be removed!

When exporting (or importing), press Ctrl-c to show the datapump prompt and type KILL_JOB or STOP_JOB[=IMMEDIATE]. You will be prompted to confirm if you are sure…

Adding ‘=IMMEDIATE‘ to STOP_JOB will not finish currently running ‘sub-job’ and must be redone when starting it again.

Processing object type DATABASE_EXPORT/SCHEMA/TABLE/TABLE_DATA
[Ctrl-c]
Export> KILL_JOB
..or..
Export> STOP_JOB=IMMEDIATE
Are you sure you wish to stop this job ([yes]/no): yes
Resuming a stopped job
Identify your job with SQL or you already knew it because you used ‘JOB_NAME=‘ ;)

SELECT owner_name, job_name, operation, job_mode, state
FROM dba_datapump_jobs;

OWNER_NAME JOB_NAME             OPERATION  JOB_MODE   STATE  
---------- -------------------- ---------- ---------- ------------
SYSTEM     EXP_FULL             EXPORT     FULL       NOT RUNNING
Now we can ATTACH to the job using it as a parameter to the expdp or impdp command, and a lot of gibberish is shown:

> expdp system ATTACH=EXP_FULL

Job: EXP_FULL
 Owner: SYSTEM
 Operation: EXPORT
 Creator Privs: TRUE
 GUID: A5441357B472DFEEE040007F0100692A
 Start Time: Thursday, 08 June, 2011 20:23:39
 Mode: FULL
 Instance: db1
 Max Parallelism: 1
 EXPORT Job Parameters:
 Parameter Name      Parameter Value:
 CLIENT_COMMAND        system/******** full=y JOB_NAME=EXP_FULL
 State: IDLING
 Bytes Processed: 0
 Current Parallelism: 1
 Job Error Count: 0
 Dump File: /u01/app/oracle/admin/db1/dpdump/expdat.dmp
 bytes written: 520,192

Worker 1 Status:
 Process Name: DW00
 State: UNDEFINED
(Re)start the job with START_JOB, use ‘=SKIP_CURRENT‘ if you want to skip the current job. To show progress again, type CONTINUE_CLIENT (Job will be restarted if idle).

Export> START_JOB[=SKIP_CURRENT]
Export> CONTINUE_CLIENT
Job EXP_FULL has been reopened at Thursday, 09 June, 2011 10:26
Restarting "SYSTEM"."EXP_FULL":  system/******** full=y JOB_NAME=EXP_FULL

Processing object type DATABASE_EXPORT/TABLESPACE
Processing object type DATABASE_EXPORT/PROFILE

Oracle: How to kill data pump jobs (Below example is for import (impdp) the same is applicable for export (expdp) )

When you import or export using data pump impdp or expdp tools, the import/export is done by a job. You have an option to provide a job name using JOB_NAME parameter too

Following sql will give you the list of data pump jobs
select * from dba_datapump_jobs;

If you want to kill your impdp or expdp
1) Make sure that your impdp/expdp command prompt window is active
2) Press Control-C , It will pause the job. Don’t press another Control-C or close the command prompt. This will just close the window, but the job will still be running in the background
3) Type Kill_Job
ex: Import>kill_job

Are you sure you wish to stop this job (y/n): y

If by mistake, you closed the window and your import/export job is still running,
1) Get the name of the job using
select * from dba_datapump_jobs
2) Open a new command prompt window. If you want to kill your import job type
impdp username/password@database attach=name_of_the_job   (Get the name_of_the_job using the above query)
3) Once you are attached to job, Type Kill_Job
ex: Import>kill_job

Are you sure you wish to stop this job (y/n): y
And your job is killed, it will no longer show in dba_datapump_jobs

======== import key word for oracle by using imp command ======
imp system/sys123 file=HEMIS_2017_06_10.dmp log=imphemis.log fromuser=HEMIS
imp system/sys123 file=spagobi_foodmart_2017_06_10.dmp log=impspagobi.log fromuser=spagobi,foodmart
imp system/sys123 file=Faisal_12112014.dmp log=faisal.log fromuser=Faisal_hrm

======== Check tablespace in oracle =======
select df.tablespace_name "Tablespace",
totalusedspace "Used MB",
(df.totalspace - tu.totalusedspace) "Free MB",
df.totalspace "Total MB",
round(100 * ( (df.totalspace - tu.totalusedspace)/ df.totalspace))
"Pct. Free"
from
(select tablespace_name,
round(sum(bytes) / 1048576) TotalSpace
from dba_data_files
group by tablespace_name) df,
(select round(sum(bytes)/(1024*1024)) totalusedspace, tablespace_name
from dba_segments
group by tablespace_name) tu
where df.tablespace_name = tu.tablespace_name
order by df.tablespace_name;

======== Check data file name wise size =======
set lines 100
col file_name format a70
select file_name,ceil(bytes / 1024 / 1024) "size MB",AUTOEXTENSIBLE
from dba_data_files;

========= Resize data file size =======
alter database datafile '/home/oracle/app/oracle/oradata/orcl/system01.dbf' resize 5g;

====== Table wise row count ========
select table_name,
   to_number( extractvalue( xmltype( dbms_xmlgen.getxml('select count(*) c from '||table_name)),'/ROWSET/ROW/C')) count
from user_tables
order by table_name;

=== Remote machine DB connection string from sqlplus command prompt ======

sqlplus user/pwd@//IP:1521/orcl

== Displays CPU usage for each User. Useful to understand database load by user ====

SELECT ss.username, se.SID, VALUE / 100 cpu_usage_seconds
    FROM v$session ss, v$sesstat se, v$statname sn
   WHERE     se.STATISTIC# = sn.STATISTIC#
         AND NAME LIKE '%CPU used by this session%'
         AND se.SID = ss.SID
         AND ss.status = 'ACTIVE'
         AND ss.username IS NOT NULL
ORDER BY VALUE DESC;

======= Drop Tablespace with datafile ===============
DROP TABLESPACE <TablespaceName> INCLUDING CONTENTS AND DATAFILES;

======== Export all tables without specific tables =========
CREATE OR REPLACE DIRECTORY test_dir AS '/u01/';

GRANT READ, WRITE ON DIRECTORY test_dir TO scott;

expdp scott/tiger@dell schemas=SCOTT EXCLUDE=TABLE:\"IN\(\'BONUS\',\'SALGRADE\'\)\" directory=TEST_DIR dumpfile=SCOTT.dmp logfile=expdpSCOTT.log

============

GRANT READ, WRITE ON DIRECTORY test_dir TO system;
impdp system/sys123@dell directory=TEST_DIR remap_schema=scott:imam dumpfile=SCOTT.dmp logfile=impdpSCOTT.log

====== only table import and export ==========
expdp scott/tiger@dell directory=TEST_DIR dumpfile=multi_table.dmp tables=scott.BONUS,scott.SALGRADE

impdp system/sys123@dell directory=TEST_DIR remap_schema=scott:imam dumpfile=multi_table.dmp logfile=impdpMULT.log

=======================================================


If you find an oracle process is consuming a high amount of CPU, you can find the sql_text that is related to that process id using the following code:
SELECT SQL_TEXT
FROM v$sql
WHERE sql_id = (SELECT sql_id FROM v$session WHERE paddr = (sELECT addr
FROM v$process
WHERE spid = '&process_id'));
You will need to find the process id using either top (linux), topas -P (aix), or task manager (windows). Equally you can use Enterprise Manager to find this information, by looking under the performance monitor and any alerts regarding tuning / high CPU consumption.
To disable gather_stats_job in 10g:
BEGIN
DBMS_SCHEDULER.DISABLE('GATHER_STATS_JOB');
END;
/
To disable gather_stats_job (also known as optimizer stats) in 11g:
BEGIN
DBMS_AUTO_TASK_ADMIN.DISABLE(
client_name => 'auto optimizer stats collection',
operation => NULL,
window_name => NULL);
END;
/

If you wish to find the source code for a view, you can look in the user_views table:
SQL> SELECT view_name, text FROM user_views;
You can check the v$fixed_view_definition table to check the definition of fixed views (views starting with v$).
SQL> SELECT view_name, view_definition FROM v$fixed_view_definition;
Further Reading

To retrieve the instance name of the database instance you are currently connected to, you can perform a number of queries:
Non-public single-node query
SQL> SELECT name FROM v$instance;
INSTANCE_NAME
-----------------------
DEV
Non-public RAC node query
SQL> SELECT instance_name FROM gv$instance;
INSTANCE_NAME
-----------------------
DEV
Public query
SQL> SELECT sys_context('USERENV','DB_NAME') AS instance_name FROM dual;
INSTANCE_NAME
-----------------------
DEV

MMON (Memory Monitor) is an Oracle background process that gathers memory statistics (snapshots) and stores this information in the AWR.
MMON is also responsible for issuing alerts for metrics that exceed their thresholds.
MMON is available from Oracle 10g.
The default for recording an AWR snapshot is hourly.

SMON (system monitor) is the Oracle background process which performs instance recovery, cleans up after unclean shutdowns and coalesces adjacent free extents into larger free extents.
SMON wakes up every 5 minutes to perform housekeeping duties, and the database instance will terminate if SMON is not running.
You can check if SMON is running from the command line in Linux/Unix:
$ ps -ef | grep pmon

PMON is an Oracle background process created when you start the database instance. It is responsible for freeing up resources if a user process fails.
PMON normally wakes up every 3 seconds to perform housekeeping.
If PMON is not running then the database instance will terminate.
To speed up house-keeping you can wake-up PMON manually:
SQL> oradebug setmypid
SQL> oradebug wakeup 2

Sometimes it is necessary to do work on a database without any other users being logged in. It is possible to restrict the database session in such a case. When the database starts in restricted mode only users with restricted session privileges can get access to the database even though it is technically in open mode.
Enable / Disable Restricted Session
SQL> startup restrict ORACLE instance started.
Total System Global Area 504366872 bytes
Fixed Size 743192 bytes
Variable Size 285212672 bytes
Database Buffers 218103808 bytes
Redo Buffers 307200 bytes
Database mounted.
Database opened.
Startup the database in restricted mode
The alter system command can be used to put the database in and out of restricted session once it is open:
SQL> alter system enable restricted session;
system altered
SQL> alter system disable restricted session;
system altered
Find and disconnect users connected during restricted session
Any users connected to the database when restricted session is enabled will remain connected and need to be manually disconnected
To check which users are connected to the database run the following:
SQL> SELECT username, logon_time, process from v$session;
USERNAME LOGON_TIM PROCESS
-------- --------- -------
17-NOV-10 606252
17-NOV-10 598054
17-NOV-10 540690
17-NOV-10 421948
17-NOV-10 561182
17-NOV-10 512046
17-NOV-10 1257542
SYS      17-NOV-10 1310796
8 rows selected.
By querying the process id you can then issue a kill -9 <process_id> at the operating system level to disconnect the connected user. The blank usernames in v$session refer to background database processes.
Check if database in restricted mode
If you are unsure whether the database is in restricted session or not you can run the following query to check:
SQL> SELECT logins from v$instance;
LOGINS
----------
RESTRICTED

Opatch is an Oracle utility for the application and rolling back of interim patches to the Oracle RDBMS.  In order to use opatch it is recommended to set its location in $PATH.
Location
OPatch can be found under $ORACLE_HOME/OPatch
Current Patch History
To find the current patch history run the following:
$ opatch lsinventory [ -all ] [ -i[nvPtrLoc] <Path to oraInst.loc> ][ -oh <ORACLE_HOME>]
-all
– list all patches currently applied.
OPatch Version
$ sh opatch version
Invoking OPatch 10.2.0.4.2
OPatch Version: 10.2.0.4.2
OPatch succeeded.
OPatch Apply
$ opatch apply [-f[orce]] [-i[nvPtrLoc]<path to oraInst.log] [-m[inimize_downtime]] [-n[o_inventory]] [-oh<ORACLE_HOME>] [<patch_location>]
-force
– used to remove any conflicting patches and force the patch to be applied
-invPtrLoc
– used to locate the oraInst.loc file
-minimize_downtime
– used only in RAC instances, allowing for the remaining instances to remain up during patching. It is the responsibility of the user to shutdown each instance before applying the patches, after the last instance is patched then all instances can be brought back up.
-no_inventory
– This only works if the inventory is unavailable and allows for bypassing the inventory for reading and updates.
-oh
– Directory to be used instead of the default $ORACLE_HOME
patch_location
– Where to install the patch from
OPatch Rollback
Sometimes it is necessary to rollback a patch once it has been applied.
$ opatch rollback -id patch_id [-i[nvPtrLoc]<Path to oraInst.loc>] [-oh <ORACLE_HOME>] -pj patch_dir
-id
– The id of the patch that requires rollback
-ph
– The directory that is a valid patch area.

One of the tasks a DBA undertakes is to monitor the amount of space consumed by the database. If a tablespace becomes spacebound than the database will freeze up as data cannot be written down to disk.
Check Tablespace Free Space
The below script will identify the available free space for each tablespace.
SELECT a.tablespace_name
, a.fileCount
, a.MaxTSBytes
, b.TSDataBytes
, a.MaxTSBytes - b.TSDataBytes FreeSpace
, ROUND((a.TotalFilesizeMB/a.MaxTSBytes)*100,2) DFAlloc
, ROUND((b.TSDataBytes/a.MaxTSBytes)*100,2) AS DATAAlloc
FROM
(SELECT tablespace_name
, COUNT(*) filecount
, SUM(CASE WHEN maxbytes > bytes THEN maxbytes/1048576 ELSE bytes/1048576 end) AS MaxTSBytes
, SUM(bytes)/1048576 TotalFilesizeMB
FROM dba_data_files GROUP BY tablespace_name) a,
(SELECT tablespace_name
, SUM(bytes)/(1048576) AS TSDataBytes
FROM dba_extents GROUP BY tablespace_name) b
WHERE a.tablespace_name = b.tablespace_name(+)
ORDER BY 1
/
TABLESPACE_NAME FILECOUNT MAXTSBYTES TSDATABYTES FREESPACE  DFALLOC DATAALLOC
--------------- --------- ---------- ----------- ---------  ------- ---------
INTERFACE       13        22250      21906.4375  343.5625   100      98.46
LOAD            6         8550       7629.125    920.875    100      89.23
MLOG            1         1250       617.5625    632.4375   100      49.41
NOTES           3         4200       3728.6875   471.3125   100      88.78
SYSTEM          1         500        406.625     93.375     100      81.33
UNDO            3         4500       323.085938  4176.91406 100       7.18
XDB             1         100        44.9375     55.0625    100      44.94
6 rows selected.
Query Datafile Sizes
The below script queries how much free space is available per datafile. In this example only the system tablespace has been queried:
SELECT a.file_id,
SUBSTR(a.tablespace_name,1,10) tablespace,
a.autoextensible,
(CASE WHEN a.maxbytes > a.bytes THEN a.maxbytes/1048576 ELSE bytes/1048576 END) MaxFileSize,
a.bytes/1048576 filesize,
(CASE WHEN a.maxbytes > a.bytes THEN a.maxbytes/1048576 ELSE bytes/1048576 END) - nvl(b.usedbytes,0) free_Mb,
round(100*(1-(nvl(b.Usedbytes,0))/(CASE WHEN a.maxbytes > a.bytes THEN a.maxbytes/1048576 else bytes/1048576 END)),2) "%_FREE",
a.file_name
FROM  dba_data_files a,
(SELECT file_id
, sum(bytes)/1048576 Usedbytes
FROM dba_extents GROUP BY file_id) b
WHERE a.file_id = b.file_id(+)
AND a.tablespace_name = '&tablespace_name'
ORDER BY
a.tablespace_name,
a.file_id
/
FILE_ID TABLESPACE AUT MAXFILESIZE FILESIZE FREE_MB %_FREE FILE_NAME
------- ---------- --- ----------- -------- ------- ------ ---------
1       SYSTEM     NO  500         500      93.375  18.68 /u05/oracle/oradata/SYSTM_01.dbf
Once you have found the file_id for the datafile in the tablespace that needs expanding then you can increase the size of the tablespace.