22. Jupyter Notebook構築 [さくらのVPS/CentOS7]

・Jupyter Notebook のインストール

#-- jupyter notebook のログインするパスワードを設定
PASSWORD=********
JPUSER=jupyter
JPHOME="/home/${JPUSER}"
JPPORT=8081

yum install -y openssl-devel readline-devel sqlite-devel

adduser ${JPUSER}
git clone https://github.com/yyuu/pyenv ${JPHOME}/.pyenv
echo 'export PYENV_ROOT="${HOME}/.pyenv"' >> ${JPHOME}/.bash_profile
echo 'export PATH="${PYENV_ROOT}/bin:${PATH}"' >> ${JPHOME}/.bash_profile
echo 'eval "$(pyenv init -)"' >> ${JPHOME}/.bash_profile
chown -R ${JPUSER}. ${JPHOME}/.pyenv

#-- python3
su -l ${JPUSER} -c "yes | pyenv install anaconda3-5.3.1"
su -l ${JPUSER} -c "pyenv global anaconda3-5.3.1"
su -l ${JPUSER} -c "pyenv rehash"
su -l ${JPUSER} -c "yes | conda create --name py3.7 python=3.7 anaconda"

cat <<_EOF_> /tmp/ana3.sh
source /home/${JPUSER}/.pyenv/versions/anaconda3-5.3.1/bin/activate py3.7
conda install jupyter ipykernel
jupyter kernelspec install-self --user
pip install chainer
_EOF_

su -l ${JPUSER} -c "/bin/bash /tmp/ana3.sh"

#-- python2
su -l ${JPUSER} -c "yes | pyenv install anaconda2-5.3.1"
su -l ${JPUSER} -c "pyenv global anaconda2-5.3.1"
su -l ${JPUSER} -c "pyenv rehash"
su -l ${JPUSER} -c "yes | conda create --name py2.7 python=2.7 anaconda"

cat <<_EOF_> /tmp/ana2.sh
source /home/${JPUSER}/.pyenv/versions/anaconda2-5.3.1/bin/activate py2.7
conda install jupyter ipykernel
jupyter kernelspec install-self --user
pip install chainer
_EOF_
su -l ${JPUSER} -c "/bin/bash /tmp/ana2.sh"

#-- 設定作成
su -l ${JPUSER} -c "jupyter notebook --generate-config"
hashedp=$(su -l ${JPUSER} -c "python -c 'from notebook.auth import passwd; print(passwd(\"${PASSWORD}\",\"sha256\"))'")

cat <<_EOF_>>  ${JPHOME}/.jupyter/jupyter_notebook_config.py
c.NotebookApp.password = '${hashedp}'
c.NotebookApp.port = ${JPPORT}
c.NotebookApp.open_browser = False
c.NotebookApp.ip = '127.0.0.1'
c.NotebookApp.notebook_dir = '${JPHOME}'
c.NotebookApp.base_url = 'https://masdon.life/notebook/'
c.NotebookApp.base_url = 'notebook/'
_EOF_

#-- 起動スクリプト作成
cat <<_EOF_> /etc/systemd/system/jupyter.service
[Unit]
Description = jupyter daemon

[Service]
ExecStart = /home/${JPUSER}/.pyenv/shims/jupyter notebook
Restart = always
Type = simple
User = ${JPUSER}

[Install]
WantedBy = multi-user.target
_EOF_

#-- 起動
systemctl enable jupyter
systemctl start jupyter

#-- nginx の設定作成
cat <<'_EOF_' > /etc/nginx/conf.d/https.d/notebook.conf
  location ^~ /notebook {
    location /notebook/ {
      proxy_pass       http://localhost:8081;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header Host $http_host;
      proxy_http_version 1.1;
      proxy_redirect off;
      proxy_buffering off;
      proxy_set_header Upgrade $http_upgrade;
      proxy_set_header Connection "upgrade";
      proxy_read_timeout 86400;
    }
  }
_EOF_

systemctl reload nginx

URLは https://masdon.life/notebook/

21. pukiwiki構築 [さくらのVPS/CentOS7]

・pukiwiki のインストール

#-- 変数に必要な値を代入
HTTPS_DOCROOT=/var/www/html/https_root

#-- pukiwiki のインストール
cd ~/work/src/
curl -L -o pukiwiki-1.5.1_utf8.zip 'https://ja.osdn.net/frs/redir.php?m=iij&f=pukiwiki%2F64807%2Fpukiwiki-1.5.1_utf8.zip'

unzip pukiwiki-1.5.1_utf8.zip
mv pukiwiki-1.5.1_utf8 ${HTTPS_DOCROOT}/pukiwiki-1.5.1_utf8
ln -s pukiwiki-1.5.1_utf8 ${HTTPS_DOCROOT}/pukiwiki
chown nginx. ${HTTPS_DOCROOT}/pukiwiki-1.5.1_utf8

#--管理者パスワードを作成して pukiwiki.ini.php の $adminpass に設定する
printf "********" | md5sum
vi ${HTTPS_DOCROOT}/pukiwiki-1.5.1_utf8/pukiwiki.ini.php

