Skip to content

Commit 9184c31

Browse files
committed
Revert "Revert "windows支持以及linux自动更新""
This reverts commit ad2e4ee.
1 parent ad2e4ee commit 9184c31

File tree

5 files changed

+88
-18
lines changed

5 files changed

+88
-18
lines changed

.github/workflows/CI.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ jobs:
2626
- name: Install dependencies
2727
run: |
2828
python -m pip install --upgrade pip
29-
pip install requests fake_useragent ping3 prettytable aiohttp uvloop
29+
pip install requests fake_useragent ping3 prettytable aiohttp uvloop crontab
3030
- name: Build and publish
3131
run: |
3232
./main.py -t github.com

main.py

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22
import argparse
33
import myutils
44

5+
import sys
6+
57
def initArguments():
68
parser = argparse.ArgumentParser(
79
description="Prevent domains from dns polution.")
@@ -12,7 +14,7 @@ def initArguments():
1214
parser.add_argument("--area", help="Choose area in china asia europe africa oceania north_america south_america",
1315
choices=["china", "asia", "europe", "africa", "oceania", "north_america", "south_america", "debug"], type=str, default="north_america", nargs='?')
1416
parser.add_argument(
15-
"--thread", help="Run num of threads,default is 3", type=int, default=3)
17+
"--update", help="Auto update hosts", action="store_true")
1618
args = parser.parse_args()
1719
return parser, args
1820

@@ -29,6 +31,10 @@ def main():
2931

3032
if args.clean:
3133
myutils.output_dic(domain, ipdict[1])
34+
if args.update and 'win' not in sys.platform:
35+
myutils.update_hosts(domain, tuple(ipdict[1].keys()))
36+
myutils.update_crontab(domain)
37+
3238

3339
if __name__ == "__main__":
3440
main()

multi.py

Lines changed: 33 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
11
import asyncio
22
import aiohttp
3-
import uvloop
3+
4+
import sys
45

56
import time
67
import subprocess
78
import re
89

9-
1010
class MyConnector(aiohttp.TCPConnector):
1111
def __init__(self, ip):
1212
self.__ip = ip
@@ -32,6 +32,7 @@ def now(): return time.time()
3232
ip_list = []
3333
time_list = {}
3434

