PHP简单的密码库系统


main();

function main(){
	$url = 'https://www.baidu.com/';
	$host = getHost($url);

	if (empty($host)) {
		echo respone(100, 'URL Formatting error');
		exit();
	}

	$pass = getPass($host);

	if (empty($pass)) {
		$pass = createPass();
		$db = getDB();
		$db->$host = $pass;
		updateDB($db);
	}

	echo respone(0, 'Get Password Success', ['Password' => $pass]);
}

function getHost($url){
	$parse = parse_url($url);
	if (isset($parse['host'])) {
		return $parse['host'];
	} else {
		return '';
	}
}

function createPass(){
	$pass = array_merge(
		array_rand(array_flip(range(1, 9)), 2), 
		array_rand(array_flip(range('a', 'z')), 4), 
		array_rand(array_flip(range('A', 'Z')), 4), 
		array_rand(array_flip(array('@', '#', '$', '%', '+', '-')), 2)
	);
	shuffle($pass);
	return implode('', $pass);
}

function getPass($host){
	$db = getDB();
	if (isset($db->$host)) {
		return $db->$host;
	} else {
		return '';
	}
}

function getDB(){
	try {
		return json_decode(substr(file_get_contents('db.php'), 16));
	} catch (Exception $e) {
		return [];
	}
}

function updateDB($db){
	file_put_contents('db.php', "<?php exit();\n//" . json_encode($db)); 
} 

function respone($code = 0, $message = '', $data = []){ $respone = array( 'code' => intval($code),
		'data' => $data,
		'message' => $message
	);
	return json_encode($respone);
}

PHP实现并发下载


class BatchDown
{

	public $curl;
	public $task = array();
	
	function __construct(){
		$this->curl = curl_multi_init();
	}

	function __destruct(){
		curl_multi_close($this->curl);
	}

