阿里云短信发送代码封装

忽见某一高手为了实现发送短信,竟然引入了整个aliyunsdk,我一阵语塞。。。

在这里分享一个项目中调用阿里云短信发送的PHP实现吧。

注意:下面的类中 namespaceconfig 均为伪代码,请自行替换。

/**
 * 阿里云短信
 * @package rehiy\util
 * @author 若海<https://www.rehiy.com>
 */

namespace rehiy\util;

use rehiy\Config;
use rehiy\Exception;

class AliyunSms
{
    protected $accessKeyId = '';
    protected $accessKeySecret = '';

    protected $signName = '';
    protected $templateCode = '';

    protected $apiUrl = 'http://dysmsapi.aliyuncs.com/';

    public function __construct()
    {
        $this->accessKeyId = Config::get('sms_appid');
        $this->accessKeySecret = Config::get('sms_secret');

        $this->signName = Config::get('sms_signame');
        $this->templateCode = Config::get('sms_template_code');
    }

    public function send(string $phone, array $data)
    {
        $params = [
            'AccessKeyId' => $this->accessKeyId,
            'Action' => 'SendSms',
            'Format' => 'JSON',
            'PhoneNumbers' => $phone,
            'RegionId' => 'cn-hangzhou',
            'SignName' => $this->signName,
            'SignatureMethod' => 'HMAC-SHA1',
            'SignatureNonce' => uniqid(mt_rand(0, 0xffff), true),
            'SignatureVersion' => '1.0',
            'Timestamp' => gmdate('Y-m-d\TH:i:s\Z'),
            'Version' => '2017-05-25',
            'TemplateCode' => $this->templateCode,
            'TemplateParam' => json_encode($data, JSON_UNESCAPED_UNICODE),
        ];

        ksort($params);
        $sortedQuery = http_build_query($params, '', '&', PHP_QUERY_RFC3986);

        $signature = "POST&%2F&" . rawurlencode($sortedQuery);
        $signature = rawurlencode(
            base64_encode(hash_hmac('sha1', $signature, $this->accessKeySecret . '&', true))
        );

        $body = "Signature={$signature}&{$sortedQuery}";
        $header = ['x-sdk-client' => 'php/2.0.0'];

        return $this->httpRequest('POST', $this->apiUrl, $body, $header);
    }

    private function httpRequest(string $method, string $url, $data = null, $header = [])
    {
        $ch = curl_init($url);

        curl_setopt($ch, CURLOPT_TIMEOUT, 25);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);

        if (!empty($header)) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        }

        if ($data && is_array($data)) {
            $data = http_build_query($data);
        }
        if ($method == 'POST' && $data) {
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        }

        list($body, $errno, $error) = [
            curl_exec($ch), curl_errno($ch), curl_error($ch), curl_close($ch)
        ];

        if ($errno != 0) {
            throw new Exception('CURL - ' . $error, $errno);
        }

        try {
            return json_decode($body, true);
        } catch (Exception $e) {
            return false;
        }
    }
}

AlpineLinux 升级v3.14到v3.15

重要提示: 新版系统的 sshd 禁用了 ssh-rsa 密钥,如果你使用了此类密钥登录,请一定要开启 ssh-rsa 认证方式。

#!/bin/sh
#

# 更新系统版本

sed -i 's/3.14/3.15/g' /etc/apk/repositories

# 更新系统软件

apk update

apk add --upgrade apk-tools
apk upgrade --available && sync

# 修改 motd 内容

echo "Welcome to Alpine!" >/etc/motd

# 升级 sshd 配置

if [ -f /etc/ssh/sshd_config.apk-new ]; then
    rm -f /etc/ssh/sshd_config
    mv /etc/ssh/sshd_config.apk-new /etc/ssh/sshd_config
    echo "" >>/etc/ssh/sshd_config
    echo "Port 2200" >>/etc/ssh/sshd_config
    echo "PubkeyAcceptedKeyTypes=+ssh-rsa" >>/etc/ssh/sshd_config
fi

# 升级 mkinitfs 配置

if [ -f /etc/mkinitfs/mkinitfs.conf.apk-new ]; then
    rm -f /etc/mkinitfs/mkinitfs.conf
    mv /etc/mkinitfs/mkinitfs.conf.apk-new /etc/mkinitfs/mkinitfs.conf
fi

# 清理已知冗余配置

