上药三品,神与气精

曾因酒醉鞭名马 生怕情多累美人


  • 首页

  • 关于

  • 分类

  • 标签

  • 归档

  • 搜索

one-blockchain-src-anal

发表于 2018-03-27 | 阅读次数:
字数统计: 1.3k | 阅读时长 ≈ 8

看看代码的实现:

import hashlib
import json
from time import time
from urllib.parse import urlparse
from uuid import uuid4

import requests
from flask import Flask, jsonify, request


class Blockchain:
    def __init__(self):
        self.current_transactions = []
        self.chain = []
        self.nodes = set()

        # Create the genesis block
        self.new_block(previous_hash='1', proof=100)

    def register_node(self, address):
        """
        Add a new node to the list of nodes

        :param address: Address of node. Eg. 'http://192.168.0.5:5000'
        """

        parsed_url = urlparse(address)
        if parsed_url.netloc:
            self.nodes.add(parsed_url.netloc)
        elif parsed_url.path:
            # Accepts an URL without scheme like '192.168.0.5:5000'.
            self.nodes.add(parsed_url.path)
        else:
            raise ValueError('Invalid URL')


    def valid_chain(self, chain):
        """
        Determine if a given blockchain is valid

        :param chain: A blockchain
        :return: True if valid, False if not
        """

        last_block = chain[0]
        current_index = 1

        while current_index < len(chain):
            block = chain[current_index]
            print(f'{last_block}')
            print(f'{block}')
            print("\n-----------\n")
            # Check that the hash of the block is correct
            if block['previous_hash'] != self.hash(last_block):
                return False

            # Check that the Proof of Work is correct
            if not self.valid_proof(last_block['proof'], block['proof'], last_block['previous_hash']):
                return False

            last_block = block
            current_index += 1

        return True

    def resolve_conflicts(self):
        """
        This is our consensus algorithm, it resolves conflicts
        by replacing our chain with the longest one in the network.

        :return: True if our chain was replaced, False if not
        """

        neighbours = self.nodes
        new_chain = None

        # We're only looking for chains longer than ours
        max_length = len(self.chain)

        # Grab and verify the chains from all the nodes in our network
        for node in neighbours:
            response = requests.get(f'http://{node}/chain')

            if response.status_code == 200:
                length = response.json()['length']
                chain = response.json()['chain']

                # Check if the length is longer and the chain is valid
                if length > max_length and self.valid_chain(chain):
                    max_length = length
                    new_chain = chain

        # Replace our chain if we discovered a new, valid chain longer than ours
        if new_chain:
            self.chain = new_chain
            return True

        return False

    def new_block(self, proof, previous_hash):
        """
        Create a new Block in the Blockchain

        :param proof: The proof given by the Proof of Work algorithm
        :param previous_hash: Hash of previous Block
        :return: New Block
        """

        block = {
            'index': len(self.chain) + 1,
            'timestamp': time(),
            'transactions': self.current_transactions,
            'proof': proof,
            'previous_hash': previous_hash or self.hash(self.chain[-1]),
        }

        # Reset the current list of transactions
        self.current_transactions = []

        self.chain.append(block)
        return block

    def new_transaction(self, sender, recipient, amount):
        """
        Creates a new transaction to go into the next mined Block

        :param sender: Address of the Sender
        :param recipient: Address of the Recipient
        :param amount: Amount
        :return: The index of the Block that will hold this transaction
        """
        self.current_transactions.append({
            'sender': sender,
            'recipient': recipient,
            'amount': amount,
        })

        return self.last_block['index'] + 1

    @property
    def last_block(self):
        return self.chain[-1]

    @staticmethod
    def hash(block):
        """
        Creates a SHA-256 hash of a Block

        :param block: Block
        """

        # We must make sure that the Dictionary is Ordered, or we'll have inconsistent hashes
        block_string = json.dumps(block, sort_keys=True).encode()
        return hashlib.sha256(block_string).hexdigest()

    def proof_of_work(self, last_block):
        """
        Simple Proof of Work Algorithm:

         - Find a number p' such that hash(pp') contains leading 4 zeroes
         - Where p is the previous proof, and p' is the new proof

        :param last_block: <dict> last Block
        :return: <int>
        """

        last_proof = last_block['proof']
        last_hash = self.hash(last_block)

        proof = 0
        while self.valid_proof(last_proof, proof, last_hash) is False:
            proof += 1

        return proof

    @staticmethod
    def valid_proof(last_proof, proof, last_hash):
        """
        Validates the Proof

        :param last_proof: <int> Previous Proof
        :param proof: <int> Current Proof
        :param last_hash: <str> The hash of the Previous Block
        :return: <bool> True if correct, False if not.

        """

        guess = f'{last_proof}{proof}{last_hash}'.encode()
        guess_hash = hashlib.sha256(guess).hexdigest()
        return guess_hash[:4] == "0000"


