星期二, 1月 31, 2017

20170131 python Python程式設計實務_練習小記

20170131_python_Python程式設計實務_練習小記

Github:

Client: openSUSE Leap 42.2 with vi and PyCharm

今天接觸 os, shutil 以及 glob 模組
覺得接觸不同模組來練習, 感覺還不錯, 另外也更新心智圖 :)

練習相關檔案

檔案: 5-2.py

# -*- coding: utf-8 -*-
# 因為是學習 python, 所以用了很多 print() 來觀察
import os, shutil, glob
source_dir = "images/"
# 透過 os 模組來取得 / 目錄相關狀態
disk = os.statvfs("/")
print(disk)

# 目前可用空間計算
freespace = disk.f_bsize * disk.f_blocks
print(freespace)

# 透過 glob 模組來取得目前檔案, 以 list 型態存放
pngfiles = glob.glob(source_dir+"*.png")
jpgfiles = glob.glob(source_dir+"*.jpg")
giffiles = glob.glob(source_dir+"*.gif")
allfiles = pngfiles + jpgfiles + giffiles
print(allfiles)

allfilesize = 0
# allfilesize 型態是 int, 所以用 str轉型來顯示
print("allfilesize:  " + str(allfilesize))

# 使用 for 來計算目前檔案大小
for f in allfiles:
   allfilesize += os.path.getsize(f)
print("allfilesize:  " + str(allfilesize))

# 如果所有檔案大小 > 目前可用空間 顯示空間不足, 離開程式
if allfilesize > freespace:
   print("磁碟空間不足")
   exit(1)

# 設定輸出資料夾, 預設在該目錄下的 output
target_dir = source_dir + "output"
print("target_dir:  " + target_dir)

# 檢查 target_dir 是否存在, 存在就離開
if os.path.exists(target_dir):
   print("資料夾已存在")
   exit(1)

# 建立  target_dir
os.mkdir(target_dir)
imageno = 0

for f in allfiles:
   # split() 將字串根據指定字元切成 list
   # 這邊最主要要取出檔案名稱 filename
   print("---- loop start ----")
   dirname, filename = f.split('/')
   print(dirname)
   print(filename)
   # 使用 split() 切出檔案名稱還有副檔名
   mainname, extname = filename.split('.')
   print(mainname)
   print(extname)
   # 定義輸出的檔案名稱在 target_dir 下, 以 imageno 為序號加副檔名
   targetfile = target_dir + '/' + str(imageno) + '.' + extname
   print(targetfile)
   # 使用 shutil 複製檔案
   shutil.copyfile(f, targetfile)
   # 將 imageno 加1
   imageno += 1
   print("---- loop end ----")



~ enjoy it

星期一, 1月 30, 2017

Jupyterhub with openSUSE Leap 42.2 小記

Jupyterhub with openSUSE Leap 42.2 小記

之前的 jupyterhub 由於工作的關係,使用OS是配合 iCAIR 使用 CentOS 以及 ubuntu 版本
今天來建立openSUSE Leap 42.2 的 jupyterhub

OS: openSUSE Leap 42.2

測試安裝 jupyterhub 與 ansible 並容器化

安裝相關套件
# zypper  -n  install   python3  npm4  wget  unzip

# npm  install  -g   configurable-http-proxy

# zypper  -n  install  python3-pip

# pip3   install   jupyterhub   jupyter

# zypper   -n   install   python3-paramiko   python3-matplotlib   python3-numpy

# zypper  -n   install  ansible

使用 jupyterhub 指令執行
#jupyterhub

這樣就會在本機的 :8000 執行

為了以後方便執行, 接下來將 jupyterhub 容器化

# Jupyterhub / Ansible on openSUSE Leap 42.2
FROM opensuse:42.2
# Author
MAINTAINER Max Huang <sakana@cycu.org.tw>

# Install Python and pre-requisite packages
RUN \
 zypper -n  install \
  python3 \
  python3-pip \
  python3-paramiko \
  python3-matplotlib \
  python3-numpy \
  wget \
  npm4 \
  unzip

# run npm configurable-http-proxy
RUN npm install -g configurable-http-proxy

# Install Jupyterhub
RUN pip3  install --upgrade pip
RUN pip3  install  jupyter jupyterhub

# Install Ansible
RUN zypper -n install ansible

#expose ports
EXPOSE 8000