	function addTask($url, $file){
		$header = array(
			'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36',
			'Accept-Language: zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3',
			'Accept-Encoding: gzip, deflate',
			'Connection: keep-alive'
		);
		$c = curl_init($url);
		curl_setopt($c, CURLOPT_ENCODING, 'gzip');
		curl_setopt($c, CURLOPT_HTTPHEADER, $header);
		curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($c, CURLOPT_FOLLOWLOCATION, true);
		curl_setopt($c, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($c, CURLOPT_SSL_VERIFYHOST, false);
		curl_setopt($c, CURLOPT_TIMEOUT, 10);
		curl_multi_add_handle($this->curl, $c);
		$this->task[] = array(
			'url' => $url,
			'curl' => $c,
			'file' => $file
		);
	}

	function run(){
		$running = null;
		do {
			curl_multi_exec($this->curl, $running);
			curl_multi_select($this->curl);
		} while($running > 0);
		foreach ($this->task as $v) {
			$data = curl_multi_getcontent($v['curl']);
			file_put_contents($v['file'], $data);
			curl_multi_remove_handle($this->curl, $v['curl']);
			curl_close($v['curl']);
		}
	}

}

$url = 'https://www.baidu.com/';
$task = new BatchDown();

foreach (range(1, 3) as $v) {
	$task->addTask($url, $v . '.html');
}

$task->run();

使用阿里云API自动修改域名解析


define('AccessKeyId', 'KEY');
define('AccessKeySecret', 'Secret');

date_default_timezone_set('UTC');

/**
 *  获取本机 IP 地址
 */
function getIP() {
    $url = 'http://ip.taobao.com/service/getIpInfo.php?ip=myip';
    try {
        $json = json_decode(file_get_contents($url));
    } catch (Exception $e) {
        $json = [];
    }
    if (isset($json->code) && $json->code == 0) {
        return $json->data->ip;
    }
    return '';
}

/**
 *  获取请求签名
 */
function getSign($add){
    $nonce = time() . rand(11111, 99999);
    $time = date('Y-m-d') . 'T' . date('H:i:s') . 'Z';
    $data = array(
        'AccessKeyId' => AccessKeyId,
        'Format' => 'json',
        'SignatureMethod' => 'HMAC-SHA1',
        'SignatureNonce' => $nonce,
        'SignatureVersion' => '1.0',
        'Timestamp' => $time,
        'Version' => '2015-01-09'
    );
    $data = array_merge($data, $add);
    ksort($data);
    $format = http_build_query($data);
    $signUrl = 'GET&%2F&' . urlencode($format);
    $sign = urlencode(base64_encode(hash_hmac('sha1', $signUrl, AccessKeySecret . '&', true)));
    return array('url' => $format, 'sign' => $sign);
}

/**
 *  获取域名解析记录
 */
function getDNS($domain) {
    $sign = getSign(['Action' => 'DescribeSubDomainRecords', 'SubDomain' => $domain]);
    $url = 'https://alidns.aliyuncs.com/?' . $sign['url'] . '&Signature=' . $sign['sign'];
    $dns = json_decode(httpRequest($url));
    if (isset($dns->DomainRecords->Record[0])) {
        return $dns->DomainRecords->Record[0];
    }
    return '';
}

/**
 *  更新域名解析
 */
function updateDNS($id, $name, $ip) {
    $data = array(
        'Action' => 'UpdateDomainRecord',
        'RecordId' => $id,
        'RR' => $name,
        'Type' => 'A',
        'Value' => $ip,
    );
    $sign = getSign($data);
    $url = 'https://alidns.aliyuncs.com/?' . $sign['url'] . '&Signature=' . $sign['sign'];
    return httpRequest($url);
}

/**
 *  发起 HTTP 请求
 */
function httpRequest($url) {
    $header = array(
        'User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:45.0) Gecko/20100101 Firefox/45.0',
        'Accept-Language: zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3',
        'Accept-Encoding: gzip, deflate',
        'Connection: keep-alive',
    );

    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($curl, CURLOPT_ENCODING, 'gzip');
    curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    $data = curl_exec($curl);
    $error = curl_error($curl);
    curl_close($curl);
    if ($error) {
        return $error;
    } else {
        return $data;
    }
}

function main() {
    $dns = getDNS('www.test.com');
    $ip = getIP();
    if (isset($dns->RecordId)) {
        echo updateDNS($dns->RecordId, 'www', $ip);
    }
}

main();

CentOS7设置静态IP


TYPE="Ethernet"
BOOTPROTO="static"
DEFROUTE="yes"
IPV6INIT="no"
NAME="ens33"
DEVICE="ens33"
ONBOOT="yes"
IPADDR="10.0.0.4"
GATEWAY="10.0.0.1"
NETMASK="255.255.255.0"
DNS1="223.5.5.5"
DNS2="223.6.6.6"

Golang实现端口转发

package main

import (
	"io"
	"net"
)

func main() {
	server, err := net.Listen("tcp", ":8080")
	if err != nil {
		return
	}
	for {
		client, err := server.Accept()
		if err == nil {
			go handleClientRequest(client)
		}
	}
}

func handleClientRequest(client net.Conn) {
	defer client.Close()

	remote, err := net.Dial("tcp", "127.0.0.1:80")
	if err != nil {
		return
	}
	defer remote.Close()

	go io.Copy(remote, client)
	io.Copy(client, remote)
}

IP地址库解析


main();

function main(){
	$ip = isset($_GET["ip"]) ? $_GET["ip"] : "";

	if (empty($ip)) {
		IP::respone("101", "Empty IP");
		exit();
	}

	if (!preg_match("/(\d+\.){3}\d+/", $ip)) {
		IP::respone("102", "Wrong IP");
		exit();
	}

	$address = IP::find($ip);

	IP::respone("0", $address);
}

class IP {
	
    private static $ip     = NULL;
    private static $fp     = NULL;
    private static $offset = NULL;
    private static $index  = NULL;