# Instantiate the Node
app = Flask(__name__)

# Generate a globally unique address for this node
node_identifier = str(uuid4()).replace('-', '')

# Instantiate the Blockchain
blockchain = Blockchain()


@app.route('/mine', methods=['GET'])
def mine():
    # We run the proof of work algorithm to get the next proof...
    last_block = blockchain.last_block
    proof = blockchain.proof_of_work(last_block)

    # We must receive a reward for finding the proof.
    # The sender is "0" to signify that this node has mined a new coin.
    blockchain.new_transaction(
        sender="0",
        recipient=node_identifier,
        amount=1,
    )

    # Forge the new Block by adding it to the chain
    previous_hash = blockchain.hash(last_block)
    block = blockchain.new_block(proof, previous_hash)

    response = {
        'message': "New Block Forged",
        'index': block['index'],
        'transactions': block['transactions'],
        'proof': block['proof'],
        'previous_hash': block['previous_hash'],
    }
    return jsonify(response), 200


@app.route('/transactions/new', methods=['POST'])
def new_transaction():
    values = request.get_json()

    # Check that the required fields are in the POST'ed data
    required = ['sender', 'recipient', 'amount']
    if not all(k in values for k in required):
        return 'Missing values', 400

    # Create a new Transaction
    index = blockchain.new_transaction(values['sender'], values['recipient'], values['amount'])

    response = {'message': f'Transaction will be added to Block {index}'}
    return jsonify(response), 201


@app.route('/chain', methods=['GET'])
def full_chain():
    response = {
        'chain': blockchain.chain,
        'length': len(blockchain.chain),
    }
    return jsonify(response), 200


@app.route('/nodes/register', methods=['POST'])
def register_nodes():
    values = request.get_json()

    nodes = values.get('nodes')
    if nodes is None:
        return "Error: Please supply a valid list of nodes", 400

    for node in nodes:
        blockchain.register_node(node)

    response = {
        'message': 'New nodes have been added',
        'total_nodes': list(blockchain.nodes),
    }
    return jsonify(response), 201


@app.route('/nodes/resolve', methods=['GET'])
def consensus():
    replaced = blockchain.resolve_conflicts()

    if replaced:
        response = {
            'message': 'Our chain was replaced',
            'new_chain': blockchain.chain
        }
    else:
        response = {
            'message': 'Our chain is authoritative',
            'chain': blockchain.chain
        }

    return jsonify(response), 200


if __name__ == '__main__':
    from argparse import ArgumentParser

    parser = ArgumentParser()
    parser.add_argument('-p', '--port', default=5000, type=int, help='port to listen on')
    args = parser.parse_args()
    port = args.port

    app.run(host='0.0.0.0', port=port)

提供了几个url:

mine GET

transactions/new POST

chain GET

nodes/register POST

nodes/resolve GET