rm -f \
    /etc/update-extlinux.conf.apk-new \
    /etc/shadow.apk-new \
    /etc/fstab.apk-new \
    /etc/inittab.apk-new \
    /etc/motd.apk-new \
    /etc/passwd.apk-new \
    /etc/fstab.apk-new \
    /etc/hostname.apk-new \
    /etc/group.apk-new \
    /etc/hosts.apk-new \
    /etc/conf.d/loadkmap.apk-new \
    /etc/conf.d/node-exporter.apk-new

# 查看其他未处理的配置

find /etc/ -name *-new

key type ssh-rsa not in PubkeyAcceptedAlgorithms

全新安装 AlpinLinux-v3.15.0,配置好之前使用的密钥。

竟然无法登录 ??错误信息: key type ssh-rsa not in PubkeyAcceptedAlgorithms

竟然不支持 ssh-rsa。这也太搞笑了吧,翻阅 OpenSSH 文档后,终于顺利解决。

echo "PubkeyAcceptedKeyTypes=+ssh-rsa" >>/etc/ssh/sshd_config

NodeJS通过魔术封包唤醒局域网计算机

国庆假期就这么过去了,今天分享下NodeJS如何通过魔术封包唤醒局域网计算机的代码吧。

/**
 * 通过魔术封包唤醒局域网计算机
 * @author 若海 <[email protected]>
 * @website http://www.rehiy.com
 * @wiki https://en.wikipedia.org/wiki/Wake-on-LAN
 * @docs http://support.amd.com/TechDocs/20213.pdf
 */

const net = require('net');
const udp = require('dgram');

/**
 * 创建魔术封包
 * @param {string} mac 网卡MAC地址
 * @returns {Buffer}
 */
function createMagicPacket(mac) {
    mac = mac.replace(/[^0-9a-fA-F]/g, '');

    if (mac.length != 12) {
        throw new Error(`Bad MAC address "${mac}"`);
    }

    const bufMac = Buffer.from(mac, 'hex');

    let bufRes = Buffer.alloc(6, 0xff);
    for (let i = 0; i < 16; i++) {
        bufRes = Buffer.concat([bufRes, bufMac]);
    }

    return bufRes;
}

/**
 * 通过网络唤醒
 * @param {string} mac 网卡MAC地址
 * @param {object} options 可选项
 * @returns {Promise<boolean>}
 */
function wakeOnLAN(mac, options) {
    options = Object.assign({
        address: '255.255.255.255',
        port: 7
    }, options);

    return new Promise((resolve, reject) => {
        const packet = createMagicPacket(mac);

        const socket = udp.createSocket(
            net.isIPv6(options.address) ? 'udp6' : 'udp4'
        );

        socket.on('error', function (err) {
            socket.close();
            reject(err);
        });

        socket.once('listening', function () {
            socket.setBroadcast(true);
        });

        socket.send(
            packet,
            0,
            packet.length,
            options.port,
            options.address,
            function (err, res) {
                socket.close();
                if (err) {
                    return reject(err);
                }
                resolve(res == packet.length);
            }
        );
    });
}

来个例子~

wakeOnLAN('30:9C:FF:FF:FF:FF').then(
    res => {
        console.log(res);
    },
    err => {
        console.log(err.message);
    }
);

AlpineLinux 使用goaccess分析nginx日志

此脚本可以在alpinelinux上直接运行,如果你是其他操作系统,请适当修改后执行。

脚本依次执行如下操作
0、goaccessnginx 变量对照表
1、安装 goaccess 软件包
2、配置 goaccess 参数
3、配置 nginx 日志
4、下载 geoip 数据库
5、启动 goaccess 服务

#!/bin/sh
#
# Author: [email protected]
# Refer : https://www.rehiy.com/post/291
#
# Nginx Log Conversion table:
#   $time_local         %d:%t %^
#   $host               %v
#   $http_host          %v
#   $remote_addr        %h
#   $request_time       %T
#   $request_method     %m
#   $request_uri        %U
#   $server_protocol    %H
#   $request            %r
#   $status             %s
#   $body_bytes_sent    %b
#   $bytes_sent         %b
#   $http_referer       %R
#   $http_user_agent    %u
#

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

if ! type goaccess >/dev/null; then
  apk add goaccess
fi

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

cat <<EOF >/etc/goaccess/goaccess.conf 
time-format %T
date-format %d/%b/%Y
log_format %h - %e [%d:%t %^] "%r" %s %b "%R" "%u" "%^" %^ %^ %^ %T
geoip-database /usr/share/geoip/GeoIPCity.dat
ws-url wss://goac.example.org:443/report/d
EOF

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