# create user
RUN useradd -m ansible && echo "ansible:2016StudyArea"|chpasswd

# Get playbook
RUN wget https://github.com/sakanamax/LearnJupyter/archive/master.zip -O /home/ansible/master.zip
RUN su - ansible -c "unzip master.zip"


# Define default command.
CMD ["jupyterhub"]

建立 docker image 並上傳到 dockerhub

下載方式

# docker  pull  sakana/jupyterhub

使用方式
# docker  run  -d  -p 8000:8000  sakana/jupyterhub

就會在本機的 port 8000 啟動 jupyterhub
帳號: ansible
密碼: 2016StudyArea

先記下來

~ enjoy it



星期日, 1月 29, 2017

20170129_python_Python程式設計實務_練習小記

20170129_python_Python程式設計實務_練習小記
Github:
Client: openSUSE Leap 42.2 with vi and PyCharm
昨天練習相關檔案
檔案: 2-3.py
# 匯入 requests
import requests
# 透過 requests.get 去抓 民視的網頁
www = requests.get( "http://m.ftv.com.tw/newslist.aspx?class=L" )
# 如果使用 print( www ) 會得到 網頁回覆, 例如 200
# 所以如果要列出網頁內容使用書上的 print( www.text )
print( www )
print( "=========================================" )
print( www.text )
檔案: 3-1.py
a, b = 2, 3
# 列出 a 以及 b
print( a, b)
# 將 a 與 b 交換
a, b = b, a
print( a, b)
檔案: 3-2.py
# 書上的作法是 a = range(5), 他其實是要列出 list 0 到 4
# 這個時候 print( a ) 在 python 3, 會出現 range(0, 5)
# 所以 python3 內的寫法, 如果要使用 a = range(5)來列出 list 0 - 4, 應該是 print( list(a) )
# 所以將程式碼改為
# 註解寫了中文在 python 好像就會產生 error, 先無視他吧
a = list( range(4) )
#print( a )
#print( list(a) )
# 同理可證 b
b = list( range(10, 15) )
# 不然 c = a + b 在 python 3 就會出現錯誤
c = a + b
print( "List a", a )
print( "List b", b )
print( "List a + List b", c )
Chapter 4
確認是否有安裝相關模組
主要練習為 python 3 版本
# zypper   search  numPy
Loading repository data...
Reading installed packages...
S | Name                     | Summary                              | Type      
--+--------------------------+--------------------------------------+-----------
 | python-numpy             | NumPy array processing for numbers-> | srcpackage
i | python-numpy             | NumPy array processing for numbers-> | package   
 | python3-numpy            | NumPy array processing for numbers-> | package   
# zypper   search   python3-matplo
Loading repository data...
Reading installed packages...
S | Name                         | Summary                                                 | Type   
--+------------------------------+---------------------------------------------------------+--------
 | python3-matplotlib           | Plotting Library for Python                             | package
預設沒有安裝 python3 的 numpy 以及 matplotlib 模組
安裝相關模組
# zypper   install   python3-matplotlib   python3-numpy
Loading repository data...
Reading installed packages...
Resolving package dependencies...
The following 16 NEW packages are going to be installed:
 libwebpmux1 python-Cycler python-Pillow python-functools32 python-matplotlib python-matplotlib-tk python-pyparsing
 python-python-dateutil python-pytz python-tk python3-dateutil python3-matplotlib python3-numpy python3-pyparsing
 python3-pytz python3-six
The following 2 recommended packages were automatically selected:
 python-Pillow python-matplotlib-tk
16 new packages to install.
Overall download size: 79.1 MiB. Already cached: 0 B. After the operation, additional 154.7 MiB will be used.
Continue? [y/n/? shows all options] (y): Y
檔案: 4-1.py
# -*- coding: utf-8 -*-
# 目前沒有成功, 圖形介面沒有顯示, 後續再來研究
import numpy as np
import matplotlib.pyplot as pt
x = np.arange(0, 360)
y = np.sin(x * np.pi / 180.0)
pt.plot(x, y)
pt.xlim(0, 360)
pt.ylim(-1.2, 1.2)
pt.title("SIN function")
pt.show()
今天先這樣
~ enjoy it

星期一, 1月 16, 2017

使用 ansible 快速佈署 nagios with openSUSE Leap 42.2

使用 ansible 快速佈署 nagios with openSUSE Leap 42.2