/transactions/new to create a new transaction to a block
/mine to tell our server to mine a new block.
/chain to return the full Blockchain.
/nodes/register to accept a list of new nodes in the form of URLs.
/nodes/resolve to implement our Consensus Algorithm, which resolves any 
        conflicts—to ensure a node has the correct chain.

单个区块:

block = {
    'index': 1,
    'timestamp': 1506057125.900785,
    'transactions': [
        {
            'sender': "8527147fe1f5426f9dd545de4b27ee00",
            'recipient': "a77f5cdfa2934df3954a5c7c7da5df1f",
            'amount': 5,
        }
    ],
    'proof': 324984774000,
    'previous_hash': "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"
}    

blockchain-note

发表于 2018-03-27 | 分类于 AI | 阅读次数:
字数统计: 608 | 阅读时长 ≈ 2

区块链

中本聪2008年发表了《比特币:一种点对点式的电子现金系统》的论文。
以太坊是2013年开创的项目。

区块 账户 共识 智能合约

本质上是一种健壮和安全的分布式状态机,五项核心能力:

存储数据

共有数据

分布式

防篡改与隐私保护

数字化合约

三个方面可信:

数据可信

合约履行

历史可证明

目前典型的区块链账本设计为区块的单链表结构,只有增加没有减少,全局来说只有顺序处理,无法实现并行度。

目前涉及到的知识:分布式 存储 密码学 网络通讯 芯片技术 经济学 法律等。

应用场景

  • 供应链领域

  • 金融领域

  • 政务及公共服务领域

  • 其他领域: 保险防欺诈、大数据安全

原则 面向业务、标准化、松耦合与模块化、安全可审计、简洁与效率。

对 python的认识

1.上下文管理器

with open('data.txt') as source, open('target.txt') as target:
    target.write(source.read())

上下文管理器协议 需要实现 __enter__(), __exit__()

​
2.装饰器

装饰器本质上就是一个函数,这个函数接收其他函数作为参数,并将其以一个新的修改后的函数进行替换。

import functools
import inspect

def check_is_admin(f):
    @functools.wraps(f)
    def wrapper(*args, **kwargs):
        func_args = inspect.getcallargs(f, *args, **kwargs)
        print func_args
        if func_args.get('username') != 'admin':
            raise Exception("This user is not allowed to get food")
        return f(*args, **kwargs)
    return wrapper

​
@check_is_admin
def get_food(username, food=’chocolate’):
return “{0} get food: {1}”.format(username, food)

​
def main():
print get_food(‘admin’)

if __name__ == '__main__':
    main()

​
装饰器不必检查参数username是基于位置的参数还是基于关键字的参数,而只需在字典中查找即可。

def makebold(fn):
    def wrapped():
        return "<b>" + fn() + "</b>"
    return wrapped

def makeitalic(fn):
    def wrapped():
        return "<i>" + fn() + "</i>"
    return wrapped

@makebold
@makeitalic
def hello():
    return "hello world"

print hello() ## returns <b><i>hello world</i></b>

3.全局变量

4.时间复杂度

list实质上是一个数组

使用链表的时候,应该用collection.deque 双向链表

set的实现是hash标,判断元素是否在某个集合中使用set,时间复杂度低。

5.python中的else

循环使用else 不建议
try…except 中else 建议加else

​

云计算综述

发表于 2018-03-23 | 分类于 compute | 阅读次数:
字数统计: 1.2k | 阅读时长 ≈ 4

neutron nova keystone 各种组件

网络技术领域知识

平安科技(深圳)有限公司

1.image 创建命令:

1
2
glance image-create --name cirros --file /tmp/cirros-0.3.4-x86_64-disk.img --
disk-format qcow2 --container-format bare --progress

2.详细命令:

keystone user-list # 被取代
openstack user list

glance image-create
glance image-delete
glance image-update
glance image-list
glance image-show    

neutron net-create
neutron net -delete
neutron net -update
neutron net -list
neutron net –show    

neutron subnet-create
neutron subnet -delete
neutron subnet -update
neutron subnet -list
neutron subnet–show

