在chromebook上安装dns server

操作步骤相对比较多,记录总结分享一下

1、找相关的实现代码

https://github.com/samuelcolvin/dnserver/blob/master/dnserver.py

#!/usr/bin/env python3.6
import json
import logging
import os
import signal
from datetime import datetime
from pathlib import Path
from textwrap import wrap
from time import sleep

from dnslib import DNSLabel, QTYPE, RR, dns
from dnslib.proxy import ProxyResolver
from dnslib.server import DNSServer

SERIAL_NO = int((datetime.utcnow() - datetime(1970, 1, 1)).total_seconds())

handler = logging.StreamHandler()
handler.setLevel(logging.INFO)
handler.setFormatter(logging.Formatter('%(asctime)s: %(message)s', datefmt='%H:%M:%S'))

logger = logging.getLogger(__name__)
logger.addHandler(handler)
logger.setLevel(logging.INFO)

TYPE_LOOKUP = {
    'A': (dns.A, QTYPE.A),
    'AAAA': (dns.AAAA, QTYPE.AAAA),
    'CAA': (dns.CAA, QTYPE.CAA),
    'CNAME': (dns.CNAME, QTYPE.CNAME),
    'DNSKEY': (dns.DNSKEY, QTYPE.DNSKEY),
    'MX': (dns.MX, QTYPE.MX),
    'NAPTR': (dns.NAPTR, QTYPE.NAPTR),
    'NS': (dns.NS, QTYPE.NS),
    'PTR': (dns.PTR, QTYPE.PTR),
    'RRSIG': (dns.RRSIG, QTYPE.RRSIG),
    'SOA': (dns.SOA, QTYPE.SOA),
    'SRV': (dns.SRV, QTYPE.SRV),
    'TXT': (dns.TXT, QTYPE.TXT),
    'SPF': (dns.TXT, QTYPE.TXT),
}


class Record:
    def __init__(self, rname, rtype, args):
        self._rname = DNSLabel(rname)

        rd_cls, self._rtype = TYPE_LOOKUP[rtype]

        if self._rtype == QTYPE.SOA and len(args) == 2:
            # add sensible times to SOA
            args += (SERIAL_NO, 3600, 3600 * 3, 3600 * 24, 3600),

        if self._rtype == QTYPE.TXT and len(args) == 1 and isinstance(args[0], str) and len(args[0]) > 255:
            # wrap long TXT records as per dnslib's docs.
            args = wrap(args[0], 255),

        if self._rtype in (QTYPE.NS, QTYPE.SOA):
            ttl = 3600 * 24
        else:
            ttl = 300

        self.rr = RR(
            rname=self._rname,
            rtype=self._rtype,
            rdata=rd_cls(*args),
            ttl=ttl,
        )

    def match(self, q):
        return q.qname == self._rname and (q.qtype == QTYPE.ANY or q.qtype == self._rtype)

    def sub_match(self, q):
        return self._rtype == QTYPE.SOA and q.qname.matchSuffix(self._rname)

    def __str__(self):
        return str(self.rr)


class Resolver(ProxyResolver):
    def __init__(self, upstream, zone_file):
        super().__init__(upstream, 53, 5)
        self.records = self.load_zones(zone_file)

    def zone_lines(self):
        current_line = ''
        for line in zone_file.open():
            if line.startswith('#'):
                continue
            line = line.rstrip('\r\n\t ')
            if not line.startswith(' ') and current_line:
                yield current_line
                current_line = ''
            current_line += line.lstrip('\r\n\t ')
        if current_line:
            yield current_line

    def load_zones(self, zone_file):
        assert zone_file.exists(), f'zone files "{zone_file}" does not exist'
        logger.info('loading zone file "%s":', zone_file)
        zones = []
        for line in self.zone_lines():
            try:
                rname, rtype, args_ = line.split(maxsplit=2)

                if args_.startswith('['):
                    args = tuple(json.loads(args_))
                else:
                    args = (args_,)
                record = Record(rname, rtype, args)
                zones.append(record)
                logger.info(' %2d: %s', len(zones), record)
            except Exception as e:
                raise RuntimeError(f'Error processing line ({e.__class__.__name__}: {e}) "{line.strip()}"') from e
        logger.info('%d zone resource records generated from zone file', len(zones))
        return zones

    def resolve(self, request, handler):
        type_name = QTYPE[request.q.qtype]
        reply = request.reply()
        for record in self.records:
            if record.match(request.q):
                reply.add_answer(record.rr)

        if reply.rr:
            logger.info('found zone for %s[%s], %d replies', request.q.qname, type_name, len(reply.rr))
            return reply

        # no direct zone so look for an SOA record for a higher level zone
        for record in self.records:
            if record.sub_match(request.q):
                reply.add_answer(record.rr)

        if reply.rr:
            logger.info('found higher level SOA resource for %s[%s]', request.q.qname, type_name)
            return reply

        logger.info('no local zone found, proxying %s[%s]', request.q.qname, type_name)
        return super().resolve(request, handler)