sed -i 's/  access_log off/# access_log off/' /etc/nginx/nginx.conf

cat <<EOF >/etc/nginx/http.d/access-log.conf
log_format access
    '\$remote_addr - \$remote_user [\$time_local] "\$request" '
    '\$status \$body_bytes_sent "\$http_referer" "\$http_user_agent" "\$http_x_forwarded_for" '
    '\$connection \$upstream_addr \$upstream_response_time \$request_time'
;
access_log /var/log/nginx/access.log access;
EOF

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

cd /usr/share/geoip/

wget https://mailfud.org/geoip-legacy/GeoIP.dat.gz
wget https://mailfud.org/geoip-legacy/GeoIPv6.dat.gz
wget https://mailfud.org/geoip-legacy/GeoIPCity.dat.gz
wget https://mailfud.org/geoip-legacy/GeoIPCityv6.dat.gz

gunzip *.gz

cd /tmp

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

odir=/var/www/default/net.jidns.spry/report

mkdir -p $odir $odir/archive

goaccess /var/log/nginx/access.log \
    -o $odir/index.html \
    --real-time-html \
    --daemonize \

php7实现JWT认证

class JwtAuth
{
    //交换密钥
    private static $key = '123456';

    //头部信息
    private static $header = [
        'alg' => 'HS256', //算法名称
        'typ' => 'JWT', //令牌类型
    ];

    //加密方式
    private static $hash_algos = [
        'HS256' => 'sha256',
    ];

    /**
     * 获取 jwt token
     * @param array $payload jwt载荷,格式如下非必须
     * [
     * 'iss'=>'jwt_admin', //该JWT的签发者
     * 'iat'=>time(), //签发时间
     * 'exp'=>time()+7200, //过期时间
     * 'nbf'=>time()+60, //该时间之前不接收处理该Token
     * 'sub'=>'www.admin.com', //面向的用户
     * 'jti'=>md5(uniqid('JWT').time()) //该Token唯一标识
     * ]
     * @return bool|string
     */
    public static function getToken($payload)
    {
        if (is_array($payload)) {
            $base64header = self::base64UrlEncode(json_encode(self::$header, JSON_UNESCAPED_UNICODE));
            $base64payload = self::base64UrlEncode(json_encode($payload, JSON_UNESCAPED_UNICODE));
            $sign = self::signature($base64header . '.' . $base64payload, self::$header['alg']);
            return $base64header . '.' . $base64payload . '.' . $sign;
        }
        return false;
    }

    /**
     * 验证token是否有效,默认验证exp,nbf,iat时间
     * @param string $token 需要验证的token
     * @return bool|string
     */
    public static function verifyToken($token)
    {
        $tokens = explode('.', $token);
        if (count($tokens) != 3) {
            return false;
        }

        list($base64header, $base64payload, $sign) = $tokens;

        //获取算法
        $header = json_decode(self::base64UrlDecode($base64header), JSON_OBJECT_AS_ARRAY);
        if (empty($header['alg'])) {
            return false;
        }

        //签名验证
        if ($sign != self::signature($base64header . '.' . $base64payload, $header['alg'])) {
            return false;
        }

        $payload = json_decode(self::base64UrlDecode($base64payload), JSON_OBJECT_AS_ARRAY);

        //签发时间大于当前服务器时间验证失败
        if (isset($payload['iat']) && $payload['iat'] > time()) {
            return false;
        }

        //过期时间小宇当前服务器时间验证失败
        if (isset($payload['exp']) && $payload['exp'] < time()) {
            return false;
        }

        //该nbf时间之前不接收处理该Token
        if (isset($payload['nbf']) && $payload['nbf'] > time()) {
            return false;
        }

        return $payload;
    }

    /**
     * base64UrlEncode https://jwt.io/ 中base64UrlEncode编码实现
     * @param string $input 需要编码的字符串
     * @return string
     */
    private static function base64UrlEncode($input)
    {
        return str_replace('=', '', strtr(base64_encode($input), '+/', '-_'));
    }

    /**
     * base64UrlDecode https://jwt.io/ 中base64UrlEncode解码实现
     * @param string $input 需要解码的字符串
     * @return bool|string
     */
    private static function base64UrlDecode($input)
    {
        $remainder = strlen($input) % 4;
        if ($remainder) {
            $addlen = 4 - $remainder;
            $input .= str_repeat('=', $addlen);
        }
        return base64_decode(strtr($input, '-_', '+/'));
    }

