2018年9月1日 星期六

Centos GUI Webserver 設定

新灌的一台Centos7可以做以下的設定

語系設定:
- sudo localectl set-locale LC_CTYPE=zh_TW.UTF-8

修改ssh port
- http://linux.vbird.org/linux_server/0310telnetssh.php#ssh_port
- sudo firewall-cmd --add-port 2222/tcp --permanent
- sudo systemctl restart sshd

修改mail server
- http://choons-world.blogspot.com/2017/11/
- 開機發信排程:
| # wait 2min to sure all service open
| (sleep 120
| echo -e "`who -b`\n`ifconfig`\n`systemctl list-units | grep running`\n\n\n\nSettings of mail: https://choons-world.blogspot.com/2017/11/centos-sendmail-by-gmail.html" | mail -s "Server on" xxxxx@gmail.com
| )&

XRDP設定:
- http://choons-world.blogspot.com/2017/07/centos7-xrdp.html

Lamp設定教程:
- http://choons-world.blogspot.com/2017/07/centos7-apachephp7mariadbphpmyadmin.html
- selinux可以設為perminant 這樣比較好設定
- 注意:如果用yum方式安裝 請先安裝php才安裝phpmyadmin
- Webserver路徑:/var/www/html/
- 注意權限問題 要讓apache可讀(如要修改及生成文件就要可寫)

Wordpress 移機(可忽略)
- 路徑: /var/www/html/wordpress
- 需要備份的話直接備份這個資料夾和資料庫,資料庫密碼詳見wp-config.php
- 移機簡略步驟:
| 1 複製及權限
| > sudo mv wordpress/ /var/www/html/
| > ll
| > cd /var/www/html/
| > lll
| > ll
| > chgrp -R apache wordpress
| > sudo chgrp -R apache wordpress
| 2 備份資料庫然後再匯入到新的一台 (帳號看 wp-config.php)
| 3 修改基礎設定(例如:網址等)
| 4 開帳號讓ftp使用 記得設為nologin
| > sudo useradd -d /var/www/html/ -s /sbin/nologin wordpress
| > sudo passwd wordpress
| 5 設置 ftp
| - http://linux.vbird.org/linux_server/0410vsftpd.php#server
| | > yum -y install vsftpd
| | > firewall-cmd --permanent --add-service=ftp
| | > vim /etc/vsftpd/vsftpd.conf
| | ====
| | anonymous_enable=NO
| | local_enable=YES
| | write_enable=YES
| | xferlog_std_format=YES
| | chroot_local_user=YES
| | use_localtime=YES
| | allow_writeable_chroot=YES
| | userlist_deny=YES
| | ==== #userlist_deny為YES 則user_list文件裡的user可以登入ftp; 假如為NO 則user_list文件裡user不可以登入ftp
| | > systemctl restart vsftpd
| | > systemctl enable vsftpd
| | > firewall-cmd --permanent --add-port=21/tcp
| | > firewall-cmd --permanent --add-service=ftp
| | > firewall-cmd —reload
| 6 更換owner
| > sudo chown -R wordpress wordpress
| 7 新增user wordpress登入ftp權限,給予wordpress權限給user
| > vim /etc/vsftpd/user_list
| | ==
| | wordpress
| | ==

crontab設定:
| $ cat /etc/crontab
| SHELL=/bin/bash
| PATH=/sbin:/bin:/usr/sbin:/usr/bin
| MAILTO=root
|
| # For details see man 4 crontabs
|
| # Example of job definition:
| # .---------------- minute (0 - 59)
| # | .------------- hour (0 - 23)
| # | | .---------- day of month (1 - 31)
| # | | | .------- month (1 - 12) OR jan,feb,mar,apr ...
| # | | | | .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
| # | | | | |
| # * * * * * user-name command to be executed
| 0 0 1,15 * * root /opt/gitlab/bin/gitlab-rake gitlab:backup:create CRON=1
| 0 0 1,15 * * root gitlab-ctl restart
| 0 3 * * * root sh -c "sync; echo 3 > /proc/sys/vm/drop_caches"

gitlab (可忽略)
- http://choons-world.blogspot.com/2017/08/install-gitlab-to-own-pc.html
- 記得備份後再更新
| > sudo yum install -y gitlab-ce
| - 更新時如果跨minor version 必須更新到該minor最後一版才能再升級到新的minor version
| - 例如:1.2.3 > 1.2.9 > 1.3.9 > 1.4.2
- 備份查看crontab每15天備份一次 還有重啟動1次
- 本地備份位置: /var/opt/gitlab/backups/
- 備份指令 /opt/gitlab/bin/gitlab-rake gitlab:backup:create CRON=1
- 因為現在的gitlab內容較大 如果備份頻率較高,建議把舊的版本刪掉(可能只保留3個檔案)
- 跨機還原需要安裝與原版本的gitlab,如果需要新版本,則還原後再更新,choonsword裡有簡易的指令,但建議觀看網絡教程
- 設定檔 /etc/gitlab/gitlab.rb
| 每次修改完需要下以下兩個指令
| > sudo gitlab-ctl reconfigure
| > sudo gitlab-ctl restart

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

2018年8月27日 星期一

SSH 修改port

1. vim /etc/ssh/sshd_config
====
Port 2222
====

2. systemctl restart sshd.service

3. By default, SELinux only allows SSH on the port 22. We must change this to our new port. In our example, we are using 2222 but you should replace this number with the number of your port in the below command, which uses semanage port to configure ports in the SELinux policy:
semanage port -a -t ssh_port_t -p tcp 2222

