shell脚本:安装oracle19c 单节点
本内容只是自己无聊时候的不成熟的写法,放到现在肯定不会这样子复杂的写法,权当娱乐
目录结构:
oracle_isntall
--config
config.yml
template_config.yml
--install
--oracle
oracle_install.sh
template_oracle_install.sh
--root
initialization.sh
template_initialization.sh
--remove
remove.sh
template_remove.sh
--task
apidemo.py
deal_config.py
说明:
点击查看代码
脚本目录用于配置,安装Oracle 19c数据库:
所有config目录、install目录、remove目录修改在template开头的文件进行修改:
config目录:
- template_config.yml文件是变量配置文件模板,修改时编辑该文件,修改时编辑该文件
- config.yml文件变量配置文件,由template_config.yml文件生成
install目录:
oracle目录:
- template_oracle_install.sh文件是完成服务器初始化后进行一键式安装数据库的脚本模板,修改时编辑该文件
- oracle_install.sh一键式安装数据库的脚本,template_oracle_install.sh文件生成
root目录:
- template_initialization.sh用于初始化服务器,修改时编辑该文件
- initialization.sh初始化服务器脚本,由template_initialization.sh文件生成
remove目录:
- template_remove.sh用于移除数据库脚本的模板,修改时编辑该文件
- remove.sh 用于移除数据库执行的脚本,由template_remove.sh文件生成
task目录:
python脚本用于配置配置项:
- apidemo.py文件用于定义获取数据或者处理数据的方法
- deal_config.py文件用于执行获取变量数据并写入.sh文件
python信息:
- python3.10版本
- 使用到的python模块:'jsonpath json yaml re shutil os sys'
# 库里面的.sh脚本修改必须在template_开头的脚本修改
# template_*.sh文件中,变量有值的不允许再赋值
# eg: sh文件中disk_mountpoint=/data存在值,则oracle_install_config_list的列表值中不允许有disk_mountpoint存在,已存在必须删除
# 使用中的脚本可以直接在实际使用脚本修改oracle_install_config_list
# yml文件中的变量值定义只能是字符串和整数
# remove_config_list是remove.sh中需要修改的配置项集合,只有在这个变量值的列表中,才会被写入到remove.sh中
# oracle_install_config_list是oracle_install.sh脚本中需要修改的配置项集合,只有在这个变量值的列表中,才会被写入到oracle_install.sh中
# init_config_list是initialization.sh脚本中需要修改的配置项集合,只有在这个变量值的列表中,才会被写入到oracle_install.sh中
# 为什么使用模板文件:为了保证有这样一个文件,文件中需要修改的变量都是如下格式:"变量="
# *_decide是一些判断某些行为动作的变量,Y/N: Y 则执行,N 则执行
# eg:hostname_decide: Y 时,hostname必须有值
template_congig.yml文件内容为:
点击查看代码
# oracle安装和移除的相关变量配置
# 遵循yml文件格式 key: value
oracle:
server:
# initialization是否按照上述hostname修改oracle服务器,Y/N
hostname_decide: Y
# initialization是否手动设置服务器时间Y/N
time_decide: Y
# initialization是否重启Y/N
reboot_decide: N
# initialization是否创建用户名和用户组Y/N
oracleUser_decide: Y
# initialization是否创建数据库安装目录es/N
oracleDir_decide: Y
# initialization是否安装数据库依赖软件Y/N
depend_decide: Y
# initialization是否配置操作系统参数Y/N
limitsConfig_decide: Y
# initialization是否配置操作系统参数Y/N
# swap_decide: Y只能一次,否则要修改生成的文件名
swap_decide: N
# initialization是否进行磁盘初始化
disk_decide: N
# oracle_install是否解压安装包
softwareUnzip_decide: Y
# oracle_install是否安装数据库
oracleInstall_decide: Y
# oracle_install是否解压安装包
pdbInstall_decide: Y
# oracle_install是否解压安装包
listenner_decide: Y
# oracle_install是否修改数据库监听端口
listennerModify_decide: Y
# oracle_install是否创建表空间
tablespaceCreate_decide: Y
# oracle_install是否创建用户
usernameCreate_decide: Y
# remove 数据库时是否删除安装目录及数据目录Y/N
remove_dir_decide: N
# initialization 服务器hostname
hostname: db1027
# initialization oracle服务器IP,必须填写
oracle_ip: 10.10.10.27
# initialization oracle服务器自动分区磁盘名和磁盘格式
disk_name: sde
disk_type: ext4
# oinitialization racle服务器磁盘挂载点
disk_mountpoint: /data
# initialization 服务器date时间
time: "'2022-10-02 15:52:00'"
# initialization 过程结束后是否重启服务器 Y/N
initiaze_reboot: N
install:
# oracle安装包名和上传位置
oracle_software_name: V982063-01.zip
oracle_software_path: /data
# 用于安装Oracle软件的用户和用户组,基本不修改
oracle_user: oracle
oracle_grid: grid
oracle_group: oinstall
group_asmdba: asmdba
group_dba: dba
group_oper: oper
group_asmoper: asmoper
group_backupdba: backupdba
group_dgdba: dgdba
group_kmdba: kmdba
group_racdba: racdba
# oracle安装需要定义的目录和SID
ORACLE_BASE: /u01/app/oracle
ORACLE_HOME: /u01/app/oracle/product/19.0.0/dbhome_1
INVENTORY_LOCATION: /u01/app/oraInventory
# ORACLE dbf数据文件存储路径
datafileDestination: /oracle_data/storage/oradata
# oracle恢复区
recoveryAreaDestination: /oracle_data/storage/flash_recovery_area
# 数据库SID,gdbName
ORACLE_SID: dwgldb
# 数据库pdbName
ORACLE_PDB: dwgldbpdb
# 数据库超管密码
ORACLE_PASSWORD: WEIba@1004
# 自定义数据库监听端口
listennerModify_port: 1588
# 字符集
characterSet: ZHS16GBK
# oracle服务器languages
LANG: zh_CN.UTF-8
NLS_LANG_COUNTRY: AMERICAN_AMERICA
# oracle 19c在Linux 7上的依赖包
depend_service_rpm: "'bc binutils compat-libcap1 compat-libstdc++-33 elfutils-libelf elfutils-libelf-devel fontconfig-devel glibc glibc-devel ksh libaio libaio-devel libXrender libXrender-devel libX11 libXau libXi libXtst libgcc libstdc++ libstdc++-devel libxcb make policycoreutils policycoreutils-python smartmontools unzip'"
# oracle_install定义表空间名
tablespace_name: weiba_data
# oracle_install定义表空间大小,需要带单位
tablespace_size: 1G
# oracle_install定义用户名及密码
user_name: weiba_test
user_password: WEIba@1004
# oracle_install用户创建后授权权限
privilege_name: "'CONNECT,EXP_FULL_DATABASE,IMP_FULL_DATABASE,RESOURCE,SELECT_CATALOG_ROLE,ALTER SYSTEM,AUDIT SYSTEM,CREATE SESSION,ALTER SESSION,CREATE TABLESPACE,DROP TABLESPACE,CREATE USER,BECOME USER,ALTER USER,DROP USER,CREATE ROLLBACK SEGMENT,DROP ROLLBACK SEGMENT,CREATE TABLE,CREATE ANY TABLE,ALTER ANY TABLE,BACKUP ANY TABLE,DROP ANY TABLE,COMMENT ANY TABLE,SELECT ANY TABLE,INSERT ANY TABLE,UPDATE ANY TABLE,DELETE ANY TABLE,CREATE CLUSTER,CREATE ANY CLUSTER,DROP ANY CLUSTER,CREATE ANY INDEX,DROP ANY INDEX,CREATE SYNNYM,CREATE ANY SYNNYM,DROP ANY SYNNYM,CREATE PUBLIC SYNNYM,DROP PUBLIC SYNNYM,CREATE VIEW,CREATE ANY VIEW,DROP ANY VIEW,CREATE SEQUENCE,CREATE ANY SEQUENCE,DROP ANY SEQUENCE,SELECT ANY SEQUENCE,CREATE DATABASE LINK,CREATE PUBLIC DATABASE LINK,DROP PUBLIC DATABASE LINK,CREATE ROLE,DROP ANY ROLE,GRANT ANY ROLE,AUDIT ANY,ALTER DATABASE,CREATE PROCEDURE,CREATE ANY PROCEDURE,ALTER ANY PROCEDURE,DROP ANY PROCEDURE,EXECUTE ANY PROCEDURE,CREATE TRIGGER,CREATE ANY TRIGGER,ALTER ANY TRIGGER,DROP ANY TRIGGER,CREATE PROFILE,ALTER PROFILE,DROP PROFILE,ALTER RESOURCE COST,ANALYZE ANY,GRANT ANY PRIVILEGE,CREATE MATERIALIZED VIEW,CREATE ANY MATERIALIZED VIEW,DROP ANY MATERIALIZED VIEW,CREATE ANY DIRECTORY,DROP ANY DIRECTORY,CREATE TYPE,CREATE ANY TYPE,ALTER ANY TYPE,DROP ANY TYPE,EXECUTE ANY TYPE,CREATE ANY LIBRARY,DROP ANY LIBRARY,CREATE OPERATOR,CREATE ANY OPERATOR,DROP ANY OPERATOR,EXECUTE ANY OPERATOR,CREATE INDEXTYPE,CREATE ANY INDEXTYPE,DROP ANY INDEXTYPE,GLOBAL QUERY REWRITE,CREATE ANY DIMENSION,DROP ANY DIMENSION,MANAGE ANY QUEUE,CREATE ANY CONTEXT,DROP ANY CONTEXT,DROP ANY OUTLINE,ADMINISTER RESOURCE MANAGER,ADMINISTER DATABASE TRIGGER,RESUMABLE,SELECT ANY DICTIONARY,GRANT ANY OBJECT PRIVILEGE,ANALYZE ANY DICTIONARY,CREATE JOB,MANAGE SCHEDULER,DROP ANY SQL PROFILE,CREATE ANY SQL PROFILE,READ ANY FILE GROUP,ADMINISTER SQL MANAGEMENT OBJECT'"
remove:
# 配置文件中确认是否移除数据库,再次确认是否删除
remove_sure: N
# 如下配置项为每个文件有哪些配置需要在程序中进行配置修改的
remove_config:
# remove.sh文件中需要修改的配置项集合
remove_config_list: [ 'oracle_user', 'remove_sure', 'ORACLE_BASE','remove_dir_decide' ]
# oracle_install.sh脚本中需要修改的配置项集合
oracle_install_config:
oracle_install_config_list: ['hostname','oracle_software_name','oracle_software_path','tablespace_name','tablespace_size','user_name','user_password','privilege_name','hostname_decide','softwareUnzip_decide','oracleInstall_decide','pdbInstall_decide','listenner_decide','listennerModify_decide','tablespaceCreate_decide','usernameCreate_decide','oracle_user','oracle_grid','oracle_group','group_asmdba','group_dba','group_oper','group_asmoper','group_backupdba','group_dgdba','group_kmdba','group_racdba','ORACLE_BASE','ORACLE_HOME','INVENTORY_LOCATION','datafileDestination','recoveryAreaDestination','characterSet','ORACLE_SID','ORACLE_PDB','ORACLE_PASSWORD','LANG','NLS_LANG_COUNTRY','listennerModify_port']
# initialization.sh脚本中需要修改的配置项集合
init_config:
init_config_list: [ 'oracle_user','oracle_ip','hostname','disk_name','disk_type','disk_mountpoint','time','hostname_decide','time_decide','reboot_decide','oracleUser_decide','oracleDir_decide','depend_decide','limitsConfig_decide','swap_decide','disk_decide','depend_service_rpm','oracle_user','oracle_grid','oracle_group','group_asmdba','group_dba','group_oper','group_asmoper','group_backupdba','group_dgdba','group_kmdba','group_racdba','ORACLE_BASE','ORACLE_HOME','INVENTORY_LOCATION','datafileDestination','recoveryAreaDestination','initiaze_reboot' ]
template_initialization.sh内容为:
点击查看代码
#!/bin/sh
################################################################
# initialize oracle server by xiaoweiba #
################################################################
# 从config目录获取变量
# 服务器初始化设置参数
oracle_ip=
hostname=
disk_name=
disk_type=
disk_mountpoint=
time=
#####################################
# 一些操作的判断Y/N
hostname_decide=
time_decide=
reboot_decide=
oracleUser_decide=
oracleDir_decide=
depend_decide=
limitsConfig_decide=
swap_decide=
disk_decide=
#####################################
# oracle安装的用户,用户组,目录
depend_service_rpm=
oracle_user=
oracle_grid=
oracle_group=
group_asmdba=
group_dba=
group_oper=
group_asmoper=
group_backupdba=
group_dgdba=
group_kmdba=
group_racdba=
ORACLE_BASE=
ORACLE_HOME=
INVENTORY_LOCATION=
datafileDestination=
recoveryAreaDestination=
#####################################
# 是否重启服务器
initiaze_reboot=
#####################################
function hostname_set() {
# 判断是否设置hostname
[ $hostname_decide == 'Y' ] && hostnamectl set-hostname $hostname
# 做静态解析
echo $oracle_ip $hostname >> /etc/hosts
# 设置时间
if [ time_set = "Y" ]; then
echo "--设置时间--"
timedatectl set-ntp N
timedatectl set-time $time
clock -w
timedatectl set-ntp Y
fi
}
function disk_set() {
if [ $disk_decide == 'Y' ]; then
echo -e "n\np\n1\n\n\nt\n8e\nw" | fdisk /dev/$disk_name && echo "--磁盘/dev/$disk_name已自动分区--"
# 磁盘挂载使用lvs模式
pvcreate /dev/${disk_name}1 && vgcreate data_vg /dev/${disk_name}1 && lvcreate -l 100%VG -n data_lv data_vg
# 格式化
mkfs.$disk_type /dev/data_vg/data_lv
echo /dev/data_vg/data_lv $disk_mountpoint $disk_type defaults 0 0 >> /etc/fstab
mount -a
# 判断是否挂载
mount_num=`lsblk|grep -i $disk_mountpoint|grep -i data_lv|wc -l`
if [ $mount_num -eq 0 ]; then
echo "----/dev/data_vg/data_lv和$disk_mountpoint挂载异常----"
exit 111
fi
fi
}
function hugepage_set() {
echo "--禁用大透明页--"
CMDLINE_LINUX="crashkernel=auto rd.lvm.lv=ol/root rd.lvm.lv=ol/swap rhgb quiet transparent_hugepage=never"
transparent=`cat /sys/kernel/mm/transparent_hugepage/enabled|awk '{print $3}'`
[ $transparent == '[never]' ] || sed -i 's#GRUB_CMDLINE_LINUX=.*#GRUB_CMDLINE_LINUX=\"'"$CMDLINE_LINUX"'\"#g' /etc/default/grub
}
function LoginGraceTime_set() {
echo "--ssh设置LoginGraceTime--"
LoginGraceTime_value=`grep -iEv '^#|^$' /etc/ssh/sshd_config |grep -i LoginGraceTime`
if [ -z $LoginGraceTime_value ]; then
echo LoginGraceTime 0 >> /etc/ssh/sshd_config
else:
sed -i 's/LoginGraceTime .*/LoginGraceTime 0/g' sshd_config
fi
systemctl restart sshd
}
function swap_set() {
if [ $swap_decide == 'Y' ]; then
echo "--检查swap空间--"
# 内存16G以上,swap空间16G
# 16G以下,swap空间为内存的1半
total_mem=`free -g | grep -i mem | awk '{print $2}'`
swap_mem=`free -g | grep -i swap | awk '{print $2}'`
if [ ! -z $swap_mem ]; then
swap_type=`lsblk | grep -iE swap | awk '{print $7}'`
if [ $swap_type == 'lvm' ]; then
halt_total_mem=$((($total_mem+1)/2))
if [ $swap_mem -lt $halt_total_mem ]; then
# 需要扩容的量
differ_value=$(($halt_total_mem-$swap_mem))
count_num=$(($differ_value*1000000))
swap_file=/dev/image.file
dd if=/dev/zero of=$swap_file bs=1024 count=$count_num
mkswap -f $swap_file
swapon $swap_file
echo $swap_file swap swap defaults 0 0 >> /etc/fstab
Nw_swap_mem=`free -g | grep -i swap | awk '{print $2}'`
echo "----swap已从${swap_mem}G扩容到${Nw_swap_mem}G----"
fi
fi
fi
fi
}
function oracleUser_set() {
# define function
function create_group() {
# 传入group名
group=`awk -F ':' '{print $1}' /etc/group | grep -iE ^$1|grep -iE $1\$`
if [ -z $group ]; then
groupadd $1 && echo "----创建用户组 $1----"
else
echo "----$1用户组组已经存在----"
fi
}
function create_user() {
# 传入user名
if [ -z `id $1` ]; then
/usr/sbin/useradd -u 54321 -g $oracle_group -G $group_asmdba,$group_dba,$group_oper,$group_asmoper,$group_backupdba,$group_dgdba,$group_kmdba,$group_racdba $1 && echo "----创建用户$1----"
else
/usr/sbin/usermod -g $oracle_group -G $group_asmdba,$group_dba,$group_oper,$group_asmoper,$group_backupdba,$group_dgdba,$group_kmdba,$group_racdba $1 && echo "----修改用户$1----"
fi
}
if [ $oracleUser_decide == 'Y' ]; then
echo "--创建oracle用户和组--"
# 创建用户组
for group_name in `echo $oracle_group $group_asmdba $group_dba $group_oper $group_asmoper $group_backupdba $group_dgdba $group_kmdba $group_racdba`
do
create_group $group_name
done
# 创建用户$oracle_user
create_user $oracle_user
create_user $oracle_grid
fi
}
function oracleDir_set() {
if [ $oracleDir_decide == 'Y' ]; then
echo "--创建oracle安装目录和存储目录--"
[ -d $ORACLE_BASE ] || mkdir -p $ORACLE_BASE
[ -d $ORACLE_HOME ] || mkdir -p $ORACLE_HOME
[ -d $INVENTORY_LOCATION ] || mkdir -p $INVENTORY_LOCATION
[ -d $datafileDestination ] || mkdir -p $datafileDestination
[ -d $recoveryAreaDestination ] || mkdir -p $recoveryAreaDestination
fi
}
function depend_rpm() {
if [ $depend_decide == 'Y' ]; then
echo "--检测本地yum源并安装依赖包--"
yum repolist
yum install -y $depend_service_rpm
fi
}
function limitsConfig_set() {
if [ $limitsConfig_decide == 'Y' ]; then
# /etc/security/limits.conf
echo "--/etc/security/limits.conf文件参数配置--"
cp -a /etc/security/limits.conf /etc/security/limits.conf.bak
cat > weiba.txt <<EOF
* soft nproc 16384
* hard Nfile 65536
* soft Nfile 65536
* hard stack 10240
* soft stack 10240
EOF
echo "--/etc/sysctl.conf文件参数配置--"
cat > /etc/sysctl.conf << EOF
fs.aio-max-nr = 1048576
fs.file-max = 6815744
kernel.shmall = 33554432
kernel.shmmax = 137438953471
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
EOF
sysctl -p
fi
}
function server_reboot() {
if [ $reboot_decide == 'Y' ]; then
echo ""
read -t 120 -n1 -p "--确认是否重启服务器: Y/N" sure_reboot
if [ $sure_reboot != 'Y' ]; then
echo "--确认重启服务器,2秒后自动重启"
sleep 2 && reboot
else
echo "--请手动重启服务器--"
fi
fi
}
function initialize_oracle() {
# 检查当前session用户
session_user=`whoami`
[ $session_user == 'root' ] || echo "--请使用root用户执行脚本--" && exit 111
# 设置hostname,静态解析,设置时间
hostname_set
# 禁用大透明页
hugepage_set
# ssh配置
LoginGraceTime_set
# swap空间
swap_set
# Oracle依赖软件,检测是否有yum源
depend_rpm
# 配置Oracle用户及用户组
oracleUser_set
# 创建基本目录
oracleDir_set
# /etc/security/limits.conf和/etc/sysctl.conf修改参数
limitsConfig_set
# 服务器重启
server_reboot
}
function main() {
#
initialize_oracle
}
# main
template_oracle_install.sh文件内容为:
点击查看代码
#!/bin/sh
################################################################
# install oracle by xiaoweiba #
# 本脚本暂时只适用于zip包安装的情况 #
################################################################
#####################################
# 从config目录获取变量
hostname=
oracle_software_name=
oracle_software_path=
tablespace_name=
tablespace_size=
user_name=
user_password=
privilege_name=
#####################################
# 是否解压安装包
hostname_decide=
softwareUnzip_decide=
oracleInstall_decide=
pdbInstall_decide=
listenner_decide=
listennerModify_decide=
tablespaceCreate_decide=
usernameCreate_decide=
#####################################
oracle_user=
oracle_grid=
oracle_group=
group_asmdba=
group_dba=
group_oper=
group_asmoper=
group_backupdba=
group_dgdba=
group_kmdba=
group_racdba=
ORACLE_BASE=
ORACLE_HOME=
INVENTORY_LOCATION=
datafileDestination=
recoveryAreaDestination=
characterSet=
ORACLE_SID=
ORACLE_PDB=
ORACLE_PASSWORD=
LANG=
NLS_LANG_COUNTRY=
LD_LIBRARY_PATH='$ORACLE_HOME/lib:$ORACLE_HOME/rdbms/lib:$ORACLE_HOME/network/lib:/lib:/usr/lib'
CLASSPATH='$ORACLE_HOME/jlib:$ORACLE_HOME/rdbms/jlib:$ORACLE_HOME/network/jlib'
listennerModify_port=
# 组合得出的变量
NLS_LANG="$NLS_LANG_COUNTRY.$characterSet"
#####################################
function profile_set() {
# 根据key/value来进行普通用户的环境变量声明
function export_set() {
# $1是key=value形式的参数
[ -z `env|grep $1` ] && echo export $1 >> ~/.bash_profile
}
export_set 'ORACLE_BASE='"$ORACLE_BASE"''
export_set 'ORACLE_HOME='"$ORACLE_HOME"''
export_set 'ORACLE_SID='"$ORACLE_SID"''
export_set 'ORACLE_HOSTNAME='"$hostname"''
export_set 'LANG='"$LANG"''
export_set 'NLS_LANG='"$NLS_LANG"''
export_set 'LD_LIBRARY_PATH='"$LD_LIBRARY_PATH"''
export_set 'CLASSPATH='"$CLASSPATH"''
echo 'export PATH=$PATH:$ORACLE_HOME/bin:$ORACLE_HOME/OPatch' >> ~/.bash_profile
source ~/.bash_profile
}
function softwareUnzip_set() {
# 解压数据库安装包软件
if [ $softwareUnzip_decide == 'Y' ]; then
cd $ORACLE_HOME
unzip -q ${oracle_software_path}/oracle_software_name
fi
}
function oracleInstall_set() {
# 安装数据库软件
if [ $oracleInstall_decide == 'Y' ]; then
echo "--开始安装数据库软件--"
cd $ORACLE_HOME/install/response
[ -f db_install.rsp ] || cp -a db_install.rsp db_install.rsp.bak
cat > db_install.rsp <<EOF
oracle.install.responseFileVersion=/oracle/install/rspfmt_dbinstall_response_schema_v19.0.0
oracle.install.option=INSTALL_DB_SWONLY
oracle.install.db.config.starterdb.memoryOption=true
oracle.install.db.config.starterdb.characterSet=$characterSet
UNIX_GROUP_NAME=$oracle_group
INVENTORY_LOCATION=$INVENTORY_LOCATION
ORACLE_HOME=$ORACLE_HOME
ORACLE_BASE=$ORACLE_BASE
oracle.install.db.InstallEdition=
oracle.install.db.OSDBA_GROUP=$group_dba
oracle.install.db.OSOPER_GROUP=$group_oper
oracle.install.db.OSBACKUPDBA_GROUP=$group_backupdba
oracle.install.db.OSDGDBA_GROUP=$group_dgdba
oracle.install.db.OSKMDBA_GROUP=$group_kmdba
oracle.install.db.OSRACDBA_GROUP=$group_racdba
oracle.install.db.rootconfig.executeRootScript=false
oracle.install.db.rootconfig.configMethod=ROOT
EOF
cd $ORACLE_HOME && ./runInstaller -force -silent -Nconfig -igNrePrereq -responseFile $ORACLE_HOME/install/response/db_install.rsp && echo "--完成安装数据库软件--" && sleep 4
echo ""
echo "----请按照提示在root用户下执行脚本----"
read -t 120 -n1 -p "----是否已确认执行脚本----; Y or N" confirm
[ $confirm == 'Y' ] || exit 111
fi
}
function pdbInstall_set() {
# 解压数据库安装包软件
if [ $pdbInstall_decide == 'Y' ]; then
# 计算内存
total_mem=`free -g |grep -i mem|awk '{print $2}'`
config_mem=$((1024*$total_mem*4/5))
cd $ORACLE_HOME/assistants/dbca
[ -f dbca.rsp ] || cp -a dbca.rsp dbca.rsp.bak
cat > db_install.rsp <<EOF
emExpressPort=5500
responseFileVersion=/oracle/assistants/rspfmt_dbca_response_schema_v19.0.0
templateName=General_Purpose.dbc
gdbName=$ORACLE_SID
sid=$ORACLE_SID
createAsContainerDatabase=TRUE
numberOfPDBs=1
pdbName=$ORACLE_PDB
pdbAdminPassword=$ORACLE_PASSWORD
sysPassword=$ORACLE_PASSWORD
systemPassword=$ORACLE_PASSWORD
datafileDestination=$datafileDestination
recoveryAreaDestination=$recoveryAreaDestination
storageType=FS
characterSet=ZHS16GBK
nationalCharacterSet=ZHS16GBK
sampleSchema=true
totalMemory=$config_mem
databaseType=OLTP
emConfiguration=NNE
EOF
dbca -silent -createDatabase -responseFile $ORACLE_HOME/assistants/dbca/dbca.rsp && echo "--安装pdb数据库完成--" && sleep 2
# https://www.yisu.com/zixun/540571.html
echo "--配置sqlnet.ora文件支持jdk8--"
echo 'SQLNET.ALLOWED_LOGON_VERSION_SERVER=8' >> $ORACLE_HOME/network/admin/sqlnet.ora
echo 'SQLNET.ALLOWED_LOGON_VERSION_CLIENT=8' >> $ORACLE_HOME/network/admin/sqlnet.ora
fi
}
function listenner_set() {
# 解压数据库安装包软件
if [ $listenner_decide == 'Y' ]; then
netca -silent -responseFile $ORACLE_HOME/assistants/netca/netca.rsp && echo "--启动数据库监听1521完成--" && sleep 2
fi
# 修改数据库监听端口
if [ $listennerModify_decide == 'Y' ]; then
echo "--配置文件修改listener.ora默认端口为$listennerModify_port--"
cd $ORACLE_HOME/network/admin && sed -i 's#PORT = 1521#PORT = '"$listennerModify_port"'#g' listener.ora
echo "--修改数据库注册配置并重启数据库--"
echo " alter system set local_listener=\"(address = (PROTOCOL = TCP)(HOST = $oracle_ip) (PORT = $listennerModify_port))\";
alter system register;
shutdown immediate;
startup;
alter alter pluggable database $pdbName open;
exit
" | sqlplus / as sysdba && echo "--修改注册配置结束--"
fi
}
function tablespaceCreate_set() {
if [ $tablespaceCreate_decide == 'Y' ]; then
echo "--创建数据库表空间--"
echo "alter session set container=$ORACLE_PDB;
create tablespace $tablespace_name datafile '"$datafileDestination"01.dbf' size $tablespace_size autoextend off;
exit
" | sqlplus / as sysdba && echo "--修改注册配置结束--"
fi
}
function usernameCreate_set() {
if [ $usernameCreate_decide == 'Y' ]; then
echo "--创建数据库表空间--"
echo "alter session set container=$ORACLE_PDB;
create user $user_name IDENTIFIED BY \"$user_password\" default tablespace $tablespace_name temporary tablespace temp profile default;
alter user $user_name account unlock;
ALTER USER $user_name QUOTA UNLIMITED ON $tablespace_name;
grant $privilege_name to $user_name;
exit
" | sqlplus / as sysdba && echo "--$user_name/$user_password创建完成--"
fi
}
function oracle_install() {
# 判断用户
session_user=`whoami`
[ $session_user == $oracle_user ] || echo "--请使用$oracle_user用户执行脚本--" && exit 111
# 配置环境变量
profile_set
# 解压数据库安装包软件
softwareUnzip_set
# 安装数据库
oracleInstall_set
# 静默安装pdb
pdbInstall_set
# 配置监听及修改监听
listenner_set
# 创建表空间
tablespaceCreate_set
# 创建数据库用户,默认绑定上述新建表空间
usernameCreate_set
# 声明
echo ""
echo "--数据库安装过程结束--"
}
function main() {
function oracle_install
}
template_remove.sh文件内容为:
点击查看代码
#!/bin/sh
################################################################
# remove oracle by xiaoweiba #
################################################################
# 参数变量从config目录自动获取
oracle_user=
ORACLE_BASE=
remove_dir_decide=
remove_sure=
function removeOracle() {
# 确认当前session用户
session_user=`whoami`
[ $session_user == $oracle_user ] || echo "--请使用$oracle_user 用户执行脚本--" && exit 111
# 关闭监听
echo "--关闭监听lsnrctl--"
lsnrctl stop
# 关闭数据库
# alter pluggable database $pdb mounted;
echo "select status from v\$instance;
shutdown immediate
exit
" | sqlplus / as sysdba && echo "--关闭数据库shutdown--"
# 删除安装目录
if [ remove_dir_decide == 'Y' ]; then
if [ -d $ORACLE_BASE ]; then
read -t 120 -n1 -p "确认删除ORACLE_BASE目录: $ORACLE_BASE; Y or N" confirm
if [ $confirm != 'Y' ]; then
exit 111
fi
rm -rf $ORACLE_BASE && echo "--删除$ORACLE_BASE目录--"
else
echo "--没有发现 ORACLE_BASE 目录--"
exit 111
fi
fi
# 删除/usr/local/lib下的文件
rm -rf /urr/local/bin/coraenv
rm -rf /urr/local/bin/oraenv
rm -rf /urr/local/bin/dbhome
# 删除oratab
rm -rf /etc/oratab
# 删除用户和组(is Nt necessarily)
}
function main() {
# removeOracle
if [ $remove_sure == 'Y' ]; then
echo "--开始remove Oracle数据库软件--"
echo ""
removeOracle
else
echo "--config.yml文件中没有配置remove_sure--"
exit 111
fi
}
# main
apidemo.py文件内容为:
点击查看代码
# coding: utf-8
import jsonpath as jp
import json
import yaml
import re
import shutil
import os
import sys
class ApiDemo():
'''定义函数进行引用'''
# 数据读取
def get_data(self, res, keys, part=2):
'''res需要是一个字典'''
if res is not None:
try:
if part == 2:
value = jp.jsonpath(json.loads(res), '$..{0}'.format(keys))
else:
value = jp.jsonpath(json.loads(res), '$.{0}'.format(keys))
# 判断值
if value:
if len(value) == 1:
return value[0]
return value
except Exception as e:
return e
# 从yaml格式文件中获取参数配置
def get_yaml(self, file_name, keys):
'''
从yml文件中读取参数,返回一个字典
将结果处理为一个json对象
'''
with open(file_name, 'r', encoding="utf-8") as file:
file_read = file.read()
file.close()
file_read = yaml.load_all(file_read, Loader=yaml.FullLoader)
while True:
try:
values = json.dumps(next(file_read)) # 这个生成器一次就可以输出来
return self.get_data(values, keys)
except StopIteration:
break
# 对script_file中的配置进行修改
def replace_data(self, config_file, script_file, key):
'''
分别是配置文件
待修改的脚本文件
修改的配置项(变量)
:param config_file:
:param script_file:
:param key:
:return:
'''
old_value = key + '='
value = self.get_yaml(config_file, key)
if value:
if isinstance(value, int):
new_value = old_value + str(value)
elif isinstance(value, str):
new_value = old_value + value
elif isinstance(value, list):
new_value = old_value + str(value)
else:
print('')
print('%s的字符类型%s,程序只允许int和str变量类型' % (value, type(value)))
sys.exit()
print('\t将%s中的%s替换为%s' % (script_file, old_value, new_value))
with open(file=script_file, mode='r', encoding='UTF_8') as File:
data = File.read()
# print('匹配字符%s' % (re.findall(old_value, data)))
data = data.replace(old_value, new_value)
# print('替换后匹配字符%s' % (re.findall(new_value, data)))
with open(file=script_file, mode='w', encoding='UTF_8') as File:
File.write(data)
File.close()
# 修改文件配置全流程
def get_config_replace(self, path, config_file, template_script_file, script_file, key):
'''
path: 脚本路径
config_file: yml配置文件路径
template_script_file: shell模板文件
script_file: shell脚本文件
key: 是脚本需要修改配置的一个集合
:return:
'''
print('------------------------------------------')
os.chdir(path)
if os.path.isfile(template_script_file):
shutil.copyfile(template_script_file, script_file)
else:
print('模板文件%s不存在,请先生成模板文件' % (template_script_file))
sys.exit()
# config文件绝对路径:config_join_name
if os.path.isfile(template_script_file):
if os.path.isfile(script_file):
os.remove(script_file)
shutil.copyfile(template_script_file, script_file)
else:
shutil.copyfile(template_script_file, script_file)
# 进行配置项修改
config_list = self.get_yaml(config_file, key)
print('%s修改配置项集合: %s' % (script_file, config_list))
for config_item in config_list:
self.replace_data(config_file, script_file, config_item)
print("%s配置项修改结束" % (script_file))
print()
else:
print('模板文件%s不存在,请先生成模板文件' % (template_script_file))
sys.exit()
deal_config文件内容为:
点击查看代码
# coding: utf8
import os
import sys
import shutil
from apidemo import ApiDemo
# 获取数据的方法统一写入apidemo
api = ApiDemo()
py_home = os.getcwd()
os.chdir(py_home)
# config文件路径及文件名
config_path = py_home + '/../config'
config_name = 'config.yml'
template_config_name = 'template_' + config_name
config_join_name = os.path.join(config_path, config_name)
# remove脚本路径及脚本名
remove_path = py_home + '/../remove'
remove_script = 'remove.sh'
template_remove_script = 'template_' + remove_script
# initialization脚本路径及脚本名
init_path = py_home + '/../install/root'
init_script = 'initialization.sh'
template_init_script = 'template_' + init_script
# install脚本路径及脚本名
oracle_path = py_home + '/../install/oracle'
oracle_script = 'oracle_install.sh'
template_oracle_script = 'template_' + oracle_script
# 生成template文件
def template_create():
os.chdir(remove_path)
if os.path.isfile(template_remove_script):
# shutil.copyfile(remove_script, template_remove_script)
pass
else:
shutil.copyfile(remove_script, template_remove_script)
os.chdir(init_path)
if os.path.isfile(template_init_script):
pass
else:
shutil.copyfile(init_script, template_init_script)
os.chdir(oracle_path)
if os.path.isfile(template_oracle_script):
pass
else:
shutil.copyfile(oracle_script, template_oracle_script)
os.chdir(config_path)
if os.path.isfile(template_config_name):
# 调试期间一切修改操作改模板文件,调试完成后注释条件语句
# pass
if os.path.isfile(config_name):
os.remove(config_name)
shutil.copyfile(template_config_name, config_name)
else:
shutil.copyfile(template_config_name, config_name)
else:
shutil.copyfile(config_name, template_config_name)
# 生成安装数据库需要的脚本文件,脚本文件不带template
def config_remove():
# 已优化,待删除
os.chdir(remove_path)
if os.path.isfile(template_remove_script):
shutil.copyfile(template_remove_script, remove_script)
else:
print('模板文件%s不存在,请先生成模板文件' % (template_remove_script))
sys.exit()
# config文件绝对路径:config_join_name
if os.path.isfile(template_remove_script):
if os.path.isfile(remove_script):
os.remove(remove_script)
shutil.copyfile(template_remove_script, remove_script)
else:
shutil.copyfile(template_remove_script, remove_script)
# 进行配置项修改
config_list = api.get_yaml('../config/config.yml', 'remove_config_list')
for config_item in config_list:
print('处理的配置项为%s' % (config_item))
api.replace_data(config_join_name, remove_script, config_item)
print('-----------------------------')
print("%s配置文件配置完成" % (remove_script))
else:
print('模板文件%s不存在,请先生成模板文件' % (template_remove_script))
sys.exit()
def configuration_remove():
# remove.sh配置文件生成及修改配置项
api.get_config_replace(remove_path, config_join_name, template_remove_script, remove_script, 'remove_config_list')
def configuration_oracle_install():
# oracle_install.sh配置文件生成及修改配置项
api.get_config_replace(oracle_path, config_join_name, template_oracle_script, oracle_script,
'oracle_install_config_list')
def configuration_initialization():
# initialization.sh配置文件生成及修改配置项
api.get_config_replace(init_path, config_join_name, template_init_script, init_script, 'init_config_list')
if __name__ == '__main__':
# 生成template文件
template_create()
# 配置remove.sh
configuration_remove()
# 配置oracle_install.sh
configuration_oracle_install()
# 配置initialization.sh
configuration_initialization()