$adminpass = '{x-php-md5}*********************************';

#-- nginx の設定でメールアドレスでのbasic認証を設定
cat <<'_EOF_'> /etc/nginx/conf.d/https.d/pukiwiki.conf
  location ^~ /pukiwiki {
    location ~ /pukiwiki/.*\.php$ {
      auth_ldap "Basic Auth Location";
      auth_ldap_servers ldap1;
      fastcgi_pass 127.0.0.1:9000;
      fastcgi_index index.php;
      fastcgi_param SCRIPT_FILENAME $document_root/$fastcgi_script_name;
      include fastcgi_params;
    }

    location ~ /pukiwiki/ {
      auth_ldap "Basic Auth Location";
      auth_ldap_servers ldap1;
    }
  }
_EOF_

systemctl restart nginx

20. CMS構築 – WordPress/baserCMS [さくらのVPS/CentOS7]

・WordPress のインストール

#-- 変数に必要な値を代入
HTTPS_DOCROOT=/var/www/html/https_root

#-- wordpress のインストール
cd ~/work/src/
curl -L -o wordpress.tar.gz http://wordpress.org/latest.tar.gz
tar xvzf wordpress.tar.gz
mv wordpress ${HTTPS_DOCROOT}/wordpress
chown -R nginx. ${HTTPS_DOCROOT}/wordpress

#-- wordpress database の作成
mysql -e "create database wordpress character set utf8 collate utf8_bin;"
#-- database の password は お好みで
mysql -e "GRANT ALL PRIVILEGES ON wordpress.* TO 'wpuser'@'localhost' IDENTIFIED BY 'wppassword' ;"
mysql -e "FLUSH PRIVILEGES;"

#-- wordpress の設定
cp -p ${HTTPS_DOCROOT}/wordpress/wp-config-sample.php ${HTTPS_DOCROOT}/wordpress/wp-config.php

sed -i -e 's/database_name_here/wordpress/' \
       -e 's/username_here/wpuser/' \
       -e 's/password_here/wppassword/' ${HTTPS_DOCROOT}/wordpress/wp-config.php

cat <<'_EOL_' > /etc/nginx/conf.d/https.d/wordpress.conf
  location ^~ /wordpress {
    location /wordpress/wp-content/uploads {
      location ~ \.php$ {
          deny all;
      }
    }

    location /wordpress/ {
      try_files $uri $uri/ /index.php?$args;
    }

    location ~ \.php$ {
      fastcgi_pass 127.0.0.1:9000;
      fastcgi_index index.php;
      fastcgi_param SCRIPT_FILENAME $document_root/$fastcgi_script_name;
      include fastcgi_params;
    }

    location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
      expires max;
      log_not_found off;
    }
  }
_EOL_

systemctl restart nginx

Web画面からインストールを続ける。管理者アカウントの設定もある為、直ぐに実施すること
https://masdon.life/wordpress/

・baserCMSのインストール

#-- 変数に必要な値を代入
HTTPS_DOCROOT=/var/www/html/https_root

#-- baserCMS の database を作成
mysql -e "create database basercms character set utf8 collate utf8_bin;"
#-- database の password は お好みで
mysql -e "GRANT ALL PRIVILEGES ON basercms.* TO 'basercms'@'localhost' IDENTIFIED BY 'baserpass' ;"
mysql -e "FLUSH PRIVILEGES;"

#-- baserCMS のインストール
cd ~/work/git
git clone https://github.com/baserproject/basercms.git
cp -pr basercms ${HTTPS_DOCROOT}/blog
#-- ******** は admin アカウントのパスワード
${HTTPS_DOCROOT}/blog/app/Console/cake bc_manager install \
  "https://masdon.life/blog" \
  mysql \
  admin \
  ******** \
  admin@masdon.life \
  --host localhost \
  --database "basercms" \
  --port 3306 \
  --login "basercms" \
  --password "baserpass" \
  --data 'bc_sample.default'

chown -R nginx. /var/www/html/https_root/blog

#-- nginx の設定追加
cat <<'_EOL_'> /etc/nginx/conf.d/https.d/blog.conf
    location /blog/theme/ {
        alias /var/www/html/https_root/blog/app/webroot/theme/;
    }

    location =/blog/ {
        rewrite ^ /blog/index.php;
    }
    location /blog {
        if ( !-e $request_filename ) {
            rewrite ^ /blog/index.php last;
        }
    }
_EOL_

systemctl reload nginx

管理ページ: https://masdon.life/blog/admin

19. VPNサーバの構築 – strongswan/xl2tpd/freeradius [さくらのVPS/CentOS7]

・VPNサーバの用途

  1. 外部からVPNサーバを経由して自宅環境にログインする
  2. radiko で大阪のラジオ放送を聴く

・strongswan, xl2tp, freeradius のインストール

#-- 変数に必要な値を代入
IPV4=$(ip addr show eth0 | awk '/inet /{print $2}' | sed 's#/.*##')

#-- strongswan, xl2tpd, freeradius をインストール
yum install -y xl2tpd strongswan freeradius freeradius-utils freeradius-ldap radiusclient-ng