    /**
     * HMACSHA256签名 https://jwt.io/ 中HMACSHA256签名实现
     * @param string $input 为base64UrlEncode(header).'.'.base64UrlEncode(payload)
     * @param string $alg  算法方式
     * @return mixed
     */
    private static function signature($input, $alg = 'HS256')
    {
        return self::base64UrlEncode(
            hash_hmac(self::$hash_algos[$alg], $input, self::$key, true)
        );
    }
}

//测试和官网示例是否匹配
$payload = ['sub' => '1234567890', 'name' => 'John Doe', 'iat' => 1516239022];
$token = JwtAuth::getToken($payload);

//对token进行验证签名
$getPayload = JwtAuth::verifyToken($token);

echo $token;
echo "\n\n";
var_dump($getPayload);

实现docker跨主机通信(Swarm版)

本文将在云服务器之间实现基于Swarm集群的overlay网络,以达到跨主机通信的目的。

docker 的安装教程非常之多,这里不再赘述。

环境配置

节点名 节点IP 节点服务
dnode0 10.0.0.11 安装 Docker,并初始化Swarm集群
dnode1 10.0.0.12 安装 Docker
dnode2 10.0.0.13 安装 Docker

配置三台机器,请注意修改hostname为不同的值,防火墙放行如下端口:

  • TCP port 2376 for secure Docker client communication. This port is required for Docker Machine to work. Docker Machine is used to orchestrate Docker hosts.
  • TCP port 2377 is used for communication between the nodes of a Docker Swarm or cluster. It only needs to be opened on manager nodes.
  • UDP port 4789 for overlay network traffic (container ingress networking).
  • TCP and UDP port 7946 for communication among nodes (container network discovery).

初始化Swarm集群服务

docker swarm init

如果没有记住加入集群的token,以下可以重新获取

docker swarm join-token worker

其他节点分别加入Swarm集群

docker swarm join --token SWMTKN-1-tokenxxxxxxx 10.0.0.11:2377

在节点上创建网络

docker network create --driver overlay --subnet=10.0.2.0/24 --gateway=10.0.2.1 --attachable ovnet

分别在不同的节点上创建可以互通的容器

docker run -it --rm --network ovnet --ip 10.0.2.5 alpine
docker run -it --rm --network ovnet --ip 10.0.2.6 alpine
docker run -it --rm --network ovnet --ip 10.0.2.7 alpine

快速创建consul集群

操作环境

  • 三台AlpineLinux主机
    • 主机名分别为host-11/12/13
    • IP地址分别为192.168.0.11/12/13

自动执行脚本

#!/bin/sh
#

###############################################################
# consul-1/2/3

apk add consul
rc-update add consul boot

cat <<EOF >/etc/consul/server.json
{
  "datacenter": "test",
  "data_dir": "/var/consul",
  "server": true,
  "bootstrap_expect": 3,
  "bind_addr": "{{ GetInterfaceIP \"eth0\" }}",
  "client_addr": "0.0.0.0",
  "retry_join": [
    "192.168.0.11",
    "192.168.0.12",
    "192.168.0.13"
  ],
  "ui_config": {
    "enabled": true
  }
}
EOF

rc-service consul start

###############################################################
# consul-cli

consul members

consul operator raft list-peers

快速创建自签名ssl证书

运行环境为Linux,且已安装openssl组件。若为Windows环境,请相应修改前3行代码即可。

mkdir -p ~/myssl
cd ~/myssl

cat <<EOF >self.cnf
[ req ]
distinguished_name = req_distinguished_name
[ req_distinguished_name ]
[ v3_req ]
subjectAltName = @alt_names
[ alt_names ]
DNS.1 = example.org
DNS.2 = *.example.org
EOF

SUBJECT="/C=CN"
SUBJECT="$SUBJECT/ST=Beijing"
SUBJECT="$SUBJECT/L=Beijing"
SUBJECT="$SUBJECT/O=ExampleOrg"
SUBJECT="$SUBJECT/OU=Devops"
SUBJECT="$SUBJECT/CN=example.org"
SUBJECT="$SUBJECT/[email protected]"

openssl req -newkey rsa:4096 -x509 -nodes -days 3650 -extensions v3_req \
    -config self.cnf -keyout server.key -out server.crt -subj "$SUBJECT"