1. 程式人生 > >Linux中cx_oracle和sendEmail安裝及操作

Linux中cx_oracle和sendEmail安裝及操作

一、cx_oracle安裝及操作


作業系統:Red Hat Enterprise Linux Server release 7.2 (Maipo)
python版本:python2.7
oracle版本:11g

1、簡介與下載

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.rpminstantclient-sdk-linux.x64-11.2.0.4.0.zipinstantclient-basic-linux.x64-11.2.0.4.0.zip,需要註冊賬號進行認證下載,我們可以通過此百度網盤連結下載到這3個包!!!

2、安裝

# 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

3、測試

# 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

4、指令碼中使用操作

(1)oracle查詢
$ 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
(2)操作
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'

### 實現以python指令碼的路徑來做相對路徑
test_csv = os.path.split(os.path.realpath(__file__))[0]+ "/csv_data/" + "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)

### 我們看到我們sql的執行結果,做出對應的寫入之類的操作
for i in curs:
    print (i)

二、sendEmail安裝及操作


1、安裝

# 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/ 

2、傳送郵件

(1)直接傳送
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 "郵件內容"                  郵件的具體內容
(2)指令碼傳送csv檔案

此處我的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=<auto|text|html>
        -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=<auto|yes|no>         -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