def handle_sig(signum, frame):
    logger.info('pid=%d, got signal: %s, stopping...', os.getpid(), signal.Signals(signum).name)
    exit(0)


if __name__ == '__main__':
    signal.signal(signal.SIGTERM, handle_sig)

    port = int(os.getenv('PORT', 53))
    upstream = os.getenv('UPSTREAM', '8.8.8.8')
    zone_file = Path(os.getenv('ZONE_FILE', 'zone'))
    resolver = Resolver(upstream, zone_file)
    udp_server = DNSServer(resolver, port=port)
    tcp_server = DNSServer(resolver, port=port, tcp=True)

    logger.info('starting DNS server on port %d, upstream DNS server "%s"', port, upstream)
    udp_server.start_thread()
    tcp_server.start_thread()

    try:
        while udp_server.isAlive():
            sleep(1)
    except KeyboardInterrupt:
        pass

2、安装必要的依赖包

pip install dnslib

3、给普通用户打开53端口的权限

参考 http://blog.useasp.net/archive/2015/07/09/non-root-user-application-bind-to-ports-less-than-1024-without-root-access.aspx

chronos@localhost ~/export $ which python
/usr/local/anaconda3/bin/python
chronos@localhost ~/export $ sudo chown root.root /usr/local/anaconda3/bin/python
chronos@localhost ~/export $ sudo chmod u+s /usr/local/anaconda3/bin/python

4、编辑zone配置文件

# this is an example zones file
# each line with parts split on white space are considered thus:
#     1:               the host
#     2:               the record type
#     everything else: either a single string or json list if it starts with "["
#     lines starting with white space are striped of white space (including "\n")
#     and added to the previous line
example.com  A       1.2.3.4
example.com  CNAME   whatever.com
example.com  MX      ["whatever.com.", 5]
example.com  MX      ["mx2.whatever.com.", 10]
example.com  MX      ["mx3.whatever.com.", 20]
example.com  NS      ns1.whatever.com.
example.com  NS      ns2.whatever.com.
example.com  TXT     hello this is some text
example.com  SOA     ["ns1.example.com", "dns.example.com"]
# because the next record exceeds 255 in length dnserver will automatically
# split it into a multipart record, the new lines here have no effect on that
testing.com  TXT    one long value: IICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAg
    FWZUed1qcBziAsqZ/LzT2ASxJYuJ5sko1CzWFhFuxiluNnwKjSknSjanyYnm0vro4dhAtyiQ7O
    PVROOaNy9Iyklvu91KuhbYi6l80Rrdnuq1yjM//xjaB6DGx8+m1ENML8PEdSFbKQbh9akm2bkN
    w5DC5a8Slp7j+eEVHkgV3k3oRhkPcrKyoPVvniDNH+Ln7DnSGC+Aw5Sp+fhu5aZmoODhhX5/1m
    ANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEA26JaFWZUed1qcBziAsqZ/LzTF2ASxJYuJ5sk

5、执行脚本

python dns-server.py

6、修改dns服务器地址

打开设置-网络-自定义域名服务器修改为 127.0.0.1

7、测试

chronos@localhost / $ ping example.com
PING example.com (1.2.3.4) 56(84) bytes of data.

 

 