OS: openSUSE Leap 42.2

Notes:已經安裝 ansible 套件

上一篇文章是手動安裝 nagios 以及 client

接下來就是用 ansible 來進行快速佈署

相關檔案已經放在 GitHub 上面


下載相關檔案, 主要是 nagios_server_install.yml 以及 nagios_client_install.yml, 其他在 playbook 內都會透過 wget 來取得.

編輯或是下載 hosts 檔案, 建立相關群組

主要在 hosts 檔案內透過 群組來控制

# 安裝 nagios server
[NagiosServer]


# 安裝 nagios client
[NagiosClient]


把要安裝 nagios server 與 nagios client 的機器放到群組

要安裝 nagios server
就執行 ansible-playbook   nagios_server_install.yml

會被詢問 nagiosadmin 密碼以及要通知的 e-mail

nagios_server_install.yml 內容如下





---

#########################################################

#

- name: use when conditionals and setup module (facts)

hosts: all

tasks:

# 使用 setup moudule 列出 OS 種類

  - name: use setup module to list os distribution

# setup moudle 可以使用 filter 過濾相關內容

    setup: filter=ansible_distribution





#########################################################



- name: Install nagios server and run service

# 使用群組方式安裝 use group, 請配合 hosts 內的 [NagiosServer]

hosts: NagiosServer

become: True

# 透過提示來輸入相關變數

vars_prompt:

   - name: "nagiosadmin_password"

     prompt: "Enter nagiosadmin password"

# private 設定為 no 會顯示輸入的內容

     private: yes

# 這邊可以設定預設值

     default: nagiosadmin



   - name: "nagiosadmin_email"

     prompt: "Enter nagiosadmin e-mail"

     private: no

     default: nagios@localhost



tasks:

  - name: Install nagios and nrpe with openSUSE Leap

# 這邊使用 disable_recommends=no 加入zypper 建議的套件, 否則不會加入 apache2等其他套件

    zypper: name={{ item }} disable_recommends=no

    with_items:

      - nagios

      - monitoring-plugins

      - nrpe

      - monitoring-plugins-nrpe

    when: ansible_distribution == "openSUSE Leap"



#-------------------------------------------------------



# 設定 nagiosadmin 登入密碼

  - name: set nagiosadmin password

    shell: htpasswd2 -bc /etc/nagios/htpasswd.users nagiosadmin {{ nagiosadmin_password }}



#-------------------------------------------------------



# 由於 apache2.2 and apache2.4 相容性問題, 啟用 access_compat 模組

  - name: enable apache mod_access_compat

    shell: a2enmod mod_access_compat



#-------------------------------------------------------



# 使用修改過的 *.cfg 請詳見 github https://github.com/sakanamax/LearnAnsible/tree/master/playbook/general/nagios/files

  - name: fix localhost.cfg

    shell: wget  https://raw.githubusercontent.com/sakanamax/LearnAnsible/master/playbook/general/nagios/files/localhost.cfg -O /etc/nagios/objects/localhost.cfg

#      get_url:

#        url: https://raw.githubusercontent.com/sakanamax/LearnAnsible/master/playbook/general/nagios/files/localhost.cfg

#        dest: /etc/nagios/objects/localhost.cfg

#        backup: yes



#-------------------------------------------------------



# 使用修改過的 *.cfg 請詳見 github https://github.com/sakanamax/LearnAnsible/tree/master/playbook/general/nagios/files

  - name: use modified template.cfg

    shell: wget  https://raw.githubusercontent.com/sakanamax/LearnAnsible/master/playbook/general/nagios/files/templates.cfg -O /etc/nagios/objects/templates.cfg



#-------------------------------------------------------



# 使用修改過的 *.cfg 請詳見 github https://github.com/sakanamax/LearnAnsible/tree/master/playbook/general/nagios/files

  - name: use modified commands.cfg

    shell: wget  https://raw.githubusercontent.com/sakanamax/LearnAnsible/master/playbook/general/nagios/files/commands.cfg  -O /etc/nagios/objects/commands.cfg



#-------------------------------------------------------



# 使用修改過的 *.cfg 請詳見 github https://github.com/sakanamax/LearnAnsible/tree/master/playbook/general/nagios/files

# 用來當成監控 linux 公共服務的範本

  - name: use modified linuxPublic.cfg

    shell: wget  https://raw.githubusercontent.com/sakanamax/LearnAnsible/master/playbook/general/nagios/files/linuxPublic.cfg   -O /etc/nagios/objects/linuxPublic.cfg