nova boot
nova delete
nova list
nova show    

# 每个对象都有id

tcp/ip协议不是一个协议,而是一个协议族的统称。里面包括了IP协议,IMCP协议,TCP协议,以及我们更加熟悉的http、ftp、pop3协议等等

1.为什么建立连接协议是三次握手,而关闭连接却是四次握手呢?

这是因为服务端的LISTEN状态下的SOCKET当收到SYN报文的建连请求后,它可以把ACK和SYN(ACK起应答作用,而SYN起同步作用)放在一个报文里来发送。但关闭连接时,当收到对方的FIN报文通知时,它仅仅表示对方没有数据发送给你了;但未必你所有的数据都全部发送给对方了,所以你可以未必会马上会关闭SOCKET,也即你可能还需要发送一些数据给对方之后,再发送FIN报文给对方来表示你同意现在可以关闭连接了,所以它这里的ACK报文和FIN报文多数情况下都是分开发送的。

2.为什么TIME_WAIT状态还需要等2MSL后才能返回到CLOSED状态?

这是因为虽然双方都同意关闭连接了,而且握手的4个报文也都协调和发送完毕,按理可以直接回到CLOSED状态(就好比从SYN_SEND状态到ESTABLISH状态那样);但是因为我们必须要假想网络是不可靠的,你无法保证你最后发送的ACK报文会一定被对方收到,因此对方处于LAST_ACK状态下的SOCKET可能会因为超时未收到ACK报文,而重发FIN报文,所以这个TIME_WAIT状态的作用就是用来重发可能丢失的ACK报文。

sdn

SDN采用与传统网络截然不同的控制架构,将网络控制平面分离和转发平面分离,采用集中控制替代原有分布式控制,并通过开放和可编程接口实现“软件定义”。与传统的网络架构相比,SDN通过软硬件分离,实现了网络虚拟化、IT化及软件化,并降低了设备的复杂度、简化网络运维、提高网络利用率、加速网络创新。

evpn

EVPN是一种虚拟私有网络,那么在一套物理设备上必然可以有多个同时存在的EVPN实例,每个实例独立存在。每个EVI连接了一组或者多组用户网络,构成一个或者多个跨地域的二层网络。

vxlan

虚拟可拓展局域网

from multiprocessing import Pool
from multiprocessing.dummy import Pool
哪个速度快就用那个。尽量在写兼容的方式,这样在多线程/多进程之间切换非常方便。

现在,如果一个任务拿不准是CPU密集还是I/O密集型,且没有其它不能选择多进程方式的因素,都统一直接上多进程模式。

使用多线程(threading)和多进程(multiprocessing)完成常规的需求,在启动的时候start、jon等步骤不能省,复杂的需要还要用1-2个队列。随着需求越来越复杂,如果没有良好的设计和抽象这部分的功能层次,代码量越多调试的难度就越大。有没有什么好的方法把这些步骤抽象一下呢,让我们不关注这些细节,轻装上阵呢?

答案是:有的。

从Python3.2开始一个叫做concurrent.futures被纳入了标准库,而在Python2它属于第三方的futures库,需要手动安装:

这个模块中有2个类:ThreadPoolExecutor和ProcessPoolExecutor,也就是对threading和multiprocessing的进行了高级别的抽象,
暴露出统一的接口,帮助开发者非常方便的实现异步调用

  • lsvirtualenv: 列出全部的虚拟环境
  • showvirtualenv: 列出单个虚拟环境的信息
  • rmvirtualenv: 删除一个虚拟环境
  • cpvirtualenv: 拷贝虚拟环境
  • allvirtualenv: 对当前虚拟环境执行统一的命令。 比如, 要给 venv1 和 venv2 都安装flask, 就可以用allvirtualenv pip install flask
  • cdvirtualenv: 可以直接切换到虚拟环境的子目录里面

mac-use-tips

