设置域名

当我们在浏览器上输入网址时,首先是访问本地文件是否存在域名所对应的ip地址,如果找到就直接放回ip地址,没有找到就去域名服务器找相应ip地址。

import re
import sys


# 从命令行获取ip地址
if len(sys.argv) < 3:
    raise Exception('please input => python3 run.py 127.0.0.1 domain')

string_host = sys.argv[1]
pattern = "(?:(?:1[0-9][0-9]\.)|(?:2[0-4][0-9]\.)|(?:25[0-5]\.)|(?:[1-9][0-9]\.)|(?:[0-9]\.)){3}" \
          "(?:(?:1[0-9][0-9])|(?:2[0-4][0-9])|(?:25[0-5])|(?:[1-9][0-9])|(?:[0-9]))"

ip_pattern = re.compile(pattern)
host = ip_pattern.findall(string_host)[0]
# 判断ip地址是否正确
assert host,'ip error'

# 拼接域名
try:
    domain = ''.join(sys.argv[2:])
except IndexError:
    raise Exception('please input => python3 run.py 127.0.0.1 domain')

try:
    with open('C:\Windows\System32\drivers\etc\hosts','a') as f:
        f.write('\t{}\t{}\r\n'.format(host,domain))
except OSError as e:
    err = str(e)
    raise Exception(err)

 

posted @ 2018-09-21 21:44  努力吧,少年  阅读(345)  评论(0编辑  收藏  举报