4. firewall-cmd --permanent --zone=public --add-port=2222/tcp
5. firewall-cmd --reload


#https://www.globo.tech/learning-center/change-ssh-port-centos-7/

2018年8月23日 星期四

Drupal安裝

Drupal是一個強大的CMS/CMF。他提供給專業的工程師進行開發

安裝過程:

1. 官網下載最新版
https://www.drupal.org/download

2. 把檔案解壓縮的document root
3. 把group給予apache,並可以rewrite
3. 複製 /sites/default 地下的default檔案
4. 新增 /sites/default/files/translations folder
5. apache必須可以rewrite同時 AllowOverride 設 All 以讓htaccess可控制
6. 新增db user並給drupal
7. 報告》狀態報告 檢查 紅黃色提示
   - trusted_host_patterns  白名單
|   $settings['trusted_host_patterns'] = array(
|  '^localhost$',
|  '^127\.0\.0\.1$',
|  '^www\.pcsetting\.com$',
|);
8. 模組下載頁面:https://www.drupal.org/project/project_module
   擴展》安裝新模組,直接輸入要安裝的模組或直接把解壓縮檔放到modules裡,然後再到擴展裡按安裝  例子:滑鼠clickon就dropdown的套件 https://www.drupal.org/project/admin_toolbar
9. themes下載頁面:https://www.drupal.org/project/project_theme
   方法同上




#參考教材:https://www.pcsetting.com/devtools/60?page=0%2C0
三大CMS比較:https://www.kingman.idv.tw/technology-news/142-how-to-choose-wordpress-joomla-and-drupal-to-build-a-website.html
台灣支援站:https://drupaltaiwan.org/

2018年3月19日 星期一

Docker command

Docker 是在本機OS上執行虛擬化,與傳統的虛擬方法不太一樣。
以下是Docker的常用指令

docker images //show local docker images
docker search python //search docker images online
docker pull python // pull store images to local
docker run -t -i python /bin/bash  //run docker images(name:python) by bash
-i : Keep STDIN open even if not attached ,無論有無 Attach ,都會確保 STDIN 有持續開啟
-t : Allocate a pseudo-tty 分配一個 tty
docker commit -m "Add pandas" -a "add pandas" f446ce29c915 python
-m : same like git
-a : 指定更新的使用者信息
(一堆數字) 建立映像檔的容器的 ID
(string) images and tag
docker save -o python3.tar python //save imaes to tar file
docker rmi centos/python-35-centos7   //delete local docker images
sudo docker load < ubuntu_14.04.tar //load tar to local docker

如果要在VM裡的OS測試Docker,則該VM必須要設定 ParavirtualizationInterface 為 Hyper-V

2017年11月28日 星期二

Centos sendmail by gmail

#install ssmtp
sudo yum install ssmtp -y
sudo cp /etc/ssmtp/ssmtp.conf /etc/ssmtp/ssmtp.conf.bak

vim /etc/ssmtp/ssmtp.conf
====
root=xxxxx@gmail.com
mailhub=smtp.gmail.com:587
Hostname=localhost
FromLineOverride=YES
UseTLS=YES
UseSTARTTLS=YES
AuthUser=xxxx@gmail.com
AuthPass=xxxxx
=====

#send test mail by ssmtp
echo "This is a test" | ssmtp recipient@your.domain.com

#change command mail default
alternatives --config mta
(choose)

echo "This is a test"  | mail -s "Title" xxxxx@gmail.com

#set server reboot and mail to admin
sudo vim /etc/rc.d/rc.local 
===
# wait 2min to sure all service open
(sleep 120
echo -e "`who -b`\n`ifconfig`\n`systemctl list-units | grep running`" | mail -s "Server on" xxxx@gmail.com
)&
====
sudo chmod u+x /etc/rc.d/rc.local


Install Juypter

#install jupyter
sudo pip3 install jupyter
# generate config file
jupyter notebook --generate-config

#generate hashcode
python3
===
from notebook.auth import passwd
passwd()
(password)
(password)
...
sha1:63d137bxxxxxxxxxxxxxxxxxxxxxxxxxx
exit()
=====

vim ~/.jupyter/jupyter_notebook_config.py
====
c.NotebookApp.ip='*'
c.NotebookApp.password = u'sha:ce...刚才复制的那个密文'
c.NotebookApp.open_browser = False
c.NotebookApp.port =8888 #随便指定一个端口
====

# firewall
firewall-cmd --zone=public --add-port=8888/tcp --permanent
systemctl restart firewalld.service
#or use ssh tunnel
ssh username@address_of_remote -L127.0.0.1:1234:127.0.0.1:8888 

#centos restart autostart by screen 
vim /etc/crontab
===
@reboot username screen -dmS jupyter jupyter notebook
===

screen -r jupyter
#===Int Screen: Jupyter====
#can see information
#========

## if open multijuyter must type following command first
unset XDG_RUNTIME_DIR

ref:
http://blog.leanote.com/post/jevonswang/%E8%BF%9C%E7%A8%8B%E8%AE%BF%E9%97%AEjupyter-notebook
http://jupyter.org/install.html

2017年8月13日 星期日

Install Gitlab to own PC

Install Gitlab to own PC

1. Install and configure the necessary dependencies