#-- VPNで使用するIPアドレスを eth0 に 追加
cat <<_EOL_>> /etc/sysconfig/network-scripts/ifcfg-eth0
IPADDR1=192.168.0.1
PREFIX1=24
_EOL_

systemctl restart network

#-- strongwan の設定
cat <<_EOL_>> /etc/strongswan/ipsec.conf
conn %default
    auto=add
    keyexchange=ikev1
    ikelifetime=60m
    keylife=20m
    rekeymargin=3m
    authby=secret
    rekey=no
    keyingtries=3
    type=transport
    keyexchange=ikev1
    left=%defaultroute
    leftprotoport=udp/1701
    right=%any
    rightprotoport=udp/%any

conn L2TP
    left=${IPV4}
    # for Android 6
    ike=aes256-sha1-modp1024,3des-sha1-modp1024!
    esp=aes256-sha1,3des-sha1!
_EOL_

#-- 共通シークレットはお好みで
cat <<_EOL_>> /etc/strongswan/ipsec.secrets
: PSK "PreSharedKey"
_EOL_

cat <<_EOL_> /etc/strongswan/strongswan.conf
# strongswan.conf - strongSwan configuration file
#
# Refer to the strongswan.conf(5) manpage for details
#
# Configuration changes should be made in the included files

charon {
    load_modular = yes
    plugins {
        include strongswan.d/charon/*.conf
    }
    dns1=127.0.0.1
    dns2=8.8.8.8
}

include strongswan.d/*.conf
_EOL_

#-- strongswan の起動
systemctl enable strongswan
systemctl start strongswan

#-- radius の設定 (LDAP認証)
sed -i -e "s/base_dn = 'dc=example,dc=org'/base_dn = ''/" \
 -e 's/filter = "(uid=.*/filter = "(mailRoutingAddress=%{%{Stripped-User-Name}:-%{User-Name}})"/' /etc/raddb/mods-available/ldap

ln -s ../mods-available/ldap /etc/raddb/mods-enabled/ldap

sed -i -e 's/-ldap/-ldap\n\tif ((ok || updated) \&\& User-Password) { update control { Auth-Type := ldap } }/' \
  -e 's/.*Auth-Type LDAP {/\tAuth-Type LDAP {\n\t\tldap\n\t}\n#\tAuth-Type LDAP {/' /etc/raddb/sites-available/default

cat <<_EOL_ >> /etc/raddb/dictionary
VALUE Auth-Type LDAP 5
_EOL_

#-- radiusd の起動
systemctl enable radiusd
systemctl start radiusd

#-- radiusclient の設定
ln -s radiusclient-ng /etc/radiusclient

sed -i -e 's/auth_order\tradius,local/auth_order\tradius/' -e 's/bindaddr.*/#bindaddr */' /etc/radiusclient-ng/radiusclient.conf

#-- testing123 は使ってないので何でもいいはず
cat <<_EOL_>> /etc/radiusclient-ng/servers
localhost testing123
_EOL_

#-- xl2tpd の設定 (192.168.0.101 から 192.168.0.200 をクライアントに割り当てる)
cat <<_EOL_>/etc/xl2tpd/xl2tpd.conf
[global]
listen-addr = ${IPV4}

[lns default]
ip range = 192.168.0.101-192.168.0.200
local ip = 192.168.0.1
require authentication = yes
name = LinuxVPNserver
pppoptfile = /etc/ppp/options.xl2tpd
length bit = yes
_EOL_

cat <<_EOL_>/etc/ppp/options.xl2tpd
ipcp-accept-local
ipcp-accept-remote
ms-dns  127.0.0.1
ms-dns  8.8.8.8
noccp
auth
idle 1800
mtu 1410
mru 1410
nodefaultroute
proxyarp
connect-delay 5000
require-pap
refuse-chap
refuse-mschap
refuse-mschap-v2
logfile /var/log/xl2tpd.log
plugin radius.so
plugin radattr.so
_EOL_

#-- xl2tpd の起動
systemctl enable xl2tpd
systemctl start xl2tpd

#-- firewall の解放
firewall-cmd --permanent --add-port={4500,500,1701}/udp
firewall-cmd --permanent --add-masquerade
firewall-cmd --reload

#-- kernel パラメーター設定変更
cat <<_EOL_>> /etc/sysctl.conf
# for vpn
net.ipv4.ip_forward = 1
_EOL_

sysctl -p

・クライアントの設定

サーバアドレス: 該当サーバのIPv4アドレス
アカウント名: メールアドレス
パスワード: メールアドレスのパスワード
共有シークレット: PreSharedKey

macOS と Android と IOS での接続確認済み

18. オンラインストレージサーバ構築 – Nextcloud [さくらのVPS/CentOS7]

・Nextcloud のインストール

#-- 変数に必要な値を代入
HTTPS_DOCROOT=/var/www/html/https_root

#-- 必要な phpパッケージをインストール
yum install -y php73-php-{zip,mcrypt,smbclient,imap,gmp,apcu,redis,memcached}
systemctl restart php73-php-fpm

#-- nextcloud のインストール
cd ~/work/git
git clone https://github.com/nextcloud/server.git nextcloud
cd nextcloud
VERSION=$(git tag | egrep -iv "rc|beta" | sed 's/^v//' | sort -n | tail -1)
git checkout v${VERSION}
git submodule update --init
cp -pr ~/work/git/nextcloud ${HTTPS_DOCROOT}/nextcloud
chown -R nginx. ${HTTPS_DOCROOT}/nextcloud/

#-- nextcloud の database を作成
mysql -e "create database nextcloud character set utf8 collate utf8_bin;"
#-- database の password は お好みで
mysql -e "GRANT ALL PRIVILEGES ON nextcloud.* TO 'ncuser'@'localhost' IDENTIFIED BY 'ncpassword' ;"
mysql -e "FLUSH PRIVILEGES;"

#-- nextcloud 用 nginx の設定作成
cat <<'_EOL_' > /etc/nginx/conf.d/https.d/nextcloud.conf
  # for nextcloud
  add_header X-Content-Type-Options nosniff;
  add_header X-XSS-Protection "1; mode=block";
  add_header X-Robots-Tag none;
  add_header X-Download-Options noopen;
  add_header X-Permitted-Cross-Domain-Policies none;
  add_header Referrer-Policy no-referrer;
  fastcgi_hide_header X-Powered-By;

  location = /robots.txt {
    allow all;
    log_not_found off;
    access_log off;
  }

  location ^~ /nextcloud {

    # set max upload size
    client_max_body_size 512M;
    fastcgi_buffers 64 4K;

    # Enable gzip but do not remove ETag headers
    gzip on;
    gzip_vary on;
    gzip_comp_level 4;
    gzip_min_length 256;
    gzip_proxied expired no-cache no-store private no_last_modified no_etag auth;
    gzip_types application/atom+xml application/javascript application/json application/ld+json application/manifest+json application/rss+xml application/vnd.geo+json application/vnd.ms-fontobject application/x-font-ttf application/x-web-app-manifest+json application/xhtml+xml application/xml font/opentype image/bmp image/svg+xml image/x-icon text/cache-manifest text/css text/plain text/vcard text/vnd.rim.location.xloc text/vtt text/x-component text/x-cross-domain-policy;

    # Uncomment if your server is build with the ngx_pagespeed module
    # This module is currently not supported.
    #pagespeed off;

    location /nextcloud {
      rewrite ^ /nextcloud/index.php$request_uri;
    }

    location ~ ^/nextcloud/(?:build|tests|config|lib|3rdparty|templates|data)/ {
      deny all;
    }
    location ~ ^/nextcloud/(?:\.|autotest|occ|issue|indie|db_|console) {
      deny all;
    }

    location ~ ^/nextcloud/(?:index|remote|public|cron|core/ajax/update|status|ocs/v[12]|updater/.+|ocs-provider/.+)\.php(?:$|/) {
      fastcgi_split_path_info ^(.+?\.php)(/.*)$;
      include fastcgi_params;
      fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
      fastcgi_param PATH_INFO $fastcgi_path_info;
      fastcgi_param HTTPS on;
      #Avoid sending the security headers twice
      fastcgi_param modHeadersAvailable true;
      fastcgi_param front_controller_active true;
      fastcgi_pass 127.0.0.1:9000;
      fastcgi_intercept_errors on;
      fastcgi_request_buffering off;
    }

    location ~ ^/nextcloud/(?:updater|ocs-provider)(?:$|/) {
      try_files $uri/ =404;
      index index.php;
    }

    # Adding the cache control header for js and css files
    # Make sure it is BELOW the PHP block
    location ~ \.(?:css|js|woff2?|svg|gif)$ {
      try_files $uri /nextcloud/index.php$request_uri;
      add_header Cache-Control "public, max-age=15778463";
      # Add headers to serve security related headers  (It is intended
      # to have those duplicated to the ones above)
      # Before enabling Strict-Transport-Security headers please read
      # into this topic first.
      # add_header Strict-Transport-Security "max-age=15768000;
      # includeSubDomains; preload;";
      add_header X-Content-Type-Options nosniff;
      add_header X-XSS-Protection "1; mode=block";
      add_header X-Robots-Tag none;
      add_header X-Download-Options noopen;
      add_header X-Permitted-Cross-Domain-Policies none;
      add_header Referrer-Policy no-referrer;

      # Optional: Don't log access to assets
      access_log off;
    }

    location ~ \.(?:png|html|ttf|ico|jpg|jpeg)$ {
      try_files $uri /nextcloud/index.php$request_uri;
      # Optional: Don't log access to other assets
      access_log off;
    }
  }
_EOL_

systemctl restart nginx

管理者アカウントをWeb画面から作成できるので直ぐに作成すること
https://masdon.life/nextcloud/
mysql を使用する場合は、ストレージとデータベースをクリックして必要な項目を入力する

・ Redis を使用する設定を追加

vi /var/www/html/https_root/nextcloud/config
-- 追加する設定 ここから
  'memcache.local' => '\OC\Memcache\Redis',
  'memcache.locking' => '\OC\Memcache\Redis',
  'redis' => array(
     'host' => 'localhost',
     'port' => 6379,
      )
-- ここまで

17. チャットサーバ構築 – mattermost [さくらのVPS/CentOS7]

・mattermostのインストール

#-- 変数に必要な値を代入
DOMAIN=masdon.life
#-- admin@masdon.life のパスワード
PASSWORD=********
VERSION=5.6.2
HTTPS_DOCROOT=/var/www/html/https_root

#-- mattermost のダウンロードとインストール
cd ~/work/src
curl -O https://releases.mattermost.com/${VERSION}/mattermost-team-${VERSION}-linux-amd64.tar.gz
tar xpf mattermost-team-${VERSION}-linux-amd64.tar.gz
mv mattermost /opt/
mkdir -p /opt/mattermost/data
adduser mattermost
chown -R mattermost. /opt/mattermost
chmod -R g+w /opt/mattermost

#-- mattermost database を作成 (データ投入は初回起動時に自動で行われる)
mysql -e "create database mattermost character set utf8 collate utf8_bin;"
#-- database の password は お好みで
mysql -e "GRANT ALL PRIVILEGES ON mattermost.* TO 'mmuser'@'localhost' IDENTIFIED BY 'mostest' ;"
mysql -e "FLUSH PRIVILEGES;"

#-- mattermost の設定
cp -p /opt/mattermost/config/config.json{,.org}
sed -i -e 's/dockerhost/127.0.0.1/' \
-e 's/mattermost_test/mattermost/' \
-e "s#SiteURL.*#SiteURL\": \"https://${DOMAIN}/mattermost/\",#" \
-e 's/SendEmailNotifications.*/SendEmailNotifications": true,/' \
-e 's/FeedbackName.*/FeedbackName": "Mattermost",/' \
-e "s/FeedbackEmail.*/FeedbackEmail\": \"admin@${DOMAIN}\",/" \
-e 's/EnableSMTPAuth.*/EnableSMTPAuth": true,/' \
-e "s/SMTPUsername.*/SMTPUsername\": \"admin@${DOMAIN}\",/" \
-e "s/SMTPPassword.*/SMTPPassword\": \"${PASSWORD}\",/" \
-e "s/SMTPServer.*/SMTPServer\": \"${DOMAIN}\",/" \
-e 's/SMTPPort.*/SMTPPort": "465",/' \
-e 's/RequireEmailVerification.*/RequireEmailVerification": true,/' \
-e 's/"en"/"ja"/' /opt/mattermost/config/config.json

sed -i -e '186s/ConnectionSecurity.*/ConnectionSecurity": "TLS",/' /opt/mattermost/config/config.json

sed -i -e 's#"Directory": "./data/"#"Directory": "/opt/mattermost/data/"#' \
-e 's#"Directory": "./plugins"#"Directory": "/opt/mattermost/plugins"#' \
-e 's#"ClientDirectory": "./client/plugins"#"Directory": "/opt/mattermost/client/plugins"#' /opt/mattermost/config/config.json

#-- mattermost の起動ルール
cat <<_EOF_> /etc/systemd/system/mattermost.service
[Unit]
Description=Mattermost
After=mysqld.service postfix.service

[Service]
Type=simple
WorkingDirectory=/opt/mattermost/bin
User=mattermost
ExecStart=/opt/mattermost/bin/mattermost
PIDFile=/var/spool/mattermost/pid/master.pid
LimitNOFILE=49152

[Install]
WantedBy=multi-user.target
_EOF_

#-- mattermost 起動
systemctl enable mattermost
systemctl start mattermost

#-- mattermost 用の nginx の設定追加
cp -p /etc/nginx/conf.d/https.conf{,.org}
cat <<'_EOF_'>> /etc/nginx/conf.d/https.conf

upstream backend {
  server 127.0.0.1:8065;
  keepalive 32;
}

proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=mattermost_cache:10m max_size=200m inactive=120m use_temp_path=off;
_EOF_

cat <<'_EOF_'> /etc/nginx/conf.d/https.d/mattermost.conf
  location ^~ /mattermost {
    location ~ /mattermost/api/v[0-9]+/(users/)?websocket$ {
      proxy_set_header Upgrade $http_upgrade;
      proxy_set_header Connection "upgrade";
      client_max_body_size 50M;
      proxy_set_header Host $http_host;
      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header X-Forwarded-Proto $scheme;
      proxy_set_header X-Frame-Options SAMEORIGIN;
      proxy_buffers 256 16k;
      proxy_buffer_size 16k;
      client_body_timeout 60;
      send_timeout 300;
      lingering_timeout 5;
      proxy_connect_timeout 90;
      proxy_send_timeout 300;
      proxy_read_timeout 90s;
      proxy_pass http://backend;
    }

    location /mattermost/ {
      client_max_body_size 50M;
      proxy_set_header Connection "";
      proxy_set_header Host $http_host;
      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header X-Forwarded-Proto $scheme;
      proxy_set_header X-Frame-Options SAMEORIGIN;
      proxy_buffers 256 16k;
      proxy_buffer_size 16k;
      proxy_read_timeout 600s;
      proxy_cache mattermost_cache;
      proxy_cache_revalidate on;
      proxy_cache_min_uses 2;
      proxy_cache_use_stale timeout;
      proxy_cache_lock on;
      proxy_http_version 1.1;
      proxy_pass http://backend;
    }
  }
_EOF_

systemctl restart nginx

#-- mattermostの日本語全文検索対応
mysql mattermost -u mmuser -pmostest -e "ALTER TABLE \`Posts\` ENGINE = Mroonga;"

最初に作成するアカウントが管理者となる為、直ぐにアカウントを作成すること
https://masdon.life/mattermost/

16. RSSクライアント/サーバ構築 – Tiny Tiny RSS [さくらのVPS/CentOS7]

・Tiny Tiny RSS の用途

  1. 広告排除が可能なRSSクライアント
  2. スマフォアプリから参照可能なRSSサーバ (fever pluginの有効化が必要)

・Tiny Tiny RSS のインストール

#-- 変数に必要な値を代入
DOMAIN=masdon.life
HTTPS_DOCROOT=/var/www/html/https_root

#-- git clone は激遅
git clone https://tt-rss.org/git/tt-rss.git ~/work/git/tt-rss

#-- ttrss database の作成
mysql -e "create database ttrss character set utf8;"
#-- database の password は お好みで
mysql -e "grant all privileges on ttrss.* to ttrss@localhost identified by 'ttrsspass';"
mysql -e "flush privileges;"

cp -pr ~/work/git/tt-rss ${HTTPS_DOCROOT}/tt-rss
cp -p ${HTTPS_DOCROOT}/tt-rss/config.php{-dist,}

#-- diff の結果を参考に設定を編集する
vi ${HTTPS_DOCROOT}/tt-rss/config.php

diff ${HTTPS_DOCROOT}/tt-rss/config.php{-dist,}
6c6
< 	define('DB_TYPE', "pgsql"); // or mysql
---
> 	define('DB_TYPE', "mysql"); // or mysql
8,11c8,11
< 	define('DB_USER', "fox");
< 	define('DB_NAME', "fox");
< 	define('DB_PASS', "XXXXXX");
< 	define('DB_PORT', ''); // usually 5432 for PostgreSQL, 3306 for MySQL
---
> 	define('DB_USER', "ttrss");
> 	define('DB_NAME', "ttrss");
> 	define('DB_PASS', "ttrsspass");
> 	define('DB_PORT', '3306'); // usually 5432 for PostgreSQL, 3306 for MySQL
21c21
< 	define('SELF_URL_PATH', 'http://example.org/tt-rss/');
---
> 	define('SELF_URL_PATH', 'https://masdon.life/tt-rss/');
159c159,168
< 	define('PLUGINS', 'auth_internal, note');
---
> 	define('PLUGINS', 'auth_remote, auth_internal, note, updater, auth_ldap');
> 	define('LDAP_AUTH_SERVER_URI', 'ldap://localhost:389/');
> 	define('LDAP_AUTH_USETLS', FALSE);
> 	define('LDAP_AUTH_ALLOW_UNTRUSTED_CERT', TRUE);
> 	define('LDAP_AUTH_BINDDN', '');
> 	define('LDAP_AUTH_BINDPW', '');
> 	define('LDAP_AUTH_BASEDN', '');
> 	define('LDAP_AUTH_ANONYMOUSBEFOREBIND', FALSE);
> 	define('LDAP_AUTH_SEARCHFILTER', '(mailRoutingAddress=???)');
>

#-- auth_ldap plugin をインストール
git clone https://github.com/hydrian/TTRSS-Auth-LDAP ~/work/git/TTRSS-Auth-LDAP
cp -pr ~/work/git/TTRSS-Auth-LDAP/plugins/auth_ldap ${HTTPS_DOCROOT}/tt-rss/plugins

#-- fever-plugin をインストール
git clone https://github.com/DigitalDJ/tinytinyrss-fever-plugin ~/work/git/tinytinyrss-fever-plugin
cp -pr ~/work/git/tinytinyrss-fever-plugin ${HTTPS_DOCROOT}/tt-rss/plugins/fever

chown -R nginx. ${HTTPS_DOCROOT}/tt-rss

#-- database に初期データ投入
mysql -u ttrss -pttrsspass ttrss < ${HTTPS_DOCROOT}/tt-rss/schema/ttrss_schema_mysql.sql

#-- cron で定期的にデータを更新
echo "*/3 * * * * nginx php73 /var/www/html/https_root/tt-rss/update.php --feeds > /dev/null 2>&1" >> /etc/cron.d/${DOMAIN}-cron

メールアドレスでログインし、設定から fever plugin を有効にしてパスワードを設定する。fever に対応した RSS reader を使えば超便利。

15. 監視サーバ構築 – Zabbix [さくらのVPS/CentOS7]

・zabbixのインストール

#-- 変数に必要な値を代入
HTTPS_DOCROOT=/var/www/html/https_root

#-- zabbix 4.x のリポジトリを追加
rpm -Uvh http://repo.zabbix.com/zabbix/4.0/rhel/7/x86_64/zabbix-release-4.0-1.el7.noarch.rpm

#-- zabbix のインストール
yum install -y zabbix-server zabbix-server-mysql zabbix-web-mysql zabbix-web-japanese zabbix-agent zabbix-get zabbix-sender

#-- 不要なパッケージまでインストールされるので削除
yum remove -y zabbix-server-pgsql-4.0.3-1.el7.x86_64

#-- 必要な php パッケージをインストール
yum install -y php73-php-bcmath
systemctl restart php73-php-fpm

#-- zabbix database の作成 
mysql -e "create database zabbix character set utf8 collate utf8_bin;"
#-- database の password は お好みで
mysql -e "grant all on zabbix.* to zabbix@localhost identified by 'zabbixpass';"
mysql -e "FLUSH PRIVILEGES;"

#-- database に初期データの登録
zcat /usr/share/doc/zabbix-server-mysql-4.0.*/create.sql.gz | mysql -u zabbix -pzabbixpass zabbix

#-- zabbix-server の設定
sed -i "/^# DBPassword=/a DBPassword=zabbixpass" /etc/zabbix/zabbix_server.conf

#-- zabbix-server, zabbix-agent の起動
systemctl enable zabbix-server zabbix-agent
systemctl start zabbix-server zabbix-agent

#-- zabbix-web の設定
cat <<'_EOL_'> /etc/zabbix/web/zabbix.conf.php
<?php
// Zabbix GUI configuration file.
global $DB;

$DB['TYPE']     = 'MYSQL';
$DB['SERVER']   = 'localhost';
$DB['PORT']     = '0';
$DB['DATABASE'] = 'zabbix';
$DB['USER']     = 'zabbix';
$DB['PASSWORD'] = 'zabbixpass';

// Schema name. Used for IBM DB2 and PostgreSQL.
$DB['SCHEMA'] = '';

$ZBX_SERVER      = 'localhost';
$ZBX_SERVER_PORT = '10051';
$ZBX_SERVER_NAME = 'zabbix';

$IMAGE_FORMAT_DEFAULT = IMAGE_FORMAT_PNG;
_EOL_

#-- Zabbix server の監視開始
mysql -uzabbix -pzabbixpass zabbix -e "update hosts set status=0 where host = 'Zabbix server' ;"

#-- 下記は yum update 時も実施する必要がある
chown -R nginx. /etc/zabbix/web
ln -s /usr/share/zabbix ${HTTPS_DOCROOT}/zabbix

admin アカウントのパスワードはデフォルトのため、直ぐに変更すること
https://masdon.life/zabbix/
user: Admin , pass: zabbix

14. LDAP管理サーバ構築 – phpldapadmin [さくらのVPS/CentOS7]

・phpldapadmin の用途

  1. LDAPのレコード管理

・phpldapadmin のインストール

#-- 変数に必要な値を代入
HTTPS_DOCROOT=/var/www/html/https_root

#-- phpldapadmin本家は php7.x に対応していない為、 fork されたものを clone する
git clone https://github.com/breisig/phpLDAPadmin.git ~/work/git/phpldapadmin

cp -pr ~/work/git/phpldapadmin ${HTTPS_DOCROOT}/phpldapadmin
cp -p ${HTTPS_DOCROOT}/phpldapadmin/config/config.php{.example,}
chown -R nginx. ${HTTPS_DOCROOT}/phpldapadmin

#-- 複数ドメインがある場合は、カンマ区切りで追加する
sed -i -e "301i \$servers->setValue('server','base',array('dc=masdon,dc=life'));" ${HTTPS_DOCROOT}/phpldapadmin/config/config.php

#-- 使用しないテンプレートを移動
mkdir ${HTTPS_DOCROOT}/phpldapadmin/templates/creation_backup
for x in courierMailAccount.xml courierMailAlias.xml mozillaOrgPerson.xml sambaDomain.xml sambaGroupMapping.xml sambaMachine.xml sambaSamAccount.xml
do
  mv ${HTTPS_DOCROOT}/phpldapadmin/templates/creation/${x} ${HTTPS_DOCROOT}/phpldapadmin/templates/creation_backup
done

ログインユーザは RootDN

13. Webメールサーバ構築 – roundcube/rainloop [さくらのVPS/CentOS7]

・roundcubeの用途

  1. Webメール
  2. アカウントのパスワード変更
  3. メールのフォルダ振り分け/転送の設定

・roundcubeのインストール

#-- 変数に必要な値を代入
DOMAIN=masdon.life
HTTPS_DOCROOT=/var/www/html/https_root

#-- 1.3系の最新版を入手
git clone https://github.com/roundcube/roundcubemail.git ~/work/git/roundcubemail
cd ~/work/git/roundcubemail
VERSION=$(git for-each-ref --sort=-taggerdate --format='%(tag)' refs/tags | grep -m 1 "1\.3\.")
git checkout ${VERSION}
cp -pr ../roundcubemail ${HTTPS_DOCROOT}/roundcubemail-${VERSION}
ln -s ${HTTPS_DOCROOT}/roundcubemail-${VERSION} ${HTTPS_DOCROOT}/roundcube

#-- roundcube の DB を作成
mysql -e "create database roundcubemail character set utf8 collate utf8_bin;"
#-- database の password は お好みで
mysql -e "grant all on roundcubemail.* to roundcube@localhost identified by 'roundcube';"
mysql -e "FLUSH PRIVILEGES;"
mysql roundcubemail < ${HTTPS_DOCROOT}/roundcube/SQL/mysql.initial.sql

#-- 必要なPHPのライブラリをインストール
yum install -y php73-php-{pdo,xml,pear,mbstring,intl,pecl-imagick,gd,mysqlnd,pspell,pecl-zip}
yum install -y php-pear-Mail-mimeDecode php-kolab-net-ldap3 php-pear-Net-IDNA2 php-pear-Auth-SASL php-pear-Net-SMTP php-pear-Net-Sieve

#-- php-fpm の再起動
systemctl restart php73-php-fpm

#-- roundcube の設定
cat <<'_EOF_'> ${HTTPS_DOCROOT}/roundcube/config/config.inc.php
<?php
$config['db_dsnw'] = 'mysql://roundcube:roundcube@localhost/roundcubemail';
$config['default_host'] = array('_DOMAIN_');
$config['default_port'] = 993;
$config['smtp_server'] = '_DOMAIN_';
$config['smtp_port'] = 465;
$config['smtp_user'] = '%u';
$config['smtp_pass'] = '%p';
$config['support_url'] = '';
$config['product_name'] = 'Roundcube Webmail';
$config['des_key'] = 'rcmail-!24ByteDESkey*Str';
$config['plugins'] = array('managesieve', 'password', 'archive', 'zipdownload');
$config['managesieve_host'] = 'localhost';
$config['spellcheck_engine'] = 'pspell';
$config['skin'] = 'larry';
_EOF_

sed -i "s#_DOMAIN_#ssl://${DOMAIN}#" ${HTTPS_DOCROOT}/roundcube/config/config.inc.php

cp -p ${HTTPS_DOCROOT}/roundcube/plugins/managesieve/config.inc.php{.dist,}
sed -i -e "s/managesieve_vacation'] = 0/managesieve_vacation'] = 1/" ${HTTPS_DOCROOT}/roundcube/plugins/managesieve/config.inc.php

cp -p ${HTTPS_DOCROOT}/roundcube/plugins/password/config.inc.php{.dist,}

sed -i -e "s/'sql'/'ldap'/" \
       -e "s/'ou=people,dc=example,dc=com'/''/" \
       -e "s/'dc=exemple,dc=com'/''/" \
       -e "s/'uid=%login,ou=people,dc=exemple,dc=com'/'uid=%name,ou=People,%dc'/" \
       -e "s/'(uid=%login)'/'(uid=%name,ou=People,%dc)'/" ${HTTPS_DOCROOT}/roundcube/plugins/password/config.inc.php

chown -R nginx. ${HTTPS_DOCROOT}/roundcubemail-${VERSION}
cd ${HTTPS_DOCROOT}/roundcube/bin
./install-jsdeps.sh

mv ${HTTPS_DOCROOT}/roundcube/installer ${HTTPS_DOCROOT}/roundcube/_installer

・rainloop のインストール

#-- 変数に必要な値を代入
DOMAIN=masdon.life
HTTPS_DOCROOT=/var/www/html/https_root

#-- rainloop のインストール
mkdir -p ${HTTPS_DOCROOT}/rainloop
cd ${HTTPS_DOCROOT}/rainloop
curl -sL https://repository.rainloop.net/installer.php | php
chown -R nginx. ${HTTPS_DOCROOT}/rainloop
curl -s https://${DOMAIN}/rainloop/

#-- rainloop の設定
for x in $(ldapsearch -x mailroutingaddress | awk -F@ '/^mailRoutingAddress/{print $2}' | sort | uniq)
do
cat <<_EOL_> ${HTTPS_DOCROOT}/rainloop/data/_data_/_default_/domains/${x}.ini
imap_host = "${DOMAIN}"
imap_port = 993
imap_secure = "SSL"
imap_short_login = Off
sieve_use = Off
sieve_allow_raw = Off
sieve_host = ""
sieve_port = 4190
sieve_secure = "None"
smtp_host = "${DOMAIN}"
smtp_port = 465
smtp_secure = "SSL"
smtp_short_login = Off
smtp_auth = On
smtp_php_mail = Off
_EOL_
  chown nginx. ${HTTPS_DOCROOT}/rainloop/data/_data_/_default_/domains/${x}.ini
done

sed -i 's/$/,gmail.com/' ${HTTPS_DOCROOT}/rainloop/data/_data_/_default_/domains/disabled

cat <<_EOL_> /etc/nginx/conf.d/https.d/rainloop.conf
  location ^~ /rainloop/data {
    deny all;
  }
_EOL_

#-- nginx の再起動
systemctl reload nginx

admin アカウントのパスワードはデフォルトのため、直ぐに変更すること
https://masdon.life/rainloop/?ADMIN
user: admin , pass: 12345