操作系统:Red Hat Enterprise Linux Server release 7.2 (Maipo)
python版本:python2.7
oracle版本:11g
oracle客户端是Oracle instant client, 除了安装basic package外, 还需要安装sdk包, 否则cx_oracle无法编译,其主要的功能是用来实现oracle数据库和python进行连接。
官网链接:https://cx-oracle.readthedocs.io/en/latest/installation.html#installing-cx-oracle-on-linux
cx_Oracle-5.2.1-11g-py27-1.x86_64.rpm(这个是python2.7,根据python版本下对应的):
官网下载链接:https://pypi.org/project/cx_Oracle/5.2.1/#files
# wget https://files.pythonhosted.org/packages/93/d8/3acdd4d3176a877a396647f55191549b8624f1157bf2e1ada6bb1f92615d/cx_Oracle-5.2.1-11g-py27-1.x86_64.rpm
下载地址:https://www.oracle.com/technetwork/topics/linuxx86-64soft-092277.html
instantclient-basic-linux.x64-11.2.0.4.0.zip:
# wget https://download.oracle.com/otn/linux/instantclient/11204/instantclient-basic-linux.x64-11.2.0.4.0.zip?AuthParam=1542071440_6811e77c541321f8a3c1ac29cfb01fbe
instantclient-sdk-linux.x64-11.2.0.4.0.zip:
# wget https://download.oracle.com/otn/linux/instantclient/11204/instantclient-sdk-linux.x64-11.2.0.4.0.zip?AuthParam=1542071548_c5cc6be3e8c987b70e582bff568d132e
其实就是下载好这几个包:
cx_Oracle-5.2.1-11g-py27-1.x86_64.rpm
、instantclient-sdk-linux.x64-11.2.0.4.0.zip
、instantclient-basic-linux.x64-11.2.0.4.0.zip
,需要注册账号进行认证下载,我们可以通过此百度网盘链接下载到这3个包!!!
# rpm -ivh cx_Oracle-5.2.1-11g-py27-1.x86_64.rpm ###python包安装
# mkdir /usr/local/oracle
# cd /usr/local/oracle
### 把刚才zip文件移动到这里,会生成一个目录
# unzip instantclient-sdk-linux-11.2.0.4.0.zip
# unzip instantclient-basic-linux.x64-11.2.0.4.0.zip
### 加入环境变量
# vim /etc/profile ###在末尾加入即可
export ORACLE_HOME=/usr/local/oracle/instantclient_11_2
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$ORACLE_HOME
# . /etc/profile 或 source /etc/profile ###声明环境变量
# cd /usr/local/oracle/instantclient_11_2
# ln -s libclntsh.so.11.1 libclntsh.so
# python
Python 2.7.5 (default, Oct 11 2015, 17:47:16)
[GCC 4.8.3 20140911 (Red Hat 4.8.3-9)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import cx_Oracle ###执行没有报错即为正确
提示
:因为此处我们使用了环境变量来连接oracle数据库,因此我们在使用linux的定时任务时,需要先source /etc/profile
在使用python+脚本来运行,eg:* * * * * source /etc/profile && /bin/python /home/oracle/scripts/test.py
$ sqlplus / as sysdba ###在oracle用户查看字符集
...
SQL> SELECT value$ FROM sys.props$ WHERE name = 'NLS_CHARACTERSET' ;
VALUE$
--------------------------------------------------------------------------------
ZHS16GBK
SQL> show parameter service_names; ###查看service_name
NAME TYPE VALUE
------------------------------------ ----------- ------------------------------
service_names string dream
import csv
import cx_Oracle
import os
import datetime
### 昨天
yesterday_time = int((datetime.datetime.now()-datetime.timedelta(days=1)).strftime('%Y%m%d0000'))
### 改变字符集,否则执行的命令结果会乱码(即使oracle字符集为ZHS16GBK)
os.environ['NLS_LANG'] = 'SIMPLIFIED CHINESE_CHINA.UTF8'
### 判断目录是否存在,不存在就创建目录
dirs=os.path.split(os.path.realpath(__file__))[0] + "/csv_data/"
if not os.path.exists(dirs):
os.makedirs(dirs)
### 实现以python脚本的路径来做相对路径
test_csv = dirs + "test.csv"
### 连接到oracle库;格式:用户名/密码@IP:端口/service_name
connection = "TEST/[email protected]/dream"
orcl = cx_Oracle.connect(connection)
curs = orcl.cursor()
### 如果我们sql很长,我们想把时间变量传入进去,我们使用"""来进行块注释,然后通过“+”来拼接和双引号传参数
sql_test = """
sql内容
""" + "AND TIME_ID = %s" %(yesterday_time) + """
sql内容
"""
### 执行sql
curs.execute(sql_test)
### 表头
li_title = []
for title in curs.description:
print (title)
li_title.append(title[0])
print (li_title)
### 我们看到我们sql的执行结果,做出对应的写入之类的操作
for i in curs:
print (i)
### 关闭连接
curs.close()
orcl.close()
# wget http://caspian.dotconf.net/menu/Software/SendEmail/sendEmail-v1.56.tar.gz
# tar xf sendEmail-v1.56.tar.gz
# cd sendEmail-v1.56/
# mv sendEmail /usr/local/bin/
sendEmail -f 主题名 -t 收件人 \
-s smtp.163.com(也可以写mail服务器IP) -u "邮件主题" -o message-content-type=html \
-o message-charset=utf8 -xu 账号 -xp 密码 -m "邮件内容"
参数说明:
/usr/local/bin/sendEmail 命令主程序
-f 发件人邮箱
-s smtp.163.com 发件人邮箱的smtp服务器或者IP
-u "邮件主题" 邮件的标题
-o message-content-type=html 邮件内容的格式,html表示它是html格式
-o message-charset=utf8 邮件内容编码
-xu 账号 发件人邮箱的用户名
-xp 密码 发件人邮箱密码
-m "邮件内容" 邮件的具体内容
此处我的test.csv是个csv文件即以逗号为分割的文件,下面的方式我们可以完成附件的发送,subject变量是解决标题乱码!!!
#!/bin/bash
result="/home/oracle/scripts/csv_data/test.csv"
subject=`echo -n "哈哈哈" | base64`
/usr/local/bin/sendEmail -f 主题名 -s IP:25 -u "=?utf-8?b?${subject}?=" -o message-content-type=html -o message-charset=utf-8 -xu 账号 -xp 密码 -t 收件人 -m `cat ${result}` -a ${result}
其他参数:
Required:
-f ADDRESS from (sender) email address
* At least one recipient required via -t, -cc, or -bcc
* Message body required via -m, STDIN, or -o message-file=FILE
Common:
-t ADDRESS [ADDR ...] to email address(es)
-u SUBJECT message subject
-m MESSAGE message body
-s SERVER[:PORT] smtp mail relay, default is localhost:25
Optional:
-a FILE [FILE ...] file attachment(s)
-cc ADDRESS [ADDR ...] cc email address(es)
-bcc ADDRESS [ADDR ...] bcc email address(es)
-xu USERNAME username for SMTP authentication
-xp PASSWORD password for SMTP authentication
Paranormal:
-b BINDADDR[:PORT] local host bind address
-l LOGFILE log to the specified file
-v verbosity, use multiple times for greater effect
-q be quiet (i.e. no STDOUT output)
-o NAME=VALUE advanced options, for details try: --help misc
-o message-content-type=
-o message-file=FILE -o message-format=raw
-o message-header=HEADER -o message-charset=CHARSET
-o reply-to=ADDRESS -o timeout=SECONDS
-o username=USERNAME -o password=PASSWORD
-o tls= -o fqdn=FQDN
Help:
--help the helpful overview you're reading now
--help addressing explain addressing and related options
--help message explain message body input and related options
--help networking explain -s, -b, etc
--help output explain logging and other output options
--help misc explain -o options, TLS, SMTP auth, and more
注意:我们这样的文件是没有标题的,需要我们自行添加!!!
#!/bin/bash
### 格式:用户名/密码@IP:端口/service_name
sqlplus -s TEST/[email protected]/dream <
#!/bin/bash
result="文件路径"
subject=`echo -n "哈哈哈" | base64`
### 这里我把message-charset修改为gb2312,utf-8会乱码,这个自行调试
/usr/local/bin/sendEmail -f 主题名 -s IP:25 -u "=?utf-8?b?${subject}?=" -o message-content-type=html -o message-charset=gb2312 -xu 账号 -xp 密码 -t 收件人 -m `cat ${result}` -a ${result}