sudo yum install curl policycoreutils openssh-server openssh-clients -y
sudo systemctl enable sshd
sudo systemctl start sshd
sudo yum install postfix
sudo systemctl enable postfix
sudo systemctl start postfix
sudo firewall-cmd --permanent --add-service=http
sudo systemctl reload firewalld

2. Add the GitLab package server and install the package

curl -sS https://packages.gitlab.com/install/repositories/gitlab/gitlab-ce/script.rpm.sh | sudo bash
sudo yum install gitlab-ce -y

3. Configure and start GitLab

sudo gitlab-ctl reconfigure

4. Change hostname and port number

vim /etc/gitlab/gitlab.rb
===
external_url "http://localhost:9999" #change port to 9999
gitlab_rails['gitlab_shell_ssh_port'] = 9998 #change ssh port to xxxxx,if your ssh port changed

# set mail server(gmail)
gitlab_rails['smtp_enable'] = true
gitlab_rails['smtp_address'] = "smtp.gmail.com"
gitlab_rails['smtp_port'] = 587
gitlab_rails['smtp_user_name'] = "my.email@gmail.com"
gitlab_rails['smtp_password'] = "my-gmail-password"
gitlab_rails['smtp_domain'] = "smtp.gmail.com"
gitlab_rails['smtp_authentication'] = "login"
gitlab_rails['smtp_enable_starttls_auto'] = true
gitlab_rails['smtp_tls'] = false
gitlab_rails['smtp_openssl_verify_mode'] = 'peer' # Can be: 'none', 'peer', 'client_once', 'fail_if_no_peer_cert', see http://api.rubyonrails.org/classes/ActionMailer/Base.html

===
sudo gitlab-ctl reconfigure
sudo gitlab-ctl restart

Backup:
> /opt/gitlab/bin/gitlab-rake gitlab:backup:create CRON=1
>  ls
1510848068_2017_11_17_9.4.4_gitlab_backup.tar

Auto Backup:
>vi /etc/crontab
=======
// Backup in  1st & 15th day month
0 0 1,15 * * root /opt/gitlab/bin/gitlab-rake gitlab:backup:create CRON=1
=======

Recovery:
Must same version gitlab
After set gitlab.rb
Stop gitlab servies
> gitlab-ctl stop unicorn
> gitlab-ctl stop sidekiq
> gitlab-ctl status

Paste the backup file to /var/opt/gitlab/backups/
> 1530366625_2018_06_30_10.1.4_gitlab_backup.tar

recovery (use timestamp of backup file)
> gitlab-rake gitlab:backup:restore BACKUP=1530366625_2018_06_30_10.1.4
> gitlab-ctl restart

Check gitlab:
> gitlab-rake gitlab:check SANITIZE=true

Update Gitlab:
1. Make a backup (Optional)
If you would like to make a backup before updating, the below command will backup data in /var/opt/gitlab/backups by default.

> sudo gitlab-rake gitlab:backup:create STRATEGY=copy

2. Update GitLab
Update to the latest version of GitLab.

> sudo yum install -y gitlab-ce


ref:
https://about.gitlab.com/installation/#centos-7

2017年8月12日 星期六

Mongo Repica Set 設定

首先設定讓所有PC接受SSH 認證

使用AP或dhcp server 鎖好每台電腦的IP

# 切換到root
su

# 接下來,修改hosts,讓主機們有不同的代號(使用x.x.x.160)
sudo vim /etc/hosts
===
192.168.1.160 mongodb-primary
192.168.1.161 mongodb-secondary
192.168.1.162 mongodb-arbiter
===

# 把修改好的hosts傳到每台機器
for i in {161..162};
do
sudo scp /etc/hosts root@192.168.1.$i:/etc/hosts
done;

# 新增mongodb 的repo
vim /etc/yum.repos.d/mongodb-org-3.4.repo
===
[mongodb-org-3.4]
name=MongoDB Repository
baseurl=https://repo.mongodb.org/yum/redhat/$releasever/mongodb-org/3.4/x86_64/
gpgcheck=1
enabled=1
gpgkey=https://www.mongodb.org/static/pgp/server-3.4.asc
===
# 安裝mongodb
yum install -y mongodb-org

# 生成認證key碼
openssl rand -base64 741 > /var/lib/mongo/mongodb-keyfile
chmod 600 /var/lib/mongo/mongodb-keyfile
chown mongod.mongod /var/lib/mongo/mongodb-keyfile


# 把repo傳到每台機器,安裝mongo,key設定
for i in {161..162};
do
sudo scp /etc/yum.repos.d/mongodb-org-3.4.repo root@192.168.1.$i:/etc/yum.repos.d/mongodb-org-3.4.repo
ssh root@192.168.1.$i " yum install -y mongodb-org"
sudo scp /var/lib/mongo/mongodb-keyfile root@192.168.1.$i:/var/lib/mongo/mongodb-keyfile
ssh root@192.168.1.$i "
chmod 600 /var/lib/mongo/mongodb-keyfile;
chown mongod.mongod /var/lib/mongo/mongodb-keyfile;
";
done;

### CONFIG REPICA SET
mkdir /var/lib/mongo-cfg
chown -R mongod:mongod /var/lib/mongo-cfg

vim /etc/mongod.conf
====
# for documentation of all options, see:
#   http://docs.mongodb.org/manual/reference/configuration-options/

security: #security part edit by choon
  authorization: enabled
  clusterAuthMode: keyFile
  keyFile: /var/lib/mongo/mongodb-keyfile