    public static function find($ip)
    {
        if (empty($ip) === TRUE)
        {
            return "N/A";
        }

        $nip   = gethostbyname($ip);
        $ipdot = explode(".", $nip);

        if ($ipdot[0] < 0 || $ipdot[0] > 255 || count($ipdot) !== 4)
        {
            return "N/A";
        }

        if (self::$fp === NULL)
        {
            self::init();
        }

        $nip2 = pack("N", ip2long($nip));

        $tmp_offset = ((int)$ipdot[0] * 256 + (int)$ipdot[1]) * 4;
        $start      = unpack("Vlen", self::$index[$tmp_offset] . self::$index[$tmp_offset + 1] . self::$index[$tmp_offset + 2] . self::$index[$tmp_offset + 3]);

        $index_offset = $index_length = NULL;
        $max_comp_len = self::$offset["len"] - 262144 - 4;
        for ($start = $start["len"] * 9 + 262144; $start < $max_comp_len; $start += 9)
        {
            if (self::$index{$start} . self::$index{$start + 1} . self::$index{$start + 2} . self::$index{$start + 3} >= $nip2)
            {
                $index_offset = unpack("Vlen", self::$index{$start + 4} . self::$index{$start + 5} . self::$index{$start + 6} . "\x0");
                $index_length = unpack("nlen", self::$index{$start + 7} . self::$index{$start + 8});

                break;
            }
        }

        if ($index_offset === NULL)
        {
            return "N/A";
        }

        fseek(self::$fp, self::$offset["len"] + $index_offset["len"] - 262144);

        return explode("\t", fread(self::$fp, $index_length["len"]));
    }

    private static function init()
    {
        if (self::$fp === NULL)
        {
            self::$ip = new self();

            self::$fp = fopen(__DIR__ . "/ipdb.datx", "rb");
            if (self::$fp === FALSE)
            {
                throw new Exception("Invalid ipdb.datx file!");
            }

            self::$offset = unpack("Nlen", fread(self::$fp, 4));
            if (self::$offset["len"] < 4)
            {
                throw new Exception("Invalid ipdb.datx file!");
            }

            self::$index = fread(self::$fp, self::$offset["len"] - 4);
        }
    }

    public function __destruct()
    {
        if (self::$fp !== NULL)
        {
            fclose(self::$fp);

            self::$fp = NULL;
        }
    }

    public static function respone($code, $data){
        echo json_encode(["code" => $code, "data" => $data], JSON_UNESCAPED_UNICODE);
    }

}

Golang使用redis连接池


package main

import (
	"github.com/gin-gonic/gin"
	"github.com/gomodule/redigo/redis"
	"log"
)

var redisPool *redis.Pool
var err error

func main() {

	redisPool = RedisPollInit()

	gin.SetMode(gin.ReleaseMode)

	r := gin.Default()

	r.GET("/", IndexAction)

	r.GET("/ping", PingAction)

	r.GET("/user/:name", UserAction)

	r.GET("/agent", AgentAction)

	r.GET("/admin", AdminAction)

	r.Run(":80")

}

func RedisPollInit() *redis.Pool {
	return &redis.Pool{
		MaxIdle:   3,
		MaxActive: 5,
		Dial: func() (redis.Conn, error) {
			c, err := redis.Dial("tcp", "127.0.0.1:6379")
			if err != nil {
				return nil, err
			}

			_, err = c.Do("AUTH", "123456")
			if err != nil {
				c.Close()
				return nil, err
			}
			return c, err
		},
	}
}

func IndexAction(c *gin.Context) {
	c.JSON(200, gin.H{"message": "index"})
}

func PingAction(c *gin.Context) {
	c.JSON(200, gin.H{"message": "pong"})
}

func UserAction(c *gin.Context) {
	c.String(200, "Hello %s", c.Param("name"))
}

func AgentAction(c *gin.Context) {
	c.String(200, c.GetHeader("user-agent"))
}

func AdminAction(c *gin.Context) {

	conn := redisPool.Get()
	defer conn.Close()

	data, err := redis.String(conn.Do("GET", "username"))
	if err != nil {
		log.Println(err)
		return
	}
	c.String(200, data)
}