域名IP主动验证(一)
功能:主动验证给定的域名、IP对是否真正的关联
思路:
1、一开始通过修改hosts文件,把待验证的域名、IP对添加到文件里,然后用wget尝试访问,再恢复hosts文件重新验证下一对
2、后来了解到curl命令可以带参数的形式指定访问域名的解析IP,于是改用curl验证。但是要在防火墙上关闭DNS服务,要不然会主动请求外网的DNS服务。
主动验证的脚本如下
#curl www.google.com -L -i --resolve www.google.com:80:123.34.35.41 -o index.html curl $2 -L -i --resolve $2:$1 -o index.html if [ ! -f "index.html" ]; then echo false else echo true fi if [ -f "index.html" ]; then rm index.html fi
参数意义:
-L 允许重定向后继续访问重定向的URL
-i 输出返回的http头部
-o 将输出信息输出到指定文件里
--resolve 指定待访问域名的解析IP,注如果解析IP不对,curl会去尝试访问外网的DNS服务器来获得真正的IP,所以个人觉得应该将程序部署在qiang内
读输入文件调用shell脚本的Java程序
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.text.SimpleDateFormat; import java.util.Date; import java.util.ResourceBundle; import org.apache.log4j.Logger; /* * Date:2017-09-30 * Author:glt * */ public class RunShell { static Logger log = Logger.getLogger(RunShell.class); public static void main(String[] args){ ResourceBundle config = ResourceBundle.getBundle("filePath"); String inputPath = config.getString("inputPath"); String outputPath = config.getString("outputPath"); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); String today = sdf.format(new Date()); File input = new File(inputPath + today + "-validating.txt"); File output = new File(outputPath + today + "-validated.txt"); BufferedReader br = null; try { br = new BufferedReader(new FileReader(input)); } catch (IOException e1) { e1.printStackTrace(); } BufferedWriter bw = null; try { bw = new BufferedWriter(new FileWriter(output, true)); } catch (IOException e1) { e1.printStackTrace(); } String line = null; try { while((line = br.readLine()) != null){ String[] fields = line.split("\t"); long seq = Long.parseLong(fields[0]); String ip = fields[1]; String domain = fields[2]; String shpath = "./addHosts.sh " + ip + " " + domain; log.info(shpath); Process ps = Runtime.getRuntime().exec(shpath); ps.waitFor(); BufferedReader console = new BufferedReader(new InputStreamReader(ps.getInputStream())); StringBuffer sb = new StringBuffer(); String consoleLine = null; while ((consoleLine = console.readLine()) != null) { sb.append(consoleLine).append("\n"); } console.close(); String result = sb.toString(); log.info(seq + "\t" + result); if(result.contains("false")){ bw.write(seq + "\t" + ip + "\t" + domain + "\t-1\n"); }else{ bw.write(seq + "\t" + ip + "\t" + domain + "\t1\n"); } bw.flush(); } br.close(); bw.close(); }catch (Exception e) { e.printStackTrace(); } } }
关闭DNS服务
sudo iptables -A OUTPUT -p tcp --dport 53 -j DROP sudo iptables -A OUTPUT -p udp --dport 53 -j DROP
恢复DNS服务
ps:后面会讲一讲为什么这种方法能够验证域名-IP对
参考:http://www.ruanyifeng.com/blog/2011/09/curl.html
http://www.cnblogs.com/lihuobao/p/6434341.html
https://yq.aliyun.com/articles/40772
http://www.cnblogs.com/grimm/p/5362096.html
http://www.linuxidc.com/Linux/2016-09/134941.htm