发表于 2018-03-19 | 阅读次数:
字数统计: 2.3k | 阅读时长 ≈ 9

快捷键与触摸板

cmd 为 command 按键,通常情况下为所有桌面程序通用性的快捷键。
ctrl ,通常情况下是针对程序的功能进行加强,并且此功能往往是非 cmd 类(窗口操作,选择,复制粘贴等等)操作。
shift 按键通常用于加强操作。一般会让操作更进一步 or 相反操作。
cmd+tab =~ alt+tab 程序之间的切换
cmd+` 应用内窗口切换
cmd+h 窗口 hide
cmd+m 窗口 minimize
cmd+n 新建窗口
cmd+o 打开
cmd+s 保存
cmd+shift+s 另存为
cmd+p 打印 print
cmd+w 关闭
cmd+q quit
cmd+a select all
cmd+i show info
cmd+n create a new folder
cmd+f search
cmd+c copy
cmd+v paste
cmd+delete 删除选中文件
cmd+shift+delete 清空回收站
cmd+= 放大
cmd+- 缩小
cmd+t 新建选项卡
cmd+r 刷新
cmd+shift+3 截取整个屏幕
cmd+shift+4 截取选择区域
cmd+shift+4+SPACE 截取选择窗口
cmd+ 鼠标点击 -> 选中不连续文件
control+ 鼠标点击 -> 相当于 win 中右键点击
fn+left home
fn+right end
fn+up pageup
fn+down pagedown
触摸板手势:

点击
单指点击 - 单击
单指滑动 - 滑动鼠标光标
双指点击 - 相当于 Windows 的鼠标右键
三指点击 - 划词查找

​
滑动与缩放
双指上下滑动 - 滚动
双指缩放 - 与 Android 上图片缩放一致
双指双击 - 只能缩放
双指旋转 - 旋转
双指左右滑动 - 应用内切换网页
双指头从右往左
三指头左右滑动 - 全屏幕 App 切换
三指拖动 - 扔掉鼠标必备 (谢评论区提醒)
大拇指和食中无名缩放 - launchpad

​

open

open 命令用于打开文件、目录或执行程序。就等同于在命令行模式下,重复图形界面“双击”的动作。例如这个命令与在 Finder 中双击 Safari 是一样的:

open /Applications/Safari.app/

如果 open 一个文件,则会使用关联的程序打开之。例如 open screenshot.png 会在 Preview 中查看图片。

可以使用 -a 选项要求自行选择打开的程序,或使用 -e 强制在 TextEdit 中编辑此文件。

open 一个目录会在 Finder 窗口中打开此目录。一个很有用的技巧是 open . 打开当前目录。

Finder 和终端的交互是双向的——把文件从 Finder 中拖入终端,就等同于把文件的完整路径粘贴到命令行中。

pbcopy 和 pbpaste

这两个工具可以打通命令行和剪贴板。当然用鼠标操作复制粘贴也可以——但这两个工具的真正威力,发挥在将其用作Unix工具的时候。意思就是说:可以将这两个工具用作管道、IO重定向以及和其他命令的整合。例如:

ls ~ | pbcopy
可以将主目录的文件列表复制到剪贴板。

也可以把任意文件的内容读入剪贴板:

pbcopy < blogpost.txt
做点更疯狂的尝试:获取最新 Google 纪念徽标(doodle)的 URL 并复制到剪贴板:

curl http://www.google.com/doodles#oodles/archive | grep -A5 'latest-doodle on' | grep 'img src' | sed s/.*'<img src="\/\/'/''/ | sed s/'" alt=".*'/''/ | pbcopy

使用管道语法配合 pbcopy 工具可以简单的抓取命令的输出,而不必向上滚动翻阅终端窗口。可以用于和他人分享命令行的标准和错误输出。 pbcopy 和 pbpaste 也可以用于自动化或加速执行一些事情。例如把一些邮件的主题存为任务列表,就可以先从 Mail.app 中复制主题,再运行:

pbpaste >> tasklist.txt

mdfind

许多 Linux 用户都发现 Linux 下查找文件的方法在 OS X 上不好用。当然经典的 Unix find 命令总是可以,但既然 OS X 有杀手级搜索工具 Spotlight ,为什么不在命令行上也使用一下呢?

这就是mdfind命令了。 Spotlight 能做的查找, mdfind 也能做。包括搜索文件的内容和元数据(metadata)。

mdfind还提供更多的搜索选项。例如-onlyin选项可以约束搜索范围为一个目录:

mdfind -onlyin ~/Documents essay
mdfind 的索引数据库在后台自动更新,不过你也可以使用 mdutil 工具诊断数据库的问题,诊断 mdfind 的问题也等同于诊断 Spotlight 。如果 Spotlight 的工作不正确,mdutil -E命令可以强制重建索引数据库。也可以用 mdutil -i 彻底关闭文件索引。

screencapture

screencapture 命令可以截图。和 Grab.app 与 cmd + shift + 3 或 cmd + shift + 4 热键相似,但更加的灵活。

抓取包含鼠标光标的全屏幕,并以 image.png 插入到新邮件的附件中:

screencapture -C -M image.png
用鼠标选择抓取窗口(及阴影)并复制到剪贴板:

screencapture -c -W
延时10秒后抓屏,并在Preview中打开之:

screencapture -T 10 -P image.png
用鼠标截取一个矩形区域,抓取后存为pdf文件:

screencapture -s -t pdf image.pdf
更多用法请参阅 screencapture –help 。

launchctl

launchctl 管理 OS X 的启动脚本,控制启动计算机时需要开启的服务。也可以设置定时执行特定任务的脚本,就像 Linux cron 一样。

例如,开机时自动启动 Apache 服务器:

sudo launchctl load -w /System/Library/LaunchDaemons/org.apache.httpd.plist

运行 launchctl list 显示当前的启动脚本。 sudo launchctl unload [path/to/script] 停止正在运行的启动脚本,再加上 -w 选项即可去除开机启动。用这个方法可以一次去除 Adobe 或 Microsoft Office 所附带的所有“自动更新”后台程序。

Launchd 脚本存储在以下位置:

~/Library/LaunchAgents
/Library/LaunchAgents
/Library/LaunchDaemons
/System/Library/LaunchAgents
/System/Library/LaunchDaemons

say

say 是一个文本转语音(TTS)的有趣的工具,引擎和 OS X 使用的一样也是 VoiceOver 。如果不加其他选项,则会简单的语音朗读你给定的字符串:

say “Never trust a computer you can’t lift.”
用-f选项朗读特定文本文件,-o选项将朗读结果存为音频文件而不是播放:
say -f mynovel.txt -o myaudiobook.aiff
say 命令可以用于在脚本中播放警告或提示。例如你可以设置 Automator 或 Hazel 脚本处理文件,并在任务完成时用 say 命令语音提示。

最好玩(不过也负罪感十足)的用法是:通过 SSH 连接到朋友或同事的计算机,然后用 say 命令给他们一个大大大惊喜……

可以在系统设置 (System Preferences) 的字典和语音 (Dictation & Speech) 选项中调整系统的语音选项甚至是语音的语言。

diskutil

diskutil 是 OS X 磁盘工具应用的命令行版。既可以完成图形界面应用的所有任务,也可以做一些全盘填0、全盘填随机数等额外的任务。先使用 diskutil list 查看所有磁盘的列表和所在路径,然后对特定的磁盘执行命令。

警告:不正确使用 diskutil 可能意外的破坏磁盘数据。请小心。

brew

Homebrew 程序提供的 brew ,严格来讲不是一个 OS X 的原生命令,但任何一个 OS X 的专业用户都不会错过它。“ OS X 缺少的包管理器”这个评价是恰如其分的。如果你曾经在 Linux 上使用过 apt-get (或其他包管理器——译者注),你就会发现 Homebrew 基本上是一样的。

使用 brew 可以简单的获取数千种开源工具和函数库。例如 brew install imagemagick 就可以安装 ImageMagick (几乎可以处理任何图像问题,转换任何格式的图像工具), brew install node 可以安装 Node.js (当前大热的服务器端 JavaScript 编程工具)。

也可以通过 Homebrew 做有趣的事情: brew install archey 会安装 Archey (在启动命令行时显示苹果 LOGO 和计算机硬件参数的小工具)。

Homebrew 能安装的工具数量庞大,并且一直保持更新。Homebrew 最棒的一点是:所有的文件都被约束在 /usr/local/ 一个位置之下。也就是说可以通过 Homebrew 安装新版软件的同时,保持系统内置的依赖库或其他软件不变。同时如果想彻底删除 Homebrew ,也变得非常简单。

(注:删除 Homebrew 最好还是不要直接删除 /usr/local/ 。应当用这个卸载脚本点击预览。)

#!/bin/sh
# Just copy and paste the lines below (all at once, it won't work line by line!)
# MAKE SURE YOU ARE HAPPY WITH WHAT IT DOES FIRST! THERE IS NO WARRANTY!

function abort {
  echo "$1"
  exit 1
}

set -e

/usr/bin/which -s git || abort "brew install git first!"
test -d /usr/local/.git || abort "brew update first!"

cd `brew --prefix`
git checkout master
git ls-files -z | pbcopy
rm -rf Cellar
bin/brew prune
pbpaste | xargs -0 rm
rm -r Library/Homebrew Library/Aliases Library/Formula Library/Contributions
test -d Library/LinkedKegs && rm -r Library/LinkedKegs
rmdir -p bin Library share/man/man1 2> /dev/null
rm -rf .git
rm -rf ~/Library/Caches/Homebrew
rm -rf ~/Library/Logs/Homebrew
rm -rf /Library/Caches/Homebrew    

elk+redis

发表于 2018-03-18 | 分类于 web | 阅读次数:
字数统计: 235 | 阅读时长 ≈ 1

对常见的elk工具进行总结

cat /etc/issue # 检查系统版本
java -version #


wget -qO - https://packages.elastic.co/GPG-KEY-elasticsearch | sudo apt-key add -
echo "deb https://packages.elastic.co/elasticsearch/2.x/debian stable main" | sudo tee -a /etc/apt/sources.list.d/elasticsearch-2.x.list
sudo apt-get update
sudo apt-get install elasticsearch -y
sudo service elasticsearch start
echo "deb https://packages.elastic.co/logstash/2.3/debian stable main" | sudo tee -a /etc/apt/sources.list
sudo apt-get install logstash -y
sudo service logstash start
echo "deb http://packages.elastic.co/kibana/4.5/debian stable main" | sudo tee -a /etc/apt/sources.list
sudo apt-get install kibana -y 
sudo service kibana start

sudo service nginx start

# nginx 的配置文件位于 /etc/nginx/sites-available/default

# 添加 access_log /home/shiyanlou/Code/elk/access.log;

接下来是具体的配置文件

# /etc/logstash/conf.d/logstash-shipper.conf

input {
  stdin {}  
  file {
    path => "~/access.log"
    start_position => beginning
    codec =>  multiline {
      'negate' => true
      'pattern' => '^\d'
      'what' => 'previous'
    }
  }
}
output {
    stdout {
        codec => rubydebug
    }
    elasticsearch {
        hosts=>["localhost:9200"]
        index=>"logstash-%{+YYYY.MM.dd}"
    }
}    
1…899091…109
John Cheung

John Cheung

improve your python skills

543 日志
33 分类
45 标签
RSS
GitHub Email
© 2020 John Cheung
本站访客数:
|
主题 — NexT.Pisces v5.1.4
博客全站共226.3k字