190309补充:直接修改/etc/host的方法

sudo /usr/share/vboot/bin/make_dev_ssd.sh --remove_rootfs_verification

重启后可以修改/etc/hosts

转载于:https://my.oschina.net/ois/blog/1813252

### 回答1: 要在Chromebook安装Linux,您需要先启用Chromebook上的开发者模式。然后,您可以通过Crouton或Chromebrew等工具来安装Linux。安装Linux后,您可以使用Linux应用程序和命令行工具来扩展Chromebook的功能。但请注意,安装Linux可能会影响Chromebook的安全性和稳定性,因此请谨慎操作。 ### 回答2: Chromebook是一种基于Chrome OS的操作系统的笔记本电脑。虽然Chrome OS可以运行许多应用程序,但有些用户需要更广泛的功能,例如使用Linux的命令行和软件。因此,可以在Chromebook安装Linux以满足这些需求。 首先,要安装Linux,您需要启用Chromebook上的“开发者模式”。要进入开发者模式,首先,请备份您的所有文件并确保Chromebook已连接到电源。然后,按住Esc + F3(Chromebook上的切换功能键)+ 电源按钮,然后释放所有这些键。Chromebook将进入恢复模式。 在恢复模式下,您需要按Ctrl + D,然后按Enter键。您将会收到一条警告,提示您确信要进入开发者模式。按Enter再次确认。Chromebook将自行重启并进入开发者模式。 现在您有了开发者模式,需要打开Chromebook上的“Linux(Beta)”功能。前往Chromebook设置并选择“设备”>“Linux Beta”,随后按照提示启用它。系统将自动下载并安装Linux虚拟机容器。 与此同时,建议您下载和安装一个名为“Crouton”的Linux发行版,它与Chrome OS安装在同一个虚拟机容器中,并为您提供享有Linux游戏和软件的命令行界面。该软件也能帮助您在Chromebook上快速安装Linux发行版。 最后,为了使用Linux,您需要打开终端并输入以下命令:sudo startgnome 或 sudo startxfce4。这将启动您安装的GNOME或Xfce桌面环境。现在,您可以使用Linux命令行和应用程序,您可以在Chromebook上进行更广泛的任务! 总之,将Linux安装Chromebook上是一个相对简单的过程,需要您注意一些关键步骤。一旦您完成了所有步骤,您将能够在Chromebook上使用Linux的命令行和应用程序,满足您更广泛的需求。 ### 回答3: 随着Chromebook在市场上的快速普及,越来越多的用户想要在Chromebook上使用Linux。Chromebook本身是一种基于Google Chrome浏览器的操作系统,但是安装Linux可以为用户提供更多功能和灵活性。 首先需要说明的是,Chromebook是基于Google Chrome OS的,这意味着它并不是一个传统意义上的计算机。Chromebook的本质是一款浏览器,因此它并不支持像Windows或Mac OS那样的原生程序安装。这就是为什么在Chromebook安装Linux会比在其他设备上更加复杂的原因。 但是,Chromebook作为一种基于Linux内核的操作系统,是可以使用Linux的。Google为Chromebook提供了一个称为“开发人员模式”的选项,用户可以在这个模式下安装和运行Linux应用程序。以下是步骤: 步骤一:打开“开发人员模式” - 这个选项可以通过按下“ESC + 刷新 + 电源”来打开,这样您就可以进入Chromebook的开发人员模式。 步骤二:下载Crouton - Crouton是一个用于在Chromebook安装Linux的软件。 步骤三:启动Crouton - 打开“终端”并输入以下命令: sudo sh ~/Downloads/crouton -t [desktop environment] [desktop environment]将是您想要安装的桌面环境。例如,如果您想要安装Ubuntu,这将是“xfce”或“unity”之一。 步骤四:等待安装完成 - 安装会需要一些时间。安装完成后,您将可以通过在Chromebook的开发人员模式下切换到Linux环境。 总的来说,Chromebook安装Linux方面略有些复杂,但对于那些想要更多功能和灵活性的用户来说,这是一个值得尝试的方法。如果遵循正确的步骤,安装Linux将为Chromebook带来更多功用。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值