---
title: "Ubuntu linux下保存dns查询记录/缓存到hosts实现网络加速"
author: "vfate_linux"
date: "2014-07-06T11:54:18Z"
tags: []
categories: ["互联网"]
slug: "ubuntu-linux-dns-hosts"
draft: false
lastmod: "2014-07-06T14:34:25Z"
id: 2088708
url: "https://govfate.iteye.com/blog/2088708"
---

主要目的是网络加速,因为"伟大"的防火墙要对所有的dns查询进行监控检查过滤丢弃...必然导致缓慢的dns查询... 尤其是国外的网站...慢死...

思路如下
1.通过tcpdump命令抓取所有dns查询的53端口udp的数据包

```shell
sudo tcpdump -lvi any 'udp port 53' |tee  dns-record.log
```

-lvi中 -l对终端更友好 -v是详细的包信息 -i是网卡 any代表所有的网卡数据包
'udp port 53'是表达式代表抓取udp包仅仅包括53端口,dns查询的默认端口
当然你要刷新页面才会出现dns查询的udp包
2.分析过滤具体的dns记录

```shell
grep ' A ' dns-record.log |sed -e's/.\+\/[0-9] //g' -e's/\. .*A/ /g' |awk '{print $2" "$1" #tcpdump-hosts"}' 
```

其中' A '代表过来ipv4的dns查询结果 假如你是ivp6环境就要改成' AAAA '
#tcpdump-hosts是为了方便修改删除添加的注释,下面会用到

可以把tcpdump的dns记录单独保存下来:

```shell
grep ' A ' dns-record.log |sed -e's/.\+\/[0-9] //g' -e's/\. .*A/ /g' |awk '{print $2" "$1" #tcpdump-hosts"}' |sort |uniq |tee -a mydns-hosts
```

sort 和uniq是排序去掉重复的dns记录

3.最后把mydns-hosts记录导入到/etc/hosts

```shell
cat mydns-hosts |sudo tee -a /etc/hosts
```

假如你想删除tcpdump查询到的dns非常简单

```shell
sudo sed -i '/#tcpdump-hosts/ d' /etc/hosts
```

这就就不会影响到你自己以前添加的hosts了

重要说明:/etc/hosts文件中有多个重复多个host的时候 前面的优先级高,后面添加了也是白加...要删除前面的或者添加到/etc/hosts的第一行
例如
```shell
sudo sed -i '1 i 192.30.252.128 github.com' /etc/hosts
```

网站的域名和ip不是永远不变的,dns改变的时候你需要删除hosts的dns如下快速删除:
比如删除github.com

```shell
sudo sed -i '/ github.com/ d' /etc/hosts
```

当然之后你要清除浏览器的dns缓存,ubuntu linux上直接重启网络即可sudo service network-manager restart
或许你需要配合dnscrypt,把dns结果都加入hosts将大大改善dnscrypt的压力和速度

后记,假如你是android手机,也是可以这样来做的,请自行谷歌andorid tcpdump安装方法.之后:
电脑上执行
```shell
echo "su -c 'tcpdump -i any -p -s 0 -w /sdcard/udp-capture.pcap udp port 5'" >> caputure.sh
adb push caputure.sh /sdcard/
```

手机终端执行
```shell
cd /sdcard/
sh caputure.sh
```


运行了几个小时或者一天后把udp-capture.pcap文件复制到电脑
电脑上执行

```shell
adb pull /sdcard/udp-capture.pcap .
tcpdump -i any -lvvv -r udp-capture.pcap |tee andorid-dns.log 
```

稍等一会就能看到当天抓取的的udp包具体信息

后面就是过滤获取具体的dns结果和上面的类似了....

参考:<http://unix.stackexchange.com/questions/27246/how-to-gather-dns-a-record-requests>
<http://www.kandroid.org/online-pdk/guide/tcpdump.html#other>