# network interfaces
net:
  port: 27017
  bindIp: 0.0.0.0  # Listen to All - edit by choon

replication:
  replSetName: config-server # - edit by choon

# where to write logging data.
systemLog:
  destination: file
  logAppend: true
  path: /var/log/mongodb/mongod.log

# Where and how to store data.
storage:
  dbPath: /var/lib/mongo
  journal:
    enabled: true
#  engine:
#  mmapv1:
#  wiredTiger:

# how the process runs
processManagement:
  fork: true  # fork and run in background
  pidFilePath: /var/run/mongodb/mongod.pid

#operationProfiling:

#sharding:

## Enterprise-Only Options

#auditLog:

#snmp:
===

# 打開mongo
systemctl start mongod
# sudo mongod --config /etc/mongod.conf

# 打開其他台PC的mongo
for i in {163..164};
do
scp /etc/mongod.conf root@192.168.1.$i:/etc/mongod.conf
ssh root@192.168.1.$i "
systemctl start mongod
# mongod --config /etc/mongod.conf
"
done;

====

# 連結本地端
mongo 127.0.0.1
===
use admin
-------
db.createUser( {
    user: "root",
    pwd: "password#",
    roles: [ { role: "root", db: "admin" } ]
  });
------
use admin
# 登入
db.auth("root","password")
# intiate repica set
rs.initiate()
# 查看設定
rs.conf()
rs.add("mongodb-secondary")
rs.addArb("mongodb-arbiter")
rs.status()
exit
===


Ref:
https://docs.mongodb.com/manual/tutorial/deploy-replica-set/

2017年8月2日 星期三

PXE 結合 Kickstart 一鍵安裝CentOS

繼之前的PXE服務後(choons-world.blogspot.tw/2017/07/pxeos.html),這次結合CentOS Kickstart安裝Centos
讓使用者一健安裝好自定義的os

# 首先, 先建立一個ks檔案
vim /install/kickstart/firstKickStart.ks
====
#version=DEVEL
# System authorization information 使用加密協定sha512
auth --enableshadow --passalgo=sha512
# Use network installation
url --url="http://10.0.2.254/centos7"
# Use graphical install 用文字模式安裝
text
# Run the Setup Agent on first boot
firstboot --disable
ignoredisk --only-use=sda
# Keyboard layouts
keyboard --vckeymap=us --xlayouts='us'
# System language
lang en_US.UTF-8

# Network information(hard pc:--device=eno1)
network  --bootproto=dhcp --device=enp0s3 --ipv6=auto --activate
network  --hostname=localhost.localdomain

# Root password(--plaintext abc1234) plaintext是明碼 iscrryted是sha512加密後的字串
rootpw --iscrypted $6$3cHk0s2ZwYgs5$B66RHGSUflDgFF1
# SELinux configuration
selinux --permissive
# System services
services --enabled="chronyd"
# System timezone
timezone Asia/Taipei --isUtc
# System bootloader configuration
bootloader --append=" crashkernel=auto" --location=mbr --boot-drive=sda
# bootloader --append="rhgb quiet crashkernel=auto" --location=mbr
autopart --type=lvm

# Partition clearing information
clearpart --none --initlabel

# # Clear the Master Boot Record
# zerombr
# # Partition clearing information
# clearpart --all --initlabel --drives=sda
# # Disk partitioning information
# part /boot --asprimary --fstype="xfs" --size=5000
# part swap --asprimary --fstype="swap" --size=16384
# part / --asprimary --fstype="xfs" --grow


%packages
@^minimal
@core
chrony
kexec-tools

%end


######in packages #######
# @base
# @development
# @java-platform

%post
# add user and add to sudo list
# useradd -m -G wheel -s /bin/bash choon
# echo 'choon:choon123' | chpasswd
# mkdir /home/hadoop/.ssh/
# wget -q http://10.0.2.254/tftproot/ks/id_rsa.pub -O /home/choon/.ssh/authorized_keys
# wget -q http://10.0.2.254/tftproot/ks/id_rsa.pub -O /home/choon/.ssh/id_rsa.pub
# wget -q http:///10.0.2.254/tftproot/ks/id_rsa -O /home/choon/.ssh/id_rsa
# chmod 600 /home/choon/.ssh/id_rsa
# chown -R choon.choon /home/choon/.ssh/


# import GPG key for ssh
# mkdir /root/.ssh/
# wget -q http://10.0.2.254/tftproot/ks/id_rsa.pub -O /root/.ssh/authorized_keys
# wget -q http://10.0.2.254/tftproot/ks/id_rsa.pub -O /root/.ssh/id_rsa.pub
# wget -q http://10.0.2.254/tftproot/ks/id_rsa -O /root/.ssh/id_rsa
# chmod 600 /root/.ssh/id_rsa
######in packages #######


%addon com_redhat_kdump --enable --reserve-mb='auto'

%end

%anaconda
# 限制密碼
pwpolicy root --minlen=6 --minquality=50 --notstrict --nochanges --notempty
pwpolicy user --minlen=6 --minquality=50 --notstrict --nochanges --notempty
pwpolicy luks --minlen=6 --minquality=50 --notstrict --nochanges --notempty
%end
========

vim /etc/httpd/conf.d/pxeboot.conf
=====加在後面=====
Alias /ks /install/kickstart

<Directory /install/kickstart>
        Options Indexes FollowSymLinks
        Require all granted
        Allow from 127.0.0.1 10.0.2.0/24 
</Directory>
=================

systemctl restart httpd