35+
3536
async def run(cmd):
3637
proc = await asyncio.create_subprocess_shell(
3738
cmd,
@@ -41,35 +42,57 @@ async def run(cmd):
4142
stdout, stderr = await proc.communicate()
4243

4344
if stdout:
44-
ip_find = re.findall("\\d+\\.\\d+\\.\\d+\\.\\d+", stdout.decode())
45+
if platform == "linux":
46+
ip_find = re.findall("\\d+\\.\\d+\\.\\d+\\.\\d+", stdout.decode())
47+
elif platform == "win":
48+
ip_find_tmp = re.findall(
49+
"\\d+\\.\\d+\\.\\d+\\.\\d+", stdout.decode("gbk"))
50+
real_dns_addr = ip_find_tmp[0]
51+
ip_find = [i for i in ip_find_tmp if i != real_dns_addr]
4552
ip_list.extend(ip_find)
4653
if stderr:
47-
print(f'[stderr]\n{stderr.decode()}')
54+
pass
4855

4956

5057
async def test_doamin_ip(ip):
5158
st = now()
5259
try:
5360
async with aiohttp.ClientSession(connector=MyConnector(ip), timeout=aiohttp.ClientTimeout(total=10)) as client:
5461
async with client.get("https://{0}".format(ip), ssl=False, timeout=10) as resp:
55-
if resp.status == 200:
62+
if resp.status == 200 or 405:
5663
time_list[ip] = now() - st
5764
except asyncio.TimeoutError:
5865
pass
66+
5967

6068
async def dns_test(domain):
61-
task_list = [asyncio.create_task(
62-
run('dig @{0} {1} +short'.format(dns, domain))) for dns in dns_list]
69+
if platform == "linux":
70+
task_list = [asyncio.create_task(
71+
run('dig @{0} {1} +short'.format(dns, domain))) for dns in dns_list]
72+
elif platform == "win":
73+
task_list = [asyncio.create_task(
74+
run('nslookup {0} {1}'.format(domain, dns))) for dns in dns_list]
6375
done, pending = await asyncio.wait(task_list, timeout=5)
6476

6577
task_speed = [asyncio.create_task(test_doamin_ip(ip))
6678
for ip in set(ip_list)]
6779
done, pending = await asyncio.wait(task_speed)
6880

69-
def multi_local_dns(domain):
70-
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
7181

82+
def multi_local_dns(domain, platform_in):
83+
global platform
84+
platform = platform_in
85+
if platform == 'linux':
86+
import uvloop
87+
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
88+
elif platform == 'win':
89+
asyncio.set_event_loop_policy(asyncio.WindowsProactorEventLoopPolicy())
90+
else:
91+
raise "platform not support!"
7292
start = now()
73-
asyncio.run(dns_test(domain))
93+
loop = asyncio.get_event_loop()
94+
loop.run_until_complete(dns_test(domain))
95+
96+
# asyncio.run(dns_test(domain))
7497
print("Time: ", now() - start)
7598
return domain, time_list

myutils.py

Lines changed: 44 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,14 +4,22 @@
44
import re
55
from prettytable import PrettyTable
66

7+
import os
8+
import sys
9+
import subprocess
10+
11+
global platform
12+
if "linux" in sys.platform:
13+
from crontab import CronTab
14+
platform = "linux"
15+
elif "win" in sys.platform:
16+
platform = "win"
17+
718
def run_core(domain, area):
819
# Encrypt!
9-
if area == "debug":
10-
iplist = ['220.181.38.148', '39.156.69.79', '210.23.129.34', '210.23.129.34', '220.181.38.148', '39.156.69.79', '202.108.22.220', '220.181.33.31', '112.80.248.64', '14.215.178.80', '180.76.76.92', '210.23.129.34', '210.23.129.34', '39.156.69.79', '220.181.38.148', '203.12.160.35', '203.12.160.35', '39.156.69.79', '220.181.38.148',
11-
'202.108.22.220', '220.181.33.31', '112.80.248.64', '14.215.178.80', '180.76.76.92', '203.12.160.35', '203.12.160.35', '220.181.38.148', '39.156.69.79', '61.8.0.113', '61.8.0.113', '220.181.38.148', '39.156.69.79', '202.108.22.220', '220.181.33.31', '112.80.248.64', '14.215.178.80', '180.76.76.92', '61.8.0.113', '61.8.0.113']
12-
else:
13-
ipdict = multi.multi_local_dns(domain)
14-
print("[+]Got domain! \n" + str(list(ipdict[1].keys())))
20+
print("[+]platform detect: "+platform)
21+
ipdict = multi.multi_local_dns(domain,platform)
22+
print("[+]Got domain! \n" + str(list(ipdict[1].keys())))
1523
return domain, ipdict
1624

1725

@@ -47,6 +55,36 @@ def output_dic(domain, ip_dic):
4755

4856
print(table)
4957

58+
def update_hosts(domain, new_ip):
59+
if os.getuid() != 0:
60+
sys.exit("not root?")
61+
62+
if len(new_ip) != 0:
63+
print("[-]Start updating hosts")
64+
for ip in new_ip[::-1]:
65+
cmd = ['sed', '-i', rf'/^[0-9.]\+[[:space:]]\+{domain}\>/s/[^[:space:]]\+/{ip}/', '/etc/hosts']
66+
try:
67+
subprocess.check_call(cmd)
68+
print("Add {0} {1}".format(domain, ip))
69+
except:
70+
print("Error: {0} {1}".format(domain, ip))
71+
print("[+]Done!")
72+
73+
def update_crontab(domain):
74+
my_user_cron = CronTab(user=True) # 创建当前用户的crontab
75+
# 删除原有的crontab文件中重复的内容
76+
77+
objs = my_user_cron.find_comment(domain)
78+
if objs:
79+
for obj in objs:
80+
my_user_cron.remove(obj)
81+
82+
job = my_user_cron.new(command='python3 /program/python/Hosts-chooser-master main.py -t ' + domain + ' --clean')
83+
job.setall('*/2 * * * *') # 设置执行时间
84+
job.set_comment(domain)
85+
86+
my_user_cron.write()
87+
5088
class domainError(Exception):
5189
def __init__(self,err='invalid domian'):
5290
Exception.__init__(self,err)

requirements.txt

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,7 @@
1+
aiohttp==3.6.2
12
fake-useragent==0.1.11
23
prettytable==0.7.2
34
requests==2.23.0
45
urllib3==1.25.9
6+
uvloop==0.14.0
7+
crontab==0.22.9

0 commit comments

Comments
 (0)