#-------------------------------------------------------



# 使用修改過的 *.cfg 請詳見 github https://github.com/sakanamax/LearnAnsible/tree/master/playbook/general/nagios/files

# 用來當成監控 linux 服務的範本( 自己控管的主機 )

  - name: use modified linux.cfg

    shell: wget  https://raw.githubusercontent.com/sakanamax/LearnAnsible/master/playbook/general/nagios/files/linux.cfg    -O /etc/nagios/objects/linux.cfg



#-------------------------------------------------------



# 使用修改過的 *.cfg 請詳見 github https://github.com/sakanamax/LearnAnsible/tree/master/playbook/general/nagios/files

# 用來當成監控 windows 公共服務的範本( 非自己控管的主機 )

  - name: use modified windowsPublic.cfg

    shell: wget  https://raw.githubusercontent.com/sakanamax/LearnAnsible/master/playbook/general/nagios/files/windowsPublic.cfg    -O /etc/nagios/objects/windowsPublic.cfg



#-------------------------------------------------------



# 使用修改過的 *.cfg 請詳見 github https://github.com/sakanamax/LearnAnsible/tree/master/playbook/general/nagios/files

# 用來當成監控 windows 服務的範本( 自己控管的主機 )

  - name: use modified windows.cfg

    shell: wget  https://raw.githubusercontent.com/sakanamax/LearnAnsible/master/playbook/general/nagios/files/windows.cfg     -O /etc/nagios/objects/windows.cfg



#-------------------------------------------------------



# 使用修改過的 *.cfg 請詳見 github https://github.com/sakanamax/LearnAnsible/tree/master/playbook/general/nagios/files

# 用來當成監控 switch 的範本, 只監控 IP 不監控 snmp

  - name: use modified switchSimple.cfg

    shell: wget  https://raw.githubusercontent.com/sakanamax/LearnAnsible/master/playbook/general/nagios/files/switchSimple.cfg    -O /etc/nagios/objects/switchSimple.cfg



#-------------------------------------------------------



# 使用修改過的 *.cfg 請詳見 github https://github.com/sakanamax/LearnAnsible/tree/master/playbook/general/nagios/files

# 用來當成監控 rack 的範本, 只監控 IP

  - name: use modified rackHost.cfg

    shell: wget   https://raw.githubusercontent.com/sakanamax/LearnAnsible/master/playbook/general/nagios/files/rackHost.cfg    -O /etc/nagios/objects/rackHost.cfg



#-------------------------------------------------------



# 使用修改過的 *.cfg 請詳見 github https://github.com/sakanamax/LearnAnsible/tree/master/playbook/general/nagios/files

# 修改使用 cfg_dir= 參數於 nagios.cfg

  - name: use modified nagios.cfg

    shell: wget  https://raw.githubusercontent.com/sakanamax/LearnAnsible/master/playbook/general/nagios/files/nagios.cfg      -O /etc/nagios/nagios.cfg



#-------------------------------------------------------



# 建立相關工作目錄

  - name:  create working dir for nagios *.cfg

    shell: mkdir  /etc/nagios/{servers,pcs,racks,switches,projects,labs}





#-------------------------------------------------------

# 使用 replace module 去修改 nagiosadmin 通知 e-mail

  - name: Set nagiosadmin e-mail

    replace:

      dest: /etc/nagios/objects/contacts.cfg

      regexp: 'nagios@localhost'

      replace: "{{ nagiosadmin_email }}"

      backup: yes



#-------------------------------------------------------



# 設定 apache2 啟動與開機啟動

  - name: Set apache2 enable and run

    service: name=apache2 state=started enabled=yes



#-------------------------------------------------------



# 設定 nagios 啟動與開機啟動

  - name: Set nagios enable and run

    service: name=nagios state=started enabled=yes



#-------------------------------------------------------





要安裝 nagios client
就執行 ansible-playbook   nagios_client_install.yml

會被詢問 nagios server 的IP

nagios_client_install.yml 的內容如下





#########################################################

#

- name: use when conditionals and setup module (facts)

hosts: all

tasks:

# 使用 setup moudule 列出 OS 種類

  - name: use setup module to list os distribution

# setup moudle 可以使用 filter 過濾相關內容

    setup: filter=ansible_distribution