vim /install/tftpboot/pxelinux.cfg/default
====加在後面====
LABEL kickstart1
  MENU LABEL Boot from PXE Server for AUTO Install CentOS 7
  kernel ./kernel/centos7/images/pxeboot/vmlinuz
  append initrd=./kernel/centos7/images/pxeboot/initrd.img  ks=http://10.0.2.254/ks/firstKickStart.ks 
===============

ref:
http://linux.vbird.org/linux_enterprise/0120installation.php#pxe_installation

2017年7月29日 星期六

虛擬系統(VirtualBox) 安裝 Guest Additions (CentOS7為例)


# REDHAT家族系統 VirtualBox 最低記憶體768MB 空間至少8GB full install至少15GB

# 先安裝epel package
sudo yum -y install epel-release

#EPEL的全称叫 Extra Packages for Enterprise linux 。EPEL是由 Fedora 社区打造,为 RHEL 及衍生发行版如 CentOS、Scientific Linux 等提供高质量软件包的项目。装上了 EPEL之后,就相当于添加了一个第三方源。

yum install dkms
yum groupinstall "Development Tools"
yum install kernel-devel

KERN_DIR=/usr/src/kernels/選最適合的kernel

之後用virtualbox載入Guest Additions CD image
如果有圖形介面,則autorun

沒圖形介面的話,則cd到mount CD的位置
然後執行 ./VBoxLinuxAdditions.run



ref :https://wiki.centos.org/HowTos/Virtualization/VirtualBox/CentOSguest
https://www.if-not-true-then-false.com/2010/install-virtualbox-guest-additions-on-fedora-centos-red-hat-rhel/

Centos7 XRDP 服務

使用rdp服務遠端控制centos7 GUI

# 安裝網絡工具 etc:ifconfig
yum install net-tools wget
# 獲得IP
ifconfig

# 安裝gui
yum -y groups install "GNOME Desktop"

# 先安裝epel package
yum install epel-release -y

# 安裝xrdp和tigervnc
yum -y install xrdp tigervnc-server
# 啟動xrdp
systemctl restart xrdp.service
# 查看xrdp狀態
netstat -antup | grep xrdp
# 預設啟動
systemctl enable xrdp.service

# 給firewall vnc的權限
firewall-cmd --permanent --zone=public --add-port=3389/tcp
firewall-cmd --reload

# chcon --type=bin_t /usr/sbin/xrdp
# chcon --type=bin_t /usr/sbin/xrdp-sesman

ref:
http://blog.jangmt.com/2015/09/centos-linux-7-xrdp-linux-rdp.html
http://www.itzgeek.com/how-tos/linux/centos-how-tos/install-xrdp-on-centos-7-rhel-7.html

2017年7月27日 星期四

筆記-PXE環境,網絡安裝OS(以centos7為例)


# 登入ROOT
su -

# 關閉開機後預設打開selinux
vim /etc/sysconfig/selinux
====
SELINUX=disabled
====
# 目前關閉selinux(開機後恢復)
setenforce 0

# 安裝網絡工具 etc:ifconfig
yum install net-tools wget

# 安裝dhcp服務
# 主要用來分配IP,合指向pxe的server地址
yum install dhcp
mv /etc/dhcp/dhcpd.conf /etc/dhcpd.conf.bak
vim /etc/dhcp/dhcpd.conf
===
ddns-update-style interim;
ignore client-updates;

subnet 10.0.2.0 netmask 255.255.255.0 {

#        option routers                  192.168.1.1;
#       option subnet-mask              255.255.255.0;

        option domain-name-servers      10.0.2.254;

        range dynamic-bootp 10.0.2.11 10.0.2.100;
        default-lease-time 21600;
        max-lease-time 43200;

}
filename "pxelinux.0";
next-server 10.0.2.254;               #NFS服务器地址

===
#解釋一下其中几行,“subnet”和“netmask”根据你自己的网络环境来配置;“option routers”和“option domain-name-servers”这两个是路由器和DNS地址,可以不用配置,我配置了是因为我所在单位的其它计算机有可能会从这里获得IP,而不是从路由器获得,为了不影响他们正常上网才配置的;“range dynamic-bootp”这个是IP地址分配池,不要跟路由器的分配池重叠了

systemctl start dhcpd #必須在設定檔規定的網域才能打開,然後本機自己設固定ip
systemctl enable dhcpd

yum install tftp-server xinetd

#TFTP 其實是由 xinetd 這個 super daemon 所管理的,因此設定好 TFTP 之後, 你要啟動的是 xinetd 才對喔!
vim /etc/xinetd.d/tftp
# 鳥哥是將所有的資料統一放置於 /install/ 目錄下的!那這個 TFTP 的根目錄我們就將他放置於 /install/tftpboot 底下囉!
# =============
#  server_args             = -s /install/tftpboot  <== 重點在這裡!
# disable                     = no <==必須改
# =============

mkdir -p /install/tftpboot

# 給予ftp使用者權限(必要)
chcon --reference /var/lib/tftpboot /install/tftpboot
#[root@centos ~]# chcon --reference /var /install
#[root@centos ~]# ll -dZ /install/tftpboot

systemctl start xinetd
systemctl enable xinetd
systemctl enable tftp

# 給予tftp權限,這也是必要的
firewall-cmd --permanent --add-service=tftp
# 重開防火牆
firewall-cmd --reload

