ykutik
-
Posts
13 -
Joined
-
Last visited
Content Type
Profiles
Forums
Gallery
Downloads
Blogs
Events
Posts posted by ykutik
-
-
2 часа назад, ykutik сказал:
Помогите пожалуйста настроить.
Пришлось сбросить роутер до заводских.
В итоге стал перенастраивать DNSCrypt как тут в шапке. До этого уже много лет пользуюсь этим решением.
Но.
Столкнулся с проблемой обновления списка из-за python
~ # opkg install python-base python-urllib3
Unknown package 'python-base'.
Unknown package 'python-urllib3'.Я нашел в депозитарии, что пакет изменился, поставил аналогичные:
# opkg install python3-base
Installing python3-base (3.8.5-2) to root...
Downloading http://bin.entware.net/mipselsf-k3.4/python3-base_3.8.5-2_mipsel-3.4 .ipk
Configuring python3-base.
~ # opkg install python3-urllib3
Installing python3-urllib3 (1.25.10-1) to root...
Downloading http://bin.entware.net/mipselsf-k3.4/python3-urllib3_1.25.10-1_mipse l-3.4.ipk
Installing libbz2 (1.0.8-1) to root...
Downloading http://bin.entware.net/mipselsf-k3.4/libbz2_1.0.8-1_mipsel-3.4.ipk
Installing libtirpc (1.2.6-2) to root...Но скрип обновления, который еще утром отработал ,выдаешь ошибку:
root@Keenetic_Ultra:/opt/etc/cron.daily$ ./generate-blacklist
Traceback (most recent call last):
File "generate-domains-blacklist.py", line 8, in <module>
import urllib2
ModuleNotFoundError: No module named 'urllib2'Что делать?
Скрипт generate-domains-blacklist.py ниже
#! /usr/bin/env python
# run with python generate-domains-blacklist.py > list.txt.tmp && mv -f list.txt.tmp list
import argparse
import re
import sys
import urllib2
def parse_list(content, trusted=False):
rx_comment = re.compile(r'^(#|$)')
rx_inline_comment = re.compile(r'\s*#\s*[a-z0-9-].*$')
rx_u = re.compile(r'^@*\|\|([a-z0-9.-]+[.][a-z]{2,})\^?(\$(popup|third-party))?$')
rx_l = re.compile(r'^([a-z0-9.-]+[.][a-z]{2,})$')
rx_h = re.compile(r'^[0-9]{1,3}[.][0-9]{1,3}[.][0-9]{1,3}[.][0-9]{1,3}\s+([a-z0-9.-]+[.][a-z]{2,})$')
rx_mdl = re.compile(r'^"[^"]+","([a-z0-9.-]+[.][a-z]{2,})",')
rx_b = re.compile(r'^([a-z0-9.-]+[.][a-z]{2,}),.+,[0-9: /-]+,')
rx_dq = re.compile(r'^address=/([a-z0-9.-]+[.][a-z]{2,})/.')
rx_trusted = re.compile(r'^([*a-z0-9.-]+)$')names = set()
rx_set = [rx_u, rx_l, rx_h, rx_mdl, rx_b, rx_dq]
if trusted:
rx_set = [rx_trusted]
for line in content.splitlines():
line = str.lower(str.strip(line))
if rx_comment.match(line):
continue
line = rx_inline_comment.sub('', line)
for rx in rx_set:
matches = rx.match(line)
if not matches:
continue
name = matches.group(1)
names.add(name)
return names
def load_from_url(url):
sys.stderr.write("Loading data from [{}]\n".format(url))
req = urllib2.Request(url)
trusted = False
if req.get_type() == "file":
trusted = True
response = None
try:
response = urllib2.urlopen(req, timeout=int(args.timeout))
except urllib2.URLError as err:
raise Exception("[{}] could not be loaded: {}\n".format(url, err))
if trusted is False and response.getcode() != 200:
raise Exception("[{}] returned HTTP code {}\n".format(url, response.getcode()))
content = response.read()return (content, trusted)
def name_cmp(name):
parts = name.split(".")
parts.reverse()
return str.join(".", parts)
def has_suffix(names, name):
parts = str.split(name, ".")
while parts:
parts = parts[1:]
if str.join(".", parts) in names:
return Truereturn False
def whitelist_from_url(url):
if not url:
return set()
content, trusted = load_from_url(url)return parse_list(content, trusted)
def blacklists_from_config_file(file, whitelist, time_restricted_url, ignore_retrieval_failure):
blacklists = {}
whitelisted_names = set()
all_names = set()
unique_names = set()# Load conf & blacklists
with open(file) as fd:
for line in fd:
line = str.strip(line)
if str.startswith(line, "#") or line == "":
continue
url = line
try:
content, trusted = load_from_url(url)
names = parse_list(content, trusted)
blacklists[url] = names
all_names |= names
except Exception as e:
sys.stderr.write(e.message)
if not ignore_retrieval_failure:
exit(1)# Time-based blacklist
if time_restricted_url and not re.match(r'^[a-z0-9]+:', time_restricted_url):
time_restricted_url = "file:" + time_restricted_urlif time_restricted_url:
time_restricted_content, trusted = load_from_url(time_restricted_url)
time_restricted_names = parse_list(time_restricted_content)if time_restricted_names:
print("########## Time-based blacklist ##########\n")
for name in time_restricted_names:
print(name)# Time restricted names should be whitelisted, or they could be always blocked
whitelisted_names |= time_restricted_names# Whitelist
if whitelist and not re.match(r'^[a-z0-9]+:', whitelist):
whitelist = "file:" + whitelistwhitelisted_names |= whitelist_from_url(whitelist)
# Process blacklists
for url, names in blacklists.items():
print("\n\n########## Blacklist from {} ##########\n".format(url))
ignored, whitelisted = 0, 0
list_names = list()
for name in names:
if has_suffix(all_names, name) or name in unique_names:
ignored = ignored + 1
elif has_suffix(whitelisted_names, name) or name in whitelisted_names:
whitelisted = whitelisted + 1
else:
list_names.append(name)
unique_names.add(name)list_names.sort(key=name_cmp)
if ignored:
print("# Ignored duplicates: {}\n".format(ignored))
if whitelisted:
print("# Ignored entries due to the whitelist: {}\n".format(whitelisted))
for name in list_names:
print(name)
argp = argparse.ArgumentParser(description="Create a unified blacklist from a set of local and remote files")
argp.add_argument("-c", "--config", default="domains-blacklist.conf",
help="file containing blacklist sources")
argp.add_argument("-w", "--whitelist", default="domains-whitelist.txt",
help="file containing a set of names to exclude from the blacklist")
argp.add_argument("-r", "--time-restricted", default="domains-time-restricted.txt",
help="file containing a set of names to be time restricted")
argp.add_argument("-i", "--ignore-retrieval-failure", action='store_true',
help="generate list even if some urls couldn't be retrieved")
argp.add_argument("-t", "--timeout", default=30,
help="URL open timeout")
args = argp.parse_args()conf = args.config
whitelist = args.whitelist
time_restricted = args.time_restricted
ignore_retrieval_failure = args.ignore_retrieval_failureblacklists_from_config_file(conf, whitelist, time_restricted, ignore_retrieval_failure)
Вообщем изменил ситакис согласно рекомендациям
import urllib.request req=urllib.request.Request(api_url,binary_data,header) f=urllib.request.urlopen(req)
Но теперь совсем скрип не работает
Скрытый текст#! /usr/bin/env python
# run with python generate-domains-blacklist.py > list.txt.tmp && mv -f list.txt.tmp list
import argparse
import re
import sys
import urllib.request
def parse_list(content, trusted=False):
rx_comment = re.compile(r'^(#|$)')
rx_inline_comment = re.compile(r'\s*#\s*[a-z0-9-].*$')
rx_u = re.compile(r'^@*\|\|([a-z0-9.-]+[.][a-z]{2,})\^?(\$(popup|third-party))?$')
rx_l = re.compile(r'^([a-z0-9.-]+[.][a-z]{2,})$')
rx_h = re.compile(r'^[0-9]{1,3}[.][0-9]{1,3}[.][0-9]{1,3}[.][0-9]{1,3}\s+([a-z0-9.-]+[.][a-z]{2,})$')
rx_mdl = re.compile(r'^"[^"]+","([a-z0-9.-]+[.][a-z]{2,})",')
rx_b = re.compile(r'^([a-z0-9.-]+[.][a-z]{2,}),.+,[0-9: /-]+,')
rx_dq = re.compile(r'^address=/([a-z0-9.-]+[.][a-z]{2,})/.')
rx_trusted = re.compile(r'^([*a-z0-9.-]+)$')names = set()
rx_set = [rx_u, rx_l, rx_h, rx_mdl, rx_b, rx_dq]
if trusted:
rx_set = [rx_trusted]
for line in content.splitlines():
line = str.lower(str.strip(line))
if rx_comment.match(line):
continue
line = rx_inline_comment.sub('', line)
for rx in rx_set:
matches = rx.match(line)
if not matches:
continue
name = matches.group(1)
names.add(name)
return names
def load_from_url(url):
sys.stderr.write("Loading data from [{}]\n".format(url))
req = urllib.request.Request(url)
trusted = False
if req.get_type() == "file":
trusted = True
response = None
try:
response = urllib.request.urlopen(req, timeout=int(args.timeout))
except urllib.request.URLError as err:
raise Exception("[{}] could not be loaded: {}\n".format(url, err))
if trusted is False and response.getcode() != 200:
raise Exception("[{}] returned HTTP code {}\n".format(url, response.getcode()))
content = response.read()return (content, trusted)
def name_cmp(name):
parts = name.split(".")
parts.reverse()
return str.join(".", parts)
def has_suffix(names, name):
parts = str.split(name, ".")
while parts:
parts = parts[1:]
if str.join(".", parts) in names:
return Truereturn False
def whitelist_from_url(url):
if not url:
return set()
content, trusted = load_from_url(url)return parse_list(content, trusted)
def blacklists_from_config_file(file, whitelist, time_restricted_url, ignore_retrieval_failure):
blacklists = {}
whitelisted_names = set()
all_names = set()
unique_names = set()# Load conf & blacklists
with open(file) as fd:
for line in fd:
line = str.strip(line)
if str.startswith(line, "#") or line == "":
continue
url = line
try:
content, trusted = load_from_url(url)
names = parse_list(content, trusted)
blacklists[url] = names
all_names |= names
except Exception as e:
sys.stderr.write(e.message)
if not ignore_retrieval_failure:
exit(1)# Time-based blacklist
if time_restricted_url and not re.match(r'^[a-z0-9]+:', time_restricted_url):
time_restricted_url = "file:" + time_restricted_urlif time_restricted_url:
time_restricted_content, trusted = load_from_url(time_restricted_url)
time_restricted_names = parse_list(time_restricted_content)if time_restricted_names:
print("########## Time-based blacklist ##########\n")
for name in time_restricted_names:
print(name)# Time restricted names should be whitelisted, or they could be always blocked
whitelisted_names |= time_restricted_names# Whitelist
if whitelist and not re.match(r'^[a-z0-9]+:', whitelist):
whitelist = "file:" + whitelistwhitelisted_names |= whitelist_from_url(whitelist)
# Process blacklists
for url, names in blacklists.items():
print("\n\n########## Blacklist from {} ##########\n".format(url))
ignored, whitelisted = 0, 0
list_names = list()
for name in names:
if has_suffix(all_names, name) or name in unique_names:
ignored = ignored + 1
elif has_suffix(whitelisted_names, name) or name in whitelisted_names:
whitelisted = whitelisted + 1
else:
list_names.append(name)
unique_names.add(name)list_names.sort(key=name_cmp)
if ignored:
print("# Ignored duplicates: {}\n".format(ignored))
if whitelisted:
print("# Ignored entries due to the whitelist: {}\n".format(whitelisted))
for name in list_names:
print(name)
argp = argparse.ArgumentParser(description="Create a unified blacklist from a set of local and remote files")
argp.add_argument("-c", "--config", default="domains-blacklist.conf",
help="file containing blacklist sources")
argp.add_argument("-w", "--whitelist", default="domains-whitelist.txt",
help="file containing a set of names to exclude from the blacklist")
argp.add_argument("-r", "--time-restricted", default="domains-time-restricted.txt",
help="file containing a set of names to be time restricted")
argp.add_argument("-i", "--ignore-retrieval-failure", action='store_true',
help="generate list even if some urls couldn't be retrieved")
argp.add_argument("-t", "--timeout", default=30,
help="URL open timeout")
args = argp.parse_args()conf = args.config
whitelist = args.whitelist
time_restricted = args.time_restricted
ignore_retrieval_failure = args.ignore_retrieval_failureblacklists_from_config_file(conf, whitelist, time_restricted, ignore_retrieval_failure)
Скрытый текстroot@Keenetic_Ultra:/opt/etc/cron.daily$ ./generate-blacklist
Loading data from []
Traceback (most recent call last):
File "generate-domains-blacklist.py", line 96, in blacklists_from_config_file
content, trusted = load_from_url(url)
File "generate-domains-blacklist.py", line 42, in load_from_url
req = urllib.request.Request(url)
File "/opt/lib/python3.8/urllib/request.py", line 328, in __init__
File "/opt/lib/python3.8/urllib/request.py", line 354, in full_url
File "/opt/lib/python3.8/urllib/request.py", line 383, in _parse
ValueError: unknown url type: '\ufeff'During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "generate-domains-blacklist.py", line 168, in <module>
blacklists_from_config_file(conf, whitelist, time_restricted, ignore_retrieval_failure)
File "generate-domains-blacklist.py", line 101, in blacklists_from_config_file
sys.stderr.write(e.message)
AttributeError: 'ValueError' object has no attribute 'message'Помогите поправить скрипт под нового Pyton'a?
-
Помогите пожалуйста настроить.
Пришлось сбросить роутер до заводских.
В итоге стал перенастраивать DNSCrypt как тут в шапке. До этого уже много лет пользуюсь этим решением.
Но.
Столкнулся с проблемой обновления списка из-за python
Скрытый текст~ # opkg install python-base python-urllib3
Unknown package 'python-base'.
Unknown package 'python-urllib3'.Я нашел в депозитарии, что пакет изменился, поставил аналогичные:
Скрытый текст# opkg install python3-base
Installing python3-base (3.8.5-2) to root...
Downloading http://bin.entware.net/mipselsf-k3.4/python3-base_3.8.5-2_mipsel-3.4 .ipk
Configuring python3-base.
~ # opkg install python3-urllib3
Installing python3-urllib3 (1.25.10-1) to root...
Downloading http://bin.entware.net/mipselsf-k3.4/python3-urllib3_1.25.10-1_mipse l-3.4.ipk
Installing libbz2 (1.0.8-1) to root...
Downloading http://bin.entware.net/mipselsf-k3.4/libbz2_1.0.8-1_mipsel-3.4.ipk
Installing libtirpc (1.2.6-2) to root...Но скрип обновления, который еще утром отработал ,выдаешь ошибку:
Скрытый текстroot@Keenetic_Ultra:/opt/etc/cron.daily$ ./generate-blacklist
Traceback (most recent call last):
File "generate-domains-blacklist.py", line 8, in <module>
import urllib2
ModuleNotFoundError: No module named 'urllib2'Что делать?
Скрипт generate-domains-blacklist.py ниже
Скрытый текст#! /usr/bin/env python
# run with python generate-domains-blacklist.py > list.txt.tmp && mv -f list.txt.tmp list
import argparse
import re
import sys
import urllib2
def parse_list(content, trusted=False):
rx_comment = re.compile(r'^(#|$)')
rx_inline_comment = re.compile(r'\s*#\s*[a-z0-9-].*$')
rx_u = re.compile(r'^@*\|\|([a-z0-9.-]+[.][a-z]{2,})\^?(\$(popup|third-party))?$')
rx_l = re.compile(r'^([a-z0-9.-]+[.][a-z]{2,})$')
rx_h = re.compile(r'^[0-9]{1,3}[.][0-9]{1,3}[.][0-9]{1,3}[.][0-9]{1,3}\s+([a-z0-9.-]+[.][a-z]{2,})$')
rx_mdl = re.compile(r'^"[^"]+","([a-z0-9.-]+[.][a-z]{2,})",')
rx_b = re.compile(r'^([a-z0-9.-]+[.][a-z]{2,}),.+,[0-9: /-]+,')
rx_dq = re.compile(r'^address=/([a-z0-9.-]+[.][a-z]{2,})/.')
rx_trusted = re.compile(r'^([*a-z0-9.-]+)$')names = set()
rx_set = [rx_u, rx_l, rx_h, rx_mdl, rx_b, rx_dq]
if trusted:
rx_set = [rx_trusted]
for line in content.splitlines():
line = str.lower(str.strip(line))
if rx_comment.match(line):
continue
line = rx_inline_comment.sub('', line)
for rx in rx_set:
matches = rx.match(line)
if not matches:
continue
name = matches.group(1)
names.add(name)
return names
def load_from_url(url):
sys.stderr.write("Loading data from [{}]\n".format(url))
req = urllib2.Request(url)
trusted = False
if req.get_type() == "file":
trusted = True
response = None
try:
response = urllib2.urlopen(req, timeout=int(args.timeout))
except urllib2.URLError as err:
raise Exception("[{}] could not be loaded: {}\n".format(url, err))
if trusted is False and response.getcode() != 200:
raise Exception("[{}] returned HTTP code {}\n".format(url, response.getcode()))
content = response.read()return (content, trusted)
def name_cmp(name):
parts = name.split(".")
parts.reverse()
return str.join(".", parts)
def has_suffix(names, name):
parts = str.split(name, ".")
while parts:
parts = parts[1:]
if str.join(".", parts) in names:
return Truereturn False
def whitelist_from_url(url):
if not url:
return set()
content, trusted = load_from_url(url)return parse_list(content, trusted)
def blacklists_from_config_file(file, whitelist, time_restricted_url, ignore_retrieval_failure):
blacklists = {}
whitelisted_names = set()
all_names = set()
unique_names = set()# Load conf & blacklists
with open(file) as fd:
for line in fd:
line = str.strip(line)
if str.startswith(line, "#") or line == "":
continue
url = line
try:
content, trusted = load_from_url(url)
names = parse_list(content, trusted)
blacklists[url] = names
all_names |= names
except Exception as e:
sys.stderr.write(e.message)
if not ignore_retrieval_failure:
exit(1)# Time-based blacklist
if time_restricted_url and not re.match(r'^[a-z0-9]+:', time_restricted_url):
time_restricted_url = "file:" + time_restricted_urlif time_restricted_url:
time_restricted_content, trusted = load_from_url(time_restricted_url)
time_restricted_names = parse_list(time_restricted_content)if time_restricted_names:
print("########## Time-based blacklist ##########\n")
for name in time_restricted_names:
print(name)# Time restricted names should be whitelisted, or they could be always blocked
whitelisted_names |= time_restricted_names# Whitelist
if whitelist and not re.match(r'^[a-z0-9]+:', whitelist):
whitelist = "file:" + whitelistwhitelisted_names |= whitelist_from_url(whitelist)
# Process blacklists
for url, names in blacklists.items():
print("\n\n########## Blacklist from {} ##########\n".format(url))
ignored, whitelisted = 0, 0
list_names = list()
for name in names:
if has_suffix(all_names, name) or name in unique_names:
ignored = ignored + 1
elif has_suffix(whitelisted_names, name) or name in whitelisted_names:
whitelisted = whitelisted + 1
else:
list_names.append(name)
unique_names.add(name)list_names.sort(key=name_cmp)
if ignored:
print("# Ignored duplicates: {}\n".format(ignored))
if whitelisted:
print("# Ignored entries due to the whitelist: {}\n".format(whitelisted))
for name in list_names:
print(name)
argp = argparse.ArgumentParser(description="Create a unified blacklist from a set of local and remote files")
argp.add_argument("-c", "--config", default="domains-blacklist.conf",
help="file containing blacklist sources")
argp.add_argument("-w", "--whitelist", default="domains-whitelist.txt",
help="file containing a set of names to exclude from the blacklist")
argp.add_argument("-r", "--time-restricted", default="domains-time-restricted.txt",
help="file containing a set of names to be time restricted")
argp.add_argument("-i", "--ignore-retrieval-failure", action='store_true',
help="generate list even if some urls couldn't be retrieved")
argp.add_argument("-t", "--timeout", default=30,
help="URL open timeout")
args = argp.parse_args()conf = args.config
whitelist = args.whitelist
time_restricted = args.time_restricted
ignore_retrieval_failure = args.ignore_retrieval_failureblacklists_from_config_file(conf, whitelist, time_restricted, ignore_retrieval_failure)
-
В 05.05.2018 в 12:40, AgentSlash сказал:
Выложу на всякий случай свою обновленную адаптацию файла S01adblock для блокировки по этой инструкции
В оригинале уже кое что не работает + небольшие изменения. Возможно кому-то будет полезно для своих адаптаций.
Доброго дня. Прошу помочь по работе связки dnscrypt-proxy+dnsmasq
Скрытый текстМай 27 15:51:44ndmOpkg::Manager: invalid initrc "/opt/etc/initrc": no such file or directory, trying /opt/etc/init.d/.Май 27 15:51:44ADBlockCollecting hosts to block ads & windows spyingМай 27 15:51:44ndmOpkg::Manager: /opt/etc/init.d/01adblock: ADBlock: Collecting hosts to block ads & windows spying.Май 27 15:51:44ADBlockGenerating a custom windows spying blocker host fileМай 27 15:51:44ndmOpkg::Manager: /opt/etc/init.d/01adblock: ADBlock: Generating a custom windows spying blocker host file.Май 27 15:51:46ndnproxyndnproxy 1.3.0b16 started.Май 27 15:51:46ndnproxyPID file: /var/ndnproxymain.pid.Май 27 15:51:46ndnproxystats. file: /var/ndnproxymain.stat.Май 27 15:51:46minidlnaStarting MiniDLNA version 1.2.1.Май 27 15:51:47minidlnaAdded client [Samsung Series [CDE----------Май 27 15:51:47Май 27 15:51:49ADBlock- Collected 1 hosts from host.0.dws.customМай 27 15:51:49ndmOpkg::Manager: /opt/etc/init.d/01adblock: ADBlock: - Collected 1 hosts from host.0.dws.custom.Май 27 15:51:49ADBlockGenerating host-blocker files using the adblock.urlМай 27 15:51:49ndmOpkg::Manager: /opt/etc/init.d/01adblock: ADBlock: Generating host-blocker files using the adblock.url.Май 27 15:51:50ndmNtp::Client: unable to communicate with "2.pool.ntp.org".Май 27 15:51:50ndmNtp::Client: could not synchronize, waiting...Май 27 15:51:53ADBlock- Collected 0 hosts from host.1.adaway.orgМай 27 15:51:53ndmOpkg::Manager: /opt/etc/init.d/01adblock: ADBlock: - Collected 0 hosts from host.1.adaway.org.Май 27 15:51:53ADBlock- Collected 0 hosts from host.2.Май 27 15:51:53ndmOpkg::Manager: /opt/etc/init.d/01adblock: ADBlock: - Collected 0 hosts from host.2.Май 27 15:51:53ndhcpsDHCPDISCOVER received from ------------Май 27 15:51:53ndhcpsmaking OFFER of 192.------------Май 27 15:51:53ndmkernel: SWNAT bind table clearedМай 27 15:51:54ndhcpsDHCPREQUEST received (STATE_SELECTING) for 192.------------Май 27 15:51:55ndhcpssending ACK of 192.------------Май 27 15:51:57ADBlock- Collected 0 hosts from host.3.winhelp2002.mvps.orgМай 27 15:51:57ndmOpkg::Manager: /opt/etc/init.d/01adblock: ADBlock: - Collected 0 hosts from host.3.winhelp2002.mvps.org.Май 27 15:51:57ndmOpkg::Manager: /opt/etc/init.d/01adblock: ADBlock: - Collected 0 hosts from host.4.Май 27 15:51:57ADBlock- Collected 0 hosts from host.4.Май 27 15:51:59ndhcpsDHCPDISCOVER received from e4:------------Май 27 15:51:59ndhcpsmaking OFFER of 192.------------Май 27 15:51:59ndhcpsDHCPREQUEST received (STATE_SELECTING) for 192------------Май 27 15:51:59ndmkernel: SWNAT bind table clearedМай 27 15:51:59ndhcpssending ACK of 19------------Май 27 15:52:01ndmOpkg::Manager: /opt/etc/init.d/01adblock: ADBlock: - Collected 0 hosts from host.5.hosts-file.net.Май 27 15:52:01ADBlock- Collected 0 hosts from host.5.hosts-file.netМай 27 15:52:02ndmOpkg::Manager: /opt/etc/init.d/01adblock: ADBlock: - Collected 0 hosts from host.6.Май 27 15:52:02ADBlock- Collected 0 hosts from host.6.Май 27 15:52:02ADBlock- Collected 0 hosts from host.7.pgl.yoyo.orgМай 27 15:52:02ndmOpkg::Manager: /opt/etc/init.d/01adblock: ADBlock: - Collected 0 hosts from host.7.pgl.yoyo.org.Май 27 15:52:02ndmNtp::Client: unable to communicate with "3.pool.ntp.org".Май 27 15:52:02ndmNtp::Client: could not synchronize, waiting...Май 27 15:52:06ADBlock- Collected 0 hosts from host.8.www.malwaredomainlist.comМай 27 15:52:06ndmOpkg::Manager: /opt/etc/init.d/01adblock: ADBlock: - Collected 0 hosts from host.8.www.malwaredomainlist.com.Май 27 15:52:06ADBlock- Collected 0 hosts from host.9.Май 27 15:52:06ndmOpkg::Manager: /opt/etc/init.d/01adblock: ADBlock: - Collected 0 hosts from host.9.Май 27 15:52:06ADBlock- Collected 0 hosts from host.10.github.comМай 27 15:52:06ndmOpkg::Manager: /opt/etc/init.d/01adblock: ADBlock: - Collected 0 hosts from host.10.github.com.Май 27 15:52:10ADBlock- Collected 0 hosts from host.11.veryhost.googlecode.comМай 27 15:52:10ndmOpkg::Manager: /opt/etc/init.d/01adblock: ADBlock: - Collected 0 hosts from host.11.veryhost.googlecode.com.Май 27 15:52:10ADBlockWhite list applyingМай 27 15:52:10ndmOpkg::Manager: /opt/etc/init.d/01adblock: ADBlock: White list applying.Май 27 15:52:10ADBlockWARNING!!! Used the old blocking file since we could not get updatesМай 27 15:52:10ndmOpkg::Manager: /opt/etc/init.d/01adblock: ADBlock: WARNING!!! Used the old blocking file since we could not get updates.Май 27 15:52:10ADBlockGeneration of hosts.block completedМай 27 15:52:10ndmOpkg::Manager: /opt/etc/init.d/01adblock: ADBlock: Generation of hosts.block completed.Май 27 15:52:14ndmNtp::Client: unable to communicate with "0.pool.ntp.org".Май 27 15:52:14ndmNtp::Client: could not synchronize, waiting...Май 27 15:52:17ADBlockAdded 112820 hosts for blockingМай 27 15:52:17ndmOpkg::Manager: /opt/etc/init.d/01adblock: ADBlock: Added 112820 hosts for blocking.Май 27 15:52:19rootStarted dnsmasq from .Май 27 15:52:20dnsmasq[602]started, version 2.78 cachesize 150Май 27 15:52:20dnsmasq[602]compile time options: IPv6 GNU-getopt no-RTC no-DBus no-i18n no-IDN DHCP DHCPv6 no-Lua TFTP conntrack ipset auth no-DNSSEC no-ID loop-detect inotifyМай 27 15:52:20dnsmasq[602]using nameserver 127.0.0.1#65053Май 27 15:52:20dnsmasq[602]bad address at /opt/etc/hosts line 1Май 27 15:52:20dnsmasq[602]bad address at /opt/etc/hosts line 2Май 27 15:52:20dnsmasq[602]read /opt/etc/hosts - 7 addressesМай 27 15:52:22dnsmasq[602]read /opt/etc/hosts.block - 112820 addressesИюн 12 21:56:59ndmCore::System::Clock: system time has been changed.Июн 12 21:56:59ndmNetwork::InternetChecker: Internet access detected.Июн 12 21:56:59pppd[412]System time change detected.Июн 12 21:57:06ndmCore::System::Clock: system time has been changed.Июн 12 21:57:06ndmNtp::Client: time synchronized with "0.pool.ntp.org".Июн 12 21:57:18dnsmasq[602]exiting on receipt of SIGTERMИюн 12 21:57:19dnsmasq[735]started, version 2.78 cachesize 150Июн 12 21:57:19dnsmasq[735]compile time options: IPv6 GNU-getopt no-RTC no-DBus no-i18n no-IDN DHCP DHCPv6 no-Lua TFTP conntrack ipset auth no-DNSSEC no-ID loop-detect inotifyИюн 12 21:57:19dnsmasq[735]using nameserver 127.0.0.1#65053Июн 12 21:57:19dnsmasq[735]bad address at /opt/etc/hosts line 1Июн 12 21:57:19dnsmasq[735]bad address at /opt/etc/hosts line 2Июн 12 21:57:19dnsmasq[735]read /opt/etc/hosts - 7 addressesИюн 12 21:57:19rootStarted dnsmasq from .Июн 12 21:57:20dnsmasq[735]read /opt/etc/hosts.block - 46857 addressesИюн 12 21:57:45dnsmasq[735]exiting on receipt of SIGTERMИюн 12 21:57:46dnsmasq[865]started, version 2.78 cachesize 150Июн 12 21:57:46dnsmasq[865]compile time options: IPv6 GNU-getopt no-RTC no-DBus no-i18n no-IDN DHCP DHCPv6 no-Lua TFTP conntrack ipset auth no-DNSSEC no-ID loop-detect inotifyИюн 12 21:57:46dnsmasq[865]using nameserver 127.0.0.1#65053Июн 12 21:57:46dnsmasq[865]bad address at /opt/etc/hosts line 1Июн 12 21:57:46dnsmasq[865]bad address at /opt/etc/hosts line 2Июн 12 21:57:46dnsmasq[865]read /opt/etc/hosts - 7 addressesИюн 12 21:57:46rootStarted dnsmasq from .Июн 12 21:57:46dropbear[870]Running in backgroundИюн 12 21:57:48dnsmasq[865]read /opt/etc/hosts.block - 112820 addressesИюн 12 21:57:57rootFailed to start from .Июн 12 21:57:57ndmOpkg::Manager: /opt/etc/init.d/S57dnscrypt-proxy: exit code 255.Июн 12 21:57:58dnscrypt-proxy[917]Starting dnscrypt-proxy 1.9.5Особенно смущают записи в логе:
ADBlock- Collected 0 hosts from host.1.adaway.org.............ADBlock- Collected 0 hosts from host.11.veryhost.googlecode.comADBlockWARNING!!! Used the old blocking file since we could not get updatesПри этом в конце пишет:ADBlockAdded 112820 hosts for blockingи столько же в dnsmasqГоворит ли это о том, что не удается получить актуальные данные с hosts с указанных сайтов?Если да, то в чем может быть причина? -
Спасибо, команда перезапуска помогла.
Ещё вопрос про обновление:
В 01.07.2017 в 10:31, Иван Калашников сказал:сделать симлинк для обновления hosts каждую неделю
ln -s /opt/etc/init.d/S01adblock /opt/etc/cron.weekly/
Что бы заработало, достаточно поставить cron?
-
В 01.07.2017 в 10:31, Иван Калашников сказал:Скрытый текст
Вставлю и я свои 5 копеек
Блокировка рекламы с использованием нескольких hosts + Блокировка сбора информации Windows + DNSCrypt + белый список + черный список + перенаправление
Установите необходимые пакеты:
opkg install ndmq iptables curl dnsmasq-full dnscrypt-proxy
редактирует dnsmasq.conf
no-resolv server=127.0.0.1#65053 addn-hosts=/opt/etc/hosts.block
Настройка DNScrypt-proxy
переименовываем S09dnscrypt-proxy:mv /opt/etc/init.d/S09dnscrypt-proxy /opt/etc/init.d/S57dnscrypt-proxy
редактируем S57dnscrypt-proxy, строка ARGS должна выглядеть так:
ARGS="--local-address=127.0.0.1:65053 --daemonize -R yandex"
Скопировать файл S01adblock в /opt/etc/init.d/
сделать его исполняемымchmod +x /opt/etc/init.d/S01adblock
сделать симлинк для обновления hosts каждую неделю
ln -s /opt/etc/init.d/S01adblock /opt/etc/cron.weekly/
удаление лишних заданий cron
sed -i '/cron.*min/d; /hourly/d' /opt/etc/crontab rmdir /opt/etc/cron.1min /opt/etc/cron.5mins /opt/etc/cron.hourly
подключаемся по telnet к роутеру, в командной строке набираем telnet my.keenetic.net или используем Putty, авторизуемся и вводим команды:
opkg dns-override system configuration save
По скрипту S01adblock писал сам если есть замечания предложения пишите, папка /opt/etc/adblock/ появится после первого запуска скрипта
/opt/etc/adblock/adblock.url - адреса где брать hosts для блокировки рекламы
/opt/etc/adblock/redirection - перенаправления
/opt/etc/adblock/adblock.white - белый список
/opt/etc/adblock/adblock.black - черный список
Добрый вечер. Сделал всё по цитируемой инструкции, но у меня сложилось ощущения, что интернет не успевает подняться и файл хостс не успевает заполняться, причем от раз к разу в файле разно кол-во адресов, подскажи как выйти из ситуации?
первый раз 212 адресов,, после перезагрузки 2516, максимум я видел 27 тысяч адресов
Nov 04 19:46:57dropbear[702]Running in background Nov 04 19:46:57rootStarted dnsmasq from . Nov 04 19:46:57dnsmasq[716]started, version 2.78 cachesize 150 Nov 04 19:46:57dnsmasq[716]compile time options: IPv6 GNU-getopt no-RTC no-DBus no-i18n no-IDN DHCP DHCPv6 no-Lua TFTP conntrack ipset auth no-DNSSEC no-ID loop-detect inotify Nov 04 19:46:57dnsmasq[716]using nameserver 127.0.0.1#65053 Nov 04 19:46:57dnsmasq[716]bad address at /opt/etc/hosts line 1 Nov 04 19:46:57dnsmasq[716]bad address at /opt/etc/hosts line 2 Nov 04 19:46:57dnsmasq[716]read /opt/etc/hosts - 7 addresses Nov 04 19:46:57dnsmasq[716]bad name at /opt/etc/hosts.block line 165 Nov 04 19:46:57dnsmasq[716]bad name at /opt/etc/hosts.block line 166 Nov 04 19:46:57dnsmasq[716]read /opt/etc/hosts.block - 212 addresses Nov 04 19:46:57dnscrypt-proxy[717]Starting dnscrypt-proxy 1.9.5 Nov 04 19:46:57dnscrypt-proxy[717]Generating a new session key pair Nov 04 19:46:57dnscrypt-proxy[717]Done
Nov 04 20:37:45rootStarted dnsmasq from . Nov 04 20:37:45dnsmasq[710]started, version 2.78 cachesize 150 Nov 04 20:37:45dnsmasq[710]compile time options: IPv6 GNU-getopt no-RTC no-DBus no-i18n no-IDN DHCP DHCPv6 no-Lua TFTP conntrack ipset auth no-DNSSEC no-ID loop-detect inotify Nov 04 20:37:45dnsmasq[710]using nameserver 127.0.0.1#65053 Nov 04 20:37:45dnsmasq[710]bad address at /opt/etc/hosts line 1 Nov 04 20:37:45dnsmasq[710]bad address at /opt/etc/hosts line 2 Nov 04 20:37:45dnsmasq[710]read /opt/etc/hosts - 7 addresses Nov 04 20:37:45dnsmasq[710]bad name at /opt/etc/hosts.block line 165 Nov 04 20:37:45dnsmasq[710]bad name at /opt/etc/hosts.block line 166 Nov 04 20:37:46rootStarted from . Nov 04 20:37:46dnsmasq[710]read /opt/etc/hosts.block - 2516 addresses
-
всем спасибо, вчера сам догадался и выключил DNS-прокси на роутере командой "opkg dns-override". И всё заработало.
Но у меня 4 вопроса,
1. зачем мы создаем файл с блокируемыми адресами:
addn-hosts=/opt/etc/hosts0
Почему нельзя всё записать в "оригинальный" /opt/etc/hosts ? ( я сделал так)
2. И правильно ли я понимаю, что если мой подключенный диск по каким-то причинам отвалится или падет система "Opkg", то служба ДНС работать перестанет и интернета как такового не будет? тогда её надо будет включить в "CLI" ?
3. Вопрос по содержимому файла hosts, я взял файл из ссылки https://hosts-file.net/?s=Download , правильно ли я взял самый первый, где больше всего записей? ~530 000 штук? Не заметил что роутер как-то тормозил из-за этого. Правильно дли я понимаю, что эта база содержит набор адресов с рекламой, с распространителями зловредов, следящими трекерами и прочей гадости?..
4. (Наверно глупый вопрос) Доступен ли по умолчанию из нета мой Entware по ssh сейчас , при условии что я не пробрасывал порты и не давал каких-либо разрешений на это? Я боюсь стать часть ботнета
-
беру за основу:
~ # cat /opt/etc/ndm/netfilter.d/010-intercept-dns.sh #!/bin/sh case "$table" in nat) lan_ip=$(ndmq -p 'show interface Bridge0' -P address) iptables -t nat -I PREROUTING -p udp -m udp --dport 53 -j DNAT --to-destination $lan_ip:65053 iptables -t nat -I PREROUTING -p tcp -m tcp --dport 53 -j DNAT --to-destination $lan_ip:65053 ;; *) exit 0 esac
Скрытый текстJan 29 13:08:41rootStarted dnsmasq from . Jan 29 13:08:41ndmOpkg::Manager: /opt/etc/ndm/netfilter.d/010-intercept-dns.sh: /opt/etc/ndm/netfilter.d/010-intercept-dns.sh: line 1: /: Permission denied. Jan 29 13:08:41ndmOpkg::Manager: /opt/etc/ndm/netfilter.d/010-intercept-dns.sh: /opt/etc/ndm/netfilter.d/010-intercept-dns.sh: line 3: syntax error: unexpected word (expecting "in"). Jan 29 13:08:41ndmOpkg::Manager: /opt/etc/ndm/netfilter.d/010-intercept-dns.sh: exit code 2. Jan 29 13:08:42ndmOpkg::Manager: /opt/etc/ndm/netfilter.d/010-intercept-dns.sh: /opt/etc/ndm/netfilter.d/010-intercept-dns.sh: line 1: /: Permission denied. Jan 29 13:08:42ndmOpkg::Manager: /opt/etc/ndm/netfilter.d/010-intercept-dns.sh: /opt/etc/ndm/netfilter.d/010-intercept-dns.sh: line 3: syntax error: unexpected word (expecting "in"). Jan 29 13:08:42ndmOpkg::Manager: /opt/etc/ndm/netfilter.d/010-intercept-dns.sh: exit code 2. Jan 29 13:08:42ndmOpkg::Manager: /opt/etc/ndm/netfilter.d/010-intercept-dns.sh: /opt/etc/ndm/netfilter.d/010-intercept-dns.sh: line 1: /: Permission denied. Jan 29 13:08:42ndmOpkg::Manager: /opt/etc/ndm/netfilter.d/010-intercept-dns.sh: /opt/etc/ndm/netfilter.d/010-intercept-dns.sh: line 3: syntax error: unexpected word (expecting "in"). Jan 29 13:08:42ndmOpkg::Manager: /opt/etc/ndm/netfilter.d/010-intercept-dns.sh: exit code 2.
Подскажите в чём ошибка?
Уже несколько раз переделывал, с использованием нескольких версий файлов dnsmasq.conf и 010-intercept-dns.sh
Если записать в 010-intercept-dns.sh текст из первого сообщения, то ошибка как у -aMk-
ЦитатаДобрый вечер форумчане. А я не починил (как отписался предшествующий оратор :)) ). Вручную, через Putty, фильтрация работает.... Что я делаю:
в консоли копипастой по очереди запускаю
lan_ip=$(ndmq -p 'show interface Bridge0' -P address)
iptables -t nat -I PREROUTING -p udp -m udp --dport 53 -j DNAT --to-destination $lan_ip:65053
iptables -t nat -I PREROUTING -p tcp -m tcp --dport 53 -j DNAT --to-destination $lan_ip:65053
и фильтр работает, НО в журнале имею:
Nov 11 19:52:27ndm Opkg::Manager: /opt/etc/ndm/netfilter.d/010-intercept-dns.sh: Try `iptables -h' or 'iptables --help' for more information.Nov 11 19:52:27ndm Opkg::Manager: /opt/etc/ndm/netfilter.d/010-intercept-dns.sh: Try `iptables -h' or 'iptables --help' for more information.Nov 11 19:52:27ndm Opkg::Manager: /opt/etc/ndm/netfilter.d/010-intercept-dns.sh: exit code 2.Что не так-то? Сильно подозреваю, что с синтаксисом во 2-й строке косяк, но т.к. в "этих-ваших-линуксах" слабо понимаю, то сообразить где ошибка - не могу. Версия EnterWare - последняя доступная, может доустановить что-то из репозитория, или роутер сбросить "на завод" и всё с нуля попробовать ??
При этом руками команды из 010-intercept-dns.sh, то работает тоже
У меня складывается ощущение, что файлик 010-intercept-dns.sh то ли чем-то занят, то ли не совсем верно записан, и dnsmasq тупо не может прочитать свои команды.
При этом dns стоит получать от провайдера. Всякие яндекс и sky днс выключены. настроен только проброс портов во внутреннюю сеть для торентов.
Скрытый текст~ # opkg list-installed dnsmasq-full - 2.76-7a dropbear - 2016.74-1 findutils - 4.6.0-1 glib2 - 2.49.7-1 iptables - 1.4.21-2 ldconfig - 2.23-7 libattr - 20160302-1 libblkid - 2.28-1b libc - 2.23-7 libffi - 3.2.1-2 libgcc - 5.4.0-7 libiconv-full - 1.11.1-3 libintl-full - 0.19.8.1-1 libmnl - 1.0.4-1 libmount - 2.28-1b libndm - 1.1.0-1a libnetfilter-conntrack - 1.0.6-1 libnfnetlink - 1.0.1-1 libopenssl - 1.0.2j-1a libpthread - 2.23-7 librt - 2.23-7 libslang2 - 2.3.1-1 libssh2 - 1.7.0-1 libssp - 5.4.0-7 libstdcpp - 5.4.0-7 libuuid - 2.28-1b locales - 2.23-7 mc - 4.8.18-1a ndmq - 1.0.2-1a opt-ndmsv2 - 1.0-6a terminfo - 6.0-1c zlib - 1.2.8-1 zoneinfo-asia - 2016j-1 zoneinfo-europe - 2016j-1 ~ #
Установленная версия NDMS: v2.09(AAUX.1)A2
Защищаем DNS запросы с помощью dnscrypt-proxy2. Бонусом блокировка рекламы.
in Каталог готовых решений Opkg
Posted
Спасибо, заработало. Правда пришлось сделать имена файлов "толерантными"
Они решили blacklist заменить на blocklists....
А whitelist на allowlist....