#########################################################



- name: Install nagios client and run service

# 使用群組方式安裝 use group, 請配合 hosts 內的 [NagiosServer]

hosts: NagiosClient

become: True

# 透過提示來輸入相關變數

vars_prompt:

   - name: "nagios_ip"

     prompt: "Enter nagios server's ip"

# private 設定為 no 會顯示輸入的內容

     private: no

# 這邊可以設定預設值

#       default:

tasks:

  - name: Install nrpe with openSUSE Leap

# 這邊使用 disable_recommends=no 加入zypper 建議的套件, 否則不會加入 apache2等其他套件

    zypper: name={{ item }} disable_recommends=no

    with_items:

      - nrpe

      - monitoring-plugins

      - monitoring-plugins-nrpe

    when: ansible_distribution == "openSUSE Leap"



#-------------------------------------------------------



# 使用修改過的 *.cfg 請詳見 github https://github.com/sakanamax/LearnAnsible/tree/master/playbook/general/nagios/files

# 加入相關 commands

  - name: use modified nrpe.cfg

    shell: wget  https://raw.githubusercontent.com/sakanamax/LearnAnsible/master/playbook/general/nagios/files/nrpe.cfg  -O /etc/nrpe.cfg



#-------------------------------------------------------



# 使用 replace module 去修改 allowed_hosts

  - name: Set allowed_hosts

    replace:

      dest: /etc/nrpe.cfg

      regexp: 'allowed_hosts=127.0.0.1'

      replace: "allowed_hosts=127.0.0.1,{{ nagios_ip }}"

      backup: yes



#-------------------------------------------------------



# 設定 nrpe 啟動與開機啟動

  - name: Set nrpe enable and run

    service: name=nrpe state=started enabled=yes



#-------------------------------------------------------





- name: Copy client config to folder

# 使用群組方式安裝 use group, 請配合 hosts 內的 [NagiosServer]

hosts: NagiosServer

become: True

# 透過提示來輸入相關變數

vars_prompt:

   - name: "cfg_type"

     prompt: "Enter client config template name"

# private 設定為 no 會顯示輸入的內容

     private: no

# 這邊可以設定預設值

     default: linux.cfg



   - name: "cfg_folder"

     prompt: "Enter client config save folder name in /etc/nagios"

     private: no

     default: labs



tasks:

  - name: copy template config to folder

#      shell: cp  /etc/nagios/objects/{{ cfg_type }}  /etc/nagios/{{ cfg_folder }}/{{ hostvars['test4']['ansible_default_ipv4'].address }}.cfg

# 這邊卡了我很久, 這邊透過 hostvars 與 item ( with_item ) 來指定 facts 感謝 https://groups.google.com/forum/#!topic/ansible-project/X6zCbW6S1fo

    shell: cp  /etc/nagios/objects/{{ cfg_type }}  /etc/nagios/{{ cfg_folder }}/{{ hostvars[item]['ansible_default_ipv4'].address }}.cfg

# 這邊透過 with_item 來使用 loop , 將 NagiosClient 群組內的主機放進來

    with_items: "{{ groups['NagiosClient'] }}"



# 將預設 IP 改為 client IP

  - name: replace with client's ip

# 使用 replace module 更改 IP

    replace:

      dest: /etc/nagios/{{ cfg_folder }}/{{ hostvars[item]['ansible_default_ipv4'].address }}.cfg

      regexp: '192.168.3.129'

      replace: "{{ hostvars[item]['ansible_default_ipv4'].address }}"

#        backup: yes

# 這邊 with_items 沒有跟 replace 對齊造成 loop 失敗花了我很多時間, 下次要注意

    with_items: "{{ groups['NagiosClient'] }}"



# 將預設 hostname 更改

  - name: replace with client's hostname

    replace:

      dest: /etc/nagios/{{ cfg_folder }}/{{ hostvars[item]['ansible_default_ipv4'].address }}.cfg

      regexp: 'suseserver129'

      replace: "{{ hostvars[item]['ansible_hostname'] }}"

#        backup: yes

    with_items: "{{ groups['NagiosClient'] }}"





#-------------------------------------------------------



# 將 nagios reload

  - name: Set nagios reload conf

    service: name=nagios state=reloaded



#-------------------------------------------------------


這樣以後佈署上面就輕鬆多了

~ enjoy it