yum install syslinux  <==底下的檔案是由這軟體所提供!
cp /usr/share/syslinux/menu.c32  /usr/share/syslinux/vesamenu.c32 /usr/share/syslinux/pxelinux.0 /install/tftpboot/
mkdir /install/tftpboot/pxelinux.cfg
ll /install/tftpboot/
====
-rw-r--r--. 1 root root  60928 2013-04-02 18:10 menu.c32      <==提供類選單模式的功能
-rw-r--r--. 1 root root  26828 2013-04-02 18:10 pxelinux.0    <==就是開機管理程式!
drwxr-xr-x. 2 root root   4096 2013-04-02 18:11 pxelinux.cfg  <==開機的選單設定在這裡!
-rw-r--r--. 1 root root 162860 2013-04-02 18:41 vesamenu.c32  <==圖形化介面選單
====

mkdir /install/iso
cd /install/iso
wget http://ftp.ksu.edu.tw/pub/CentOS/7/isos/x86_64/CentOS-7-x86_64-Minimal-1611.iso

# 將iso暫時掛載在 /mnt 底下來抓資料用:(我們需要安裝 Linux 系統,所以得要從原版光碟裡面將核心檔案撈出來~)
mount -o loop /install/iso/CentOS-7-x86_64-Minimal-1611.iso /mnt
mkdir -p /install/tftpboot/kernel/centos7
cp -fr /mnt/* /install/tftpboot/kernel/centos7
#cp /mnt/isolinux/vmlinuz /install/tftpboot/kernel/centos7/
#cp /mnt/isolinux/initrd.img /install/tftpboot/kernel/centos7/
cp /mnt/isolinux/isolinux.cfg /install/tftpboot/pxelinux.cfg/demo
umount /mnt

#centos7 不能直接使用kernel安裝,因此需要一個service放iso檔
yum install httpd
systemctl start httpd
systemctl enable httpd

vim /etc/httpd/conf.d/pxeboot.conf
===
Alias /centos7 /install/tftpboot/kernel/centos7

<Directory /install/tftpboot/kernel/centos7>
        Options Indexes FollowSymLinks
        Require all granted
        Allow from 127.0.0.1 10.0.2.0/24
</Directory>

===

systemctl restart httpd

# 給予http權限,這也是必要的
firewall-cmd --permanent --add-service=http
# 重開防火牆
firewall-cmd --reload


vim /install/tftpboot/pxelinux.cfg/default
===
UI vesamenu.c32        <== 使用 vesamenu.c32 這個類圖形的介面程式
TIMEOUT 300            <== 單位 0.1 秒,所以這個設定可等待 30 秒來進入預設開機
DISPLAY ./boot.msg     <== 提供一些額外的資訊,讓使用者更瞭解選單意義!
MENU TITLE Welcome to CHOON's PXE Server System
                       <== 上面這行只是提供一個大標題而已!
LABEL local            <== 第一個選單的項目
  MENU LABEL Boot from local drive
  MENU DEFAULT         <== 此選單為預設項目 (等待逾時就進入此開機)
  localboot 0          <== 本機磁碟開機的特定項目!

LABEL network1
  MENU LABEL Boot from PXE Server for Install CentOS 7
  kernel ./kernel/centos7/images/pxeboot/vmlinuz            <== 核心所在的檔名
  append initrd=./kernel/centos7/images/pxeboot/initrd.img  method=http://10.0.2.254/centos7 devfs=nomount <== 就是核心外帶參數啊!和iso裡檔案鏈接
# 上述設定中,大寫的文件部分要特別注意!那是使用 vesamenu.c32 的關鍵字!
# 至於後面的部分,那就是每個設定項目的內容囉!
===

vim /install/tftpboot/boot.msg
===
Welcome to CHOON's PXE Server System.

The 1st menu can let you system goto hard disk menu.
The 2nd menu can goto interactive installation step.
===

# 假如需要ftp的服務可以使用以下方式開通,帳號密碼是linux user
ftp: 使用自己的帳號登入
yum install vsftpd
systemctl enable vsftpd
systemctl start vsftpd

firewall-cmd --permanent --add-service=ftp
firewall-cmd --reload

#參考來源
#http://linux.vbird.org/linux_enterprise/0120installation.php#pxe_dhcp
#http://tototo.blog.51cto.com/4567634/878509

2017年7月17日 星期一

筆記- Anaconda 安裝及使用

安裝Anaconda
前往官網 https://www.continuum.io/downloads 下載sh

bash Anaconda3-4.4.0-MacOSX-x86_64.sh #安裝設定

#新建環境
conda create --name crawlerPPT
#新增複製環境
conda create --name crawlerFB --clone crawlerPPT
#刪除環境
conda remove --name crawlerFB --all

#進入環境
source activate crawlerPPT
#退出環境
source deactivate crawlerPPT

#查看目前的環境
conda info --envs

#查看目前的環境
conda info --envs

#查看目前环境已安装的套件
conda list

#查看指定环境的套件
conda list -n python34

# 查找package信息
conda search numpy

# 安装套件
conda install numpy #在目前環境
conda install -n crawlerPPT numpy #cralerPPT環境

Centos7 安裝Apache+php7+mariadb+phpmyadmin

#更新yum
sudo yum update

# 把selinux 安全度降低
sudo vi /etc/sysconfig/selinux
找到 SELINUX=enforcing 然後修改為 SELINUX=disabled 
要重新開機 reboot / restart 後才會套用

# 重開機先暫時用這個指令更換
sudo setenforce 0

#安裝apache
sudo yum install httpd
#打開apache
sudo service httpd start
#安裝mariadb的respo
sudo vim /etc/yum.repos.d/MariaDB.repo
====vim裡========
[mariadb]
name = MariaDB
gpgcheck=1
============
#安裝mariadb
sudo yum install MariaDB-server MariaDB-client
#打開並預設開機打開mariadb
sudo systemctl start mariadb
sudo systemctl enable mariadb
#設定mariadb
sudo mysql_secure_installation
# 
#安裝php和phpmyadmin
sudo yum install php70w
sudo yum install phpmyadmin

#修改phpmyadmin使得可以遠端登入
cd /etc/httpd/conf.d/
sudo cp phpMyAdmin.conf phpMyAdmin.conf.bak
sudo vim phpMyAdmin.conf 
=====vim======
<Directory /usr/share/phpMyAdmin/>
   AddDefaultCharset UTF-8

   <IfModule mod_authz_core.c>
     # Apache 2.4
     <RequireAny>
      # Require ip 127.0.0.1  #註解掉
      # Require ip ::1   #注释掉
      Require all granted   #新增這行
     </RequireAny>
 </IfModule>
 <IfModule !mod_authz_core.c>
     # Apache 2.2
     Order Deny,Allow
     Deny from All
     Allow from 127.0.0.1
     Allow from ::1
   </IfModule>
</Directory>

<Directory /usr/share/phpMyAdmin/setup/>
   <IfModule mod_authz_core.c>
     # Apache 2.4
     <RequireAny>
      #Require ip 127.0.0.1  #注释掉
      #Require ip ::1   #注释掉
      Require all granted   #新增這行
     </RequireAny>
   </IfModule>
   <IfModule !mod_authz_core.c>
     # Apache 2.2
     Order Deny,Allow
     Deny from All
     Allow from 127.0.0.1
     Allow from ::1
   </IfModule>
</Directory>
==============


sudo sudo firewall-cmd --permanent --add-port=80/tcp
sudo firewall-cmd --reload

sudo service httpd restart

2017年5月22日 星期一

筆記 - Pymongo指令

用Python操作Mongo時,常忘記一些指令,所以做下筆記,會持續更新。
# vals是1100時
coll.find({"vals":1100})
# or條件
coll.find({"$or":[ {"vals":1700}, {"vals":100}]})
# and條件
coll.find({"$and":[ {"vals":100}, {"vals":1100}]})
# artContent contains keyword
coll.find({"$and":[{"date.year":yearshow},{"date.month":monthShow},{"artContent": re.compile(keyword)}]})

2017年5月19日 星期五

Linux - 編碼相關問題(中文亂碼和出錯)

基於自己學習與工作派發的任務,常需要在多台Unix Base的機器上操作。為了方便在一台機器中控制其他機器,因此常需要用到ssh。
這幾年最常讓我遇到的問題就是編碼,編寫的程式常因為換了不同機器就無法運行。
每當這個時候就需要上網查了一大堆資料,然後匆匆的解決,一兩個月後又碰到類似的問題,然後持續進入loop。
今天,又再次遇到相同的問題。我遇到的錯誤碼是
UnicodeEncodeError: 'ascii' codec can't encode character '\u4f60' in position 0: ordinal not in range(128)。
因為在python3執行,所以會懷疑問題出在python,但python3預設是utf8,怎麼會是ascii呢?怎麼每次換機器都會遇到類似的問題?這讓我納悶了很長一段時間。
上網查了一兩小時,還是找不到適合的解決方法。之後無意間發現在本機跑是沒問題的。所以應該是遙控端的terminal編碼和被遙控端的系統編碼問題。
最後終於讓我找到問題的根源了,是被遙控端的機器編碼問題。

在terminal輸入locale,os會回應所有locale settings。
$ locale
LANG=en_US.UTF-8
LANGUAGE=
LC_CTYPE=
LC_NUMERIC="zh_TW.UTF-8"
LC_TIME="zh_TW.UTF-8"
LC_COLLATE="zh_TW.UTF-8"
LC_MONETARY="zh_TW.UTF-8"
LC_MESSAGES="zh_TW.UTF-8"
LC_PAPER="zh_TW.UTF-8"
LC_NAME="zh_TW.UTF-8"
LC_ADDRESS="zh_TW.UTF-8"
LC_TELEPHONE="zh_TW.UTF-8"
LC_MEASUREMENT="zh_TW.UTF-8"
LC_IDENTIFICATION="zh_TW.UTF-8"
LC_ALL=
LC_CTYPE 這會影響字元的分類和轉換,若要能輸入中文,就是設定這裡
LC_TIME 這就是日期和時間的顯示格式囉
LC_MONETARY 這會影響貨幣單位的符號和表示
LC_MESSAGES 這會影響系統訊息的顯示,若想要顯示中文,就是設定這裡
LANG 這是預設,如果上面有沒設定的,就會用這裡的設定
LC_ALL 這是強制全部使用這裡的設定,如果這裡設定了,那麼上面的都沒用,全部以這裡的為準

把LC_CTYPE設成zh_TW.UTF-8就解決了。
export LC_CTYPE="zh_TW.UTF-8"
假如覺得全部語系應該改成UTF8,那就直接設LC_ALL。
export LC_ALL="zh_TW.UTF-8"
使用export的好處是當把terminal關掉時,設定就會恢復,這樣也不用擔心更改到別人電腦的設定。
假如電腦是自己的,那可以根據以下說明設定,然後重開terminal。

debian家族:
修改/etc/default/locale
$ sudo vim /etc/default/locale 
LC_CTYPE=zh_TW.UTF-8
(其他...)
redhat家族:
$ localectl set-locale 變數=語系
localectl set-locale LC_CTYPE=zh_TW.UTF-8

2017年5月17日 星期三

Raspberry Pi - 智慧插座

現在市面上的智慧家居玲琅满目,上週的課程剛好有學到繼電器,所以就順帶做個智慧插座。這次DIY的智慧插座功能很簡單,純粹只用網頁開關插座,沒有其他功能。(RaspberryPi使用Python編寫,其實蠻容易擴充功能的。)

1. 首先,準備好RaspberryPi,麵包板、繼電器、延長線

2. 把延長線的火線剪開,來源段接在繼電器的COM上,終點端接在NO上
(圖裡右側3條細線,請忽略)


3. 繼電器的VCC接上3.3v,GND接上ground,In2接上GPIO(由於In1沒用到,所以不接)

4. 打開editor複製以下的code然後命名為intelligent_socket.py
(到此步驟,只要在terminal輸入python3 intelligent_socket.py 1 插座就接上電了;相反參數給0則斷電)
import RPi.GPIO as GPIO
import time
import sys
import argparse

parser = argparse.ArgumentParser()
parser.add_argument("boolean",help="1=on 2=off", type=int)
args = parser.parse_args()

GPIO.setmode(GPIO.BCM)
GPIO5 = 5 # In2 接在GPIO5上
GPIO.setup(GPIO5, GPIO.OUT)

signal = args.boolean
if signal == 1:
 GPIO.output(GPIO5, True)
elif signal == 0:
 GPIO.output(GPIO5, False)
else:
 pass 

print("end")
5. 打開editor複製以下的code然後命名為socket.php,並儲存在apache的網絡路徑。
<?php
 if(isset($_GET["a"])){
  $signal = $_GET["a"];
 
  switch($signal){
   case 'open':
    $output = shell_exec('python3 /home/pi/Desktop/intelligent_socket.py 1 2>&1');
    break;
   case 'close':
    $output = shell_exec('python3 /home/pi/Desktop/intelligent_socket.py 0 2>&1');
    break;
  }
  echo $output;
  die("done");
 }

?>

<!DOCTYPE html>
<html>
<head>
 <title>遠端插座開關</title>
 <script src="https://code.jquery.com/jquery-3.2.1.js"></script>
 <script type="text/javascript">
  $(document).ready(function(){
   $('#open').click(function(){
    $.ajax({
     url: 'socket.php?a=open',
     success: function(result){
      console.log(result);
     },
     statusCode: {
      404: function() {
       alert('網頁出錯,請重新操作或聯絡管理員');
      }
     }
    });   
   })
   $('#close').click(function(){
    $.ajax({
     url: 'socket.php?a=close',
     success: function(result){
      console.log(result);
     },
     statusCode: {
      404: function() {
       alert('網頁出錯,請重新操作或聯絡管理員');
      }
     }
    });   
   })
  })
 </script>
</head>
<body>
 <button id="open">OPEN</button>
 <button id="close">CLOSE</button>
</body>
</html>

6. 由於GPIO接觸到硬體,apache沒權限直接呼叫gpio function,所以只好把apache加進gpio的group裡。打開terminal,複製以下兩行到terminal(這步驟很重要,不然會失敗)

sudo usermod -a -G gpio www-data
sudo service apache2 restart

7. 用browser打開127.0.0.1/socket.php,點擊open則打開插座,點擊close則關閉插座。

8. 成功!


2017年5月16日 星期二

Raspberry Pi - 安裝LAMP

近期在玩 RaspberryPi,需要Lamp功能,邊裝邊紀錄過程,方便下次直接複製XD

RaspberryPi + Apache + PHP + MariaDB + Phpmyadmin

# 更新套件
sudo apt-get update & sudo apt-get upgrade
# 安裝Apache、php、mariadb
sudo apt-get install apache2 php5 libapache2-mod-php5 mariadb-server php5-mysql phpmyadmin -y
## 安裝完mariadb,會要求輸入root的密碼
# restart apache
sudo service apache2 restart
# 修改apache存儲路徑的owner為pi
sudo chown -R pi /var/www/html/
sudo echo "<?php phpinfo(); ?>" > /var/www/html/phpinfo.php
## 打開127.0.0.1/phpinfo.php, 有畫面代表成功
# 建phpmyadmin symbolic link 到apache存儲路徑
sudo ln -s /usr/share/phpmyadmin/ /var/www/html/phpmyadmin
## 打開127.0.0.1/phpmyadmin, 有畫面並且能登陸代表成功

Updated 2021.08.13
#php7
sudo apt install apache2 php libapache2-mod-php php-gd php-mysql
sudo apt install mariadb-server
sudo mysql_secure_installation
sudo systemctl enable apache2

#install adminer
sudo apt-get install adminer
ln -s /usr/share/adminer/adminer/ /var/www/html/adminer
(root must use sudo login. if want test adminer login function, we should create a new account to test )

#check installed
apt list --installed | grep apache
apt list --installed | grep php

Centos GUI Webserver 設定

新灌的一台Centos7可以做以下的設定 語系設定: - sudo localectl set-locale LC_CTYPE=zh_TW.UTF-8 修改ssh port - http://linux.vbird.org/linux_server/0310telne...