mirror of
https://github.com/Justuser3310/jetwork.git
synced 2026-06-14 06:11:02 +00:00
Compare commits
39 Commits
fa68dda1cf
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 9ff83b0c0a | |||
| 59aeeaac33 | |||
| 6e96b0dfb3 | |||
| f06c6f963c | |||
| 1c4a7bb11a | |||
| dfd5d61db7 | |||
| d3a25ee190 | |||
| c5a0111fab | |||
| dfc37d6ea7 | |||
| e83bee6b08 | |||
| ca1e5422a2 | |||
| 54a4692cac | |||
| a44099a9e0 | |||
| b9aaef110f | |||
| 311cde3b15 | |||
| b6652cf5d6 | |||
| 2abe6dfb87 | |||
| 5cec15dbd5 | |||
| 6ce7dbc771 | |||
| 89e34cd473 | |||
| 27eba1fbf4 | |||
| f89269a1f6 | |||
| ce628c40d6 | |||
| f09daea63e | |||
| 9d2645d7ca | |||
| 81f2b20866 | |||
| 393e02477e | |||
| 19349a0946 | |||
| ffcf047286 | |||
| ec0523d52c | |||
| e72996af3c | |||
| 78202f027e | |||
| 91678cdf48 | |||
| 07954059e2 | |||
| 4eb0143970 | |||
| c6a9b37325 | |||
| a73a370f0a | |||
| fecbc8787a | |||
| d78533c72b |
@@ -6,6 +6,13 @@ https://t.me/justuser31_chat
|
|||||||
<br>
|
<br>
|
||||||
<br>
|
<br>
|
||||||
|
|
||||||
|
# 📃 Документация (ТУТ ВСЁ)
|
||||||
|
[**>>> ДОКУМЕНТАЦИЯ <<<**](https://docs.del.pw/books/jetwork) <br>
|
||||||
|
(Там всё есть!!!)
|
||||||
|
|
||||||
|
<br>
|
||||||
|
<br>
|
||||||
|
|
||||||
## 🔼 План развития
|
## 🔼 План развития
|
||||||
* Обновление диаграм
|
* Обновление диаграм
|
||||||
* Обновление документации
|
* Обновление документации
|
||||||
@@ -16,114 +23,3 @@ https://t.me/justuser31_chat
|
|||||||
* Реализация динамических сайтов
|
* Реализация динамических сайтов
|
||||||
* Устранение утечки памяти при поиске портов
|
* Устранение утечки памяти при поиске портов
|
||||||
|
|
||||||
<br>
|
|
||||||
<br>
|
|
||||||
|
|
||||||
# 📃 Документация
|
|
||||||
Читайте "начало работы", если хотите, чтобы последующие действия работали.
|
|
||||||
|
|
||||||
<br>
|
|
||||||
|
|
||||||
## 📋 Содержание
|
|
||||||
- ▶️ Начало работы
|
|
||||||
- 🌐 Установка на сервер
|
|
||||||
- 🔓 Открытие любых портов
|
|
||||||
- 📎 Публикация статичного сайта
|
|
||||||
- 📎 Публикация динамичного сайта
|
|
||||||
- 🪄 Как это работает
|
|
||||||
|
|
||||||
|
|
||||||
<br>
|
|
||||||
<br>
|
|
||||||
|
|
||||||
### ▶️ Начало работы
|
|
||||||
|
|
||||||
<br>
|
|
||||||
|
|
||||||
#### 🐧 Linux
|
|
||||||
1. Установить python: `sudo apt install python3`
|
|
||||||
2. Установить git: `sudo apt install git`
|
|
||||||
3. Установить tar: `sudo apt install tar`
|
|
||||||
4. Клонировать репозиторий: `git clone https://github.com/Justuser3310/jetwork.git`
|
|
||||||
5. Запустить setup.py: `cd jetwork && python setup.py`
|
|
||||||
6. Запустить клиент: `python main.py`
|
|
||||||
7. Зайти на `http://127.0.0.1:5555`
|
|
||||||
|
|
||||||
<br>
|
|
||||||
<br>
|
|
||||||
|
|
||||||
#### 🪟 Windows
|
|
||||||
1. Установить python: https://www.python.org/downloads/release/python-3122/ (Windows installer)
|
|
||||||
2. Установить git: https://git-scm.com/download/win (Windows setup)
|
|
||||||
3. Клонировать репозиторий: `git clone https://github.com/Justuser3310/jetwork.git`
|
|
||||||
4. Запустить setup.py: `cd jetwork && python setup.py`
|
|
||||||
5. Запустить клиент: `python main.py`
|
|
||||||
6. Зайти на `http://127.0.0.1:5555`
|
|
||||||
|
|
||||||
<br>
|
|
||||||
<br>
|
|
||||||
|
|
||||||
#### 📱 Termux
|
|
||||||
Следовать инструкции для Linux.
|
|
||||||
Только заменить `sudo apt` на `pkg` в 1-3 шагах.
|
|
||||||
|
|
||||||
<br>
|
|
||||||
<br>
|
|
||||||
|
|
||||||
### 🌐 Начало работы
|
|
||||||
|
|
||||||
1. Выполнить шаги в начале работы до 5 включительно (Linux) или 4 (Windows)
|
|
||||||
2. Запустить серверный клиент: `python srv_main.py`
|
|
||||||
( Отключён скан портов, чтобы снизить нагрузку и избежать утечки памяти )
|
|
||||||
3. Зайти на `http://127.0.0.1:5555`
|
|
||||||
|
|
||||||
<br>
|
|
||||||
<br>
|
|
||||||
|
|
||||||
### 🔓 Открытие любых портов
|
|
||||||
Открыть порт 25565: \
|
|
||||||
`python port_open.py` \
|
|
||||||
Далее вводим `25565`
|
|
||||||
|
|
||||||
<br>
|
|
||||||
<br>
|
|
||||||
|
|
||||||
### 📎 Публикация статичного сайта
|
|
||||||
`python site_creator.py`
|
|
||||||
|
|
||||||
Далее следовать подсказкам.
|
|
||||||
Существование index.html ОБЯЗАТЕЛЬНО.
|
|
||||||
|
|
||||||
<br>
|
|
||||||
<br>
|
|
||||||
|
|
||||||
### 📎 Публикация динамичного сайта
|
|
||||||
|
|
||||||
Скоро...
|
|
||||||
|
|
||||||
<br>
|
|
||||||
<br>
|
|
||||||
|
|
||||||
### 🪄 Как это работает
|
|
||||||
|
|
||||||
<br>
|
|
||||||
|
|
||||||
***
|
|
||||||
#### Клиент
|
|
||||||
|
|
||||||

|
|
||||||
|
|
||||||
<br>
|
|
||||||
|
|
||||||
***
|
|
||||||
#### Статичный сайт
|
|
||||||
|
|
||||||

|
|
||||||
|
|
||||||
<br>
|
|
||||||
|
|
||||||
***
|
|
||||||
#### Динамичный сайт
|
|
||||||
|
|
||||||

|
|
||||||
|
|
||||||
|
|||||||
@@ -2,19 +2,19 @@ import os
|
|||||||
import json
|
import json
|
||||||
|
|
||||||
if not os.path.exists('config.json'):
|
if not os.path.exists('config.json'):
|
||||||
db = {"our_port": 0000, "ports": [], "domain": "http://0.0.0.0:8000"}
|
db = {'os': None,'our_port': 0000, 'ports': [], 'base_url': 'http://0.0.0.0:8000'}
|
||||||
js = json.dumps(db, indent=2)
|
js = json.dumps(db, indent=2)
|
||||||
with open("config.json", "w") as outfile:
|
with open('config.json', 'w') as outfile:
|
||||||
outfile.write(js)
|
outfile.write(js)
|
||||||
print('Created new config.json')
|
print('Created new config.json')
|
||||||
|
|
||||||
|
|
||||||
def read(file = 'config.json'):
|
def read(file = 'config.json'):
|
||||||
with open(file, "r", encoding="utf-8") as openfile:
|
with open(file, 'r', encoding='utf-8') as openfile:
|
||||||
db = json.load(openfile)
|
db = json.load(openfile)
|
||||||
return db
|
return db
|
||||||
|
|
||||||
def write(db, file = 'config.json'):
|
def write(db, file = 'config.json'):
|
||||||
js = json.dumps(db, indent=2, ensure_ascii=False)
|
js = json.dumps(db, indent=2, ensure_ascii=False)
|
||||||
with open(file, "w", encoding="utf-8") as outfile:
|
with open(file, 'w', encoding='utf-8') as outfile:
|
||||||
outfile.write(js)
|
outfile.write(js)
|
||||||
|
|||||||
@@ -0,0 +1 @@
|
|||||||
|
{"activeProfileId":"InternalProfile_SmartRules","defaultProxyServerId":"usundlzx4uvk2","firstEverInstallNotified":true,"options":{"syncSettings":false,"syncActiveProfile":true,"syncActiveProxy":true,"detectRequestFailures":true,"displayFailedOnBadge":true,"displayAppliedProxyOnBadge":true,"displayMatchedRuleOnBadge":true,"refreshTabOnConfigChanges":false,"proxyPerOrigin":true,"enableShortcuts":true,"shortcutNotification":true,"themeType":0,"themesDark":"themes-cosmo-dark"},"product":"SmartProxy","proxyProfiles":[{"enabled":true,"proxyRules":[],"rulesSubscriptions":[],"profileId":"InternalProfile_Direct","profileType":0,"profileTypeConfig":{"builtin":true,"editable":false,"selectable":true,"supportsSubscriptions":false,"supportsProfileProxy":false,"customProxyPerRule":false,"canBeDisabled":false,"supportsRuleActionWhitelist":false,"defaultRuleActionIsWhitelist":null},"profileName":"Direct (No Proxy)","profileProxyServerId":null},{"enabled":true,"proxyRules":[{"enabled":true,"whiteList":false,"ruleId":99411781,"autoGeneratePattern":true,"ruleType":0,"hostName":"jet","rulePattern":"*.jet/*","ruleRegex":"","ruleExact":"","proxy":{"name":"jet_local","id":"ezgallzykftxq","order":1,"host":"127.0.0.1","port":"8080","protocol":"HTTP","username":"","password":"","proxyDNS":true,"failoverTimeout":null},"proxyServerId":"ezgallzykftxq"},{"enabled":true,"whiteList":false,"ruleId":274078801725,"autoGeneratePattern":true,"ruleType":0,"hostName":"mirror","rulePattern":"*.mirror/*","ruleRegex":"","ruleExact":"","proxy":{"name":"jet_local","id":"ezgallzykftxq","order":1,"host":"127.0.0.1","port":"8080","protocol":"HTTP","username":"","password":"","proxyDNS":true,"failoverTimeout":null},"proxyServerId":"ezgallzykftxq"},{"enabled":true,"whiteList":false,"ruleId":597907496,"autoGeneratePattern":true,"ruleType":0,"hostName":"me","rulePattern":"*.me/*","ruleRegex":"","ruleExact":"","proxy":{"name":"jet_local","id":"ezgallzykftxq","order":1,"host":"127.0.0.1","port":"8080","protocol":"HTTP","username":"","password":"","proxyDNS":true,"failoverTimeout":null},"proxyServerId":"ezgallzykftxq"}],"rulesSubscriptions":[],"profileId":"InternalProfile_SmartRules","profileType":2,"profileTypeConfig":{"builtin":true,"editable":true,"selectable":true,"supportsSubscriptions":true,"supportsProfileProxy":true,"customProxyPerRule":true,"canBeDisabled":true,"supportsRuleActionWhitelist":true,"defaultRuleActionIsWhitelist":false},"profileName":"Smart Proxy","profileProxyServerId":""},{"enabled":true,"proxyRules":[],"rulesSubscriptions":[],"profileId":"InternalProfile_AlwaysEnabled","profileType":3,"profileTypeConfig":{"builtin":true,"editable":true,"selectable":true,"supportsSubscriptions":true,"supportsProfileProxy":true,"customProxyPerRule":true,"canBeDisabled":true,"supportsRuleActionWhitelist":true,"defaultRuleActionIsWhitelist":true},"profileName":"Always Enable","profileProxyServerId":null},{"enabled":true,"proxyRules":[],"rulesSubscriptions":[],"profileId":"InternalProfile_SystemProxy","profileType":1,"profileTypeConfig":{"builtin":true,"editable":false,"selectable":true,"supportsSubscriptions":false,"supportsProfileProxy":false,"customProxyPerRule":false,"canBeDisabled":false,"supportsRuleActionWhitelist":false,"defaultRuleActionIsWhitelist":null},"profileName":"System Proxy","profileProxyServerId":null},{"enabled":true,"proxyRules":[],"rulesSubscriptions":[],"profileType":4,"profileTypeConfig":{"builtin":true,"editable":false,"selectable":false,"supportsSubscriptions":false,"supportsProfileProxy":false,"customProxyPerRule":false,"canBeDisabled":false,"supportsRuleActionWhitelist":false,"defaultRuleActionIsWhitelist":null},"profileName":"Ignore Failure Rules","profileId":"profile-ms5zflzx4opc8"}],"proxyServerSubscriptions":[],"proxyServers":[{"name":"jet_public","id":"usundlzx4uvk2","order":3,"host":"jet.del.pw","port":"8080","protocol":"HTTP","username":"","password":"","proxyDNS":true,"failoverTimeout":null},{"name":"jet_local","id":"ezgallzykftxq","order":1,"host":"127.0.0.1","port":"8080","protocol":"HTTP","username":"","password":"","proxyDNS":true,"failoverTimeout":null}],"updateInfo":{"updateIsAvailable":false,"downloadPage":null,"version":null,"versionName":null,"isBrowserSpecific":true},"version":"1.5"}
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
{"activeProfileId":"InternalProfile_SmartRules","defaultProxyServerId":"usundlzx4uvk2","firstEverInstallNotified":true,"options":{"syncSettings":false,"syncActiveProfile":true,"syncActiveProxy":true,"detectRequestFailures":true,"displayFailedOnBadge":true,"displayAppliedProxyOnBadge":true,"displayMatchedRuleOnBadge":true,"refreshTabOnConfigChanges":false,"proxyPerOrigin":true,"enableShortcuts":true,"shortcutNotification":true,"themeType":0,"themesDark":"themes-cosmo-dark"},"product":"SmartProxy","proxyProfiles":[{"enabled":true,"proxyRules":[],"rulesSubscriptions":[],"profileId":"InternalProfile_Direct","profileType":0,"profileTypeConfig":{"builtin":true,"editable":false,"selectable":true,"supportsSubscriptions":false,"supportsProfileProxy":false,"customProxyPerRule":false,"canBeDisabled":false,"supportsRuleActionWhitelist":false,"defaultRuleActionIsWhitelist":null},"profileName":"Direct (No Proxy)","profileProxyServerId":null},{"enabled":true,"proxyRules":[{"enabled":true,"whiteList":false,"ruleId":42142459831829816,"autoGeneratePattern":true,"ruleType":0,"hostName":"jet","rulePattern":"*.jet/*","ruleRegex":"","ruleExact":"","proxy":{"name":"jet_public","id":"usundlzx4uvk2","order":3,"host":"jet.del.pw","port":"8080","protocol":"HTTP","username":"","password":"","proxyDNS":true,"failoverTimeout":null},"proxyServerId":"usundlzx4uvk2"},{"enabled":true,"whiteList":false,"ruleId":995421339685,"autoGeneratePattern":true,"ruleType":0,"hostName":"mirror","rulePattern":"*.mirror/*","ruleRegex":"","ruleExact":"","proxy":{"name":"jet_public","id":"usundlzx4uvk2","order":3,"host":"jet.del.pw","port":"8080","protocol":"HTTP","username":"","password":"","proxyDNS":true,"failoverTimeout":null},"proxyServerId":"usundlzx4uvk2"},{"enabled":true,"whiteList":false,"ruleId":7021094,"autoGeneratePattern":true,"ruleType":0,"hostName":"me","rulePattern":"*.me/*","ruleRegex":"","ruleExact":"","proxy":{"name":"jet_public","id":"usundlzx4uvk2","order":3,"host":"jet.del.pw","port":"8080","protocol":"HTTP","username":"","password":"","proxyDNS":true,"failoverTimeout":null},"proxyServerId":"usundlzx4uvk2"}],"rulesSubscriptions":[],"profileId":"InternalProfile_SmartRules","profileType":2,"profileTypeConfig":{"builtin":true,"editable":true,"selectable":true,"supportsSubscriptions":true,"supportsProfileProxy":true,"customProxyPerRule":true,"canBeDisabled":true,"supportsRuleActionWhitelist":true,"defaultRuleActionIsWhitelist":false},"profileName":"Smart Proxy","profileProxyServerId":""},{"enabled":true,"proxyRules":[],"rulesSubscriptions":[],"profileId":"InternalProfile_AlwaysEnabled","profileType":3,"profileTypeConfig":{"builtin":true,"editable":true,"selectable":true,"supportsSubscriptions":true,"supportsProfileProxy":true,"customProxyPerRule":true,"canBeDisabled":true,"supportsRuleActionWhitelist":true,"defaultRuleActionIsWhitelist":true},"profileName":"Always Enable","profileProxyServerId":null},{"enabled":true,"proxyRules":[],"rulesSubscriptions":[],"profileId":"InternalProfile_SystemProxy","profileType":1,"profileTypeConfig":{"builtin":true,"editable":false,"selectable":true,"supportsSubscriptions":false,"supportsProfileProxy":false,"customProxyPerRule":false,"canBeDisabled":false,"supportsRuleActionWhitelist":false,"defaultRuleActionIsWhitelist":null},"profileName":"System Proxy","profileProxyServerId":null},{"enabled":true,"proxyRules":[],"rulesSubscriptions":[],"profileType":4,"profileTypeConfig":{"builtin":true,"editable":false,"selectable":false,"supportsSubscriptions":false,"supportsProfileProxy":false,"customProxyPerRule":false,"canBeDisabled":false,"supportsRuleActionWhitelist":false,"defaultRuleActionIsWhitelist":null},"profileName":"Ignore Failure Rules","profileId":"profile-ms5zflzx4opc8"}],"proxyServerSubscriptions":[],"proxyServers":[{"name":"jet_public","id":"usundlzx4uvk2","order":3,"host":"jet.del.pw","port":"8080","protocol":"HTTP","username":"","password":"","proxyDNS":true,"failoverTimeout":null},{"name":"jet_local","id":"ezgallzykftxq","order":1,"host":"127.0.0.1","port":"8080","protocol":"HTTP","username":"","password":"","proxyDNS":true,"failoverTimeout":null}],"updateInfo":{"updateIsAvailable":false,"downloadPage":null,"version":null,"versionName":null,"isBrowserSpecific":true},"version":"1.5"}
|
||||||
+13
-5
@@ -1,15 +1,23 @@
|
|||||||
from re import compile, sub
|
from re import compile, sub
|
||||||
|
domains = ['jet', 'mirror', 'me']
|
||||||
|
|
||||||
def domain_ok(domain):
|
def domain_ok(domain):
|
||||||
domains = ["jet", "jw", "404", "dash", "awesome", "mirror"]
|
global domains
|
||||||
|
if domain.count('.') == 1:
|
||||||
if domain.count(".") == 1:
|
if domain.split('.')[1] in domains:
|
||||||
if domain.split(".")[1] in domains:
|
|
||||||
# ../some => some
|
# ../some => some
|
||||||
# Защита от проверки папок выше, чем нужно и др.
|
# Защита от проверки папок выше, чем нужно и др.
|
||||||
regex = compile('[^a-z.-]')
|
regex = compile('[^a-z0-9.-]')
|
||||||
c_domain = regex.sub('', domain)
|
c_domain = regex.sub('', domain)
|
||||||
if domain == c_domain:
|
if domain == c_domain:
|
||||||
return domain
|
return domain
|
||||||
|
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
def domain_list():
|
||||||
|
global domains
|
||||||
|
out = ''
|
||||||
|
for i in domains:
|
||||||
|
out += f'{i}, '
|
||||||
|
out = out[:-2]
|
||||||
|
return out
|
||||||
|
|||||||
+6
-5
@@ -67,16 +67,17 @@ def update_servers(n):
|
|||||||
Input('interval-component', 'n_intervals'),
|
Input('interval-component', 'n_intervals'),
|
||||||
Input('search', 'value'))
|
Input('search', 'value'))
|
||||||
def update_sites(n, s_val):
|
def update_sites(n, s_val):
|
||||||
# Домен по умолчанию
|
# Префикс
|
||||||
domain = read()['domain']
|
base_url = read()['base_url']
|
||||||
# Если есть элемент в поиске
|
# Если есть элемент в поиске
|
||||||
if s_val:
|
if s_val:
|
||||||
return html.Div([ dcc.Link(children=i, href=f'{domain}/{s_val}',
|
return html.Div([ dcc.Link(children=i, href=f'{base_url}/{s_val}',
|
||||||
target='_blank') ], className='sites_elem')
|
target='_blank') ], className='sites_elem')
|
||||||
|
|
||||||
res = []
|
res = []
|
||||||
for i in next(walk('cached/'), (None, None, []))[1]:
|
for i in next(walk('cached/'), (None, None, []))[1]:
|
||||||
res.append(html.Div([ dcc.Link(children=i, href=f'{domain}/{i}',
|
conf = read(f'cached/{i}/config.json')
|
||||||
|
res.append(html.Div([ dcc.Link(children=i, href=f'http://{i}',
|
||||||
target='_blank') ], className='sites_elem'))
|
target='_blank') ], className='sites_elem'))
|
||||||
return res
|
return res
|
||||||
|
|
||||||
@@ -90,4 +91,4 @@ def update_search(n):
|
|||||||
return res
|
return res
|
||||||
|
|
||||||
#app.run(debug=True, port = 5555)
|
#app.run(debug=True, port = 5555)
|
||||||
app.run(debug=False, port = 5555)
|
app.run(debug=False, host = '0.0.0.0', port = 5555)
|
||||||
|
|||||||
@@ -7,7 +7,9 @@ from multiprocessing import Process
|
|||||||
from network import *
|
from network import *
|
||||||
from updater import *
|
from updater import *
|
||||||
from proxy import *
|
from proxy import *
|
||||||
|
from web_proxy import *
|
||||||
from status import *
|
from status import *
|
||||||
|
|
||||||
from db import *
|
from db import *
|
||||||
|
|
||||||
#
|
#
|
||||||
@@ -47,9 +49,12 @@ def main():
|
|||||||
# http сервер
|
# http сервер
|
||||||
http = Thread(target = server_http)
|
http = Thread(target = server_http)
|
||||||
http.start()
|
http.start()
|
||||||
# сервер обработки запросов
|
# Cервер обработки запросов
|
||||||
srv = Thread(target = server, args=(http_port,))
|
srv = Thread(target = server, args=(http_port,))
|
||||||
srv.start()
|
srv.start()
|
||||||
|
# Прокси для браузера
|
||||||
|
http_proxy = Thread(target = web_proxy)
|
||||||
|
http_proxy.start()
|
||||||
|
|
||||||
# Стартуем авто-поиск портов и авто-обновление сайтов
|
# Стартуем авто-поиск портов и авто-обновление сайтов
|
||||||
updater = Thread(target = update_demon, args=(serv_port,))
|
updater = Thread(target = update_demon, args=(serv_port,))
|
||||||
|
|||||||
+21
-16
@@ -13,6 +13,9 @@ from db import read
|
|||||||
from json import loads
|
from json import loads
|
||||||
# Логирование ошибок
|
# Логирование ошибок
|
||||||
import logging
|
import logging
|
||||||
|
# Просто логирование
|
||||||
|
from icecream import ic
|
||||||
|
ic.disable() # Отключение логирования
|
||||||
|
|
||||||
from verify import *
|
from verify import *
|
||||||
from domain_check import *
|
from domain_check import *
|
||||||
@@ -43,7 +46,7 @@ def server_http():
|
|||||||
except KeyboardInterrupt:
|
except KeyboardInterrupt:
|
||||||
run = False
|
run = False
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print("SERVER_HTTP FALLED")
|
ic("SERVER_HTTP FALLED")
|
||||||
logging.critical(e, exc_info=True)
|
logging.critical(e, exc_info=True)
|
||||||
|
|
||||||
def server(http_port):
|
def server(http_port):
|
||||||
@@ -59,7 +62,7 @@ def server(http_port):
|
|||||||
s.listen(2)
|
s.listen(2)
|
||||||
conn, address = s.accept()
|
conn, address = s.accept()
|
||||||
|
|
||||||
print("Connection from: " + str(address))
|
ic("Connection from: " + str(address))
|
||||||
|
|
||||||
while True:
|
while True:
|
||||||
try:
|
try:
|
||||||
@@ -82,11 +85,10 @@ def server(http_port):
|
|||||||
conn.send("not_exist".encode())
|
conn.send("not_exist".encode())
|
||||||
elif op[:8] == "publish_":
|
elif op[:8] == "publish_":
|
||||||
data = op[8:]
|
data = op[8:]
|
||||||
site, port = data.split("<>")
|
site, u_port = data.split("<>")
|
||||||
site = domain_ok(site)
|
if domain_ok(site):
|
||||||
if site:
|
|
||||||
conn.send("accepted".encode())
|
conn.send("accepted".encode())
|
||||||
client(port, f"get_{site}")
|
client(u_port, f"get_{site}")
|
||||||
elif op == "check_all":
|
elif op == "check_all":
|
||||||
try:
|
try:
|
||||||
sites = next(os.walk('cached/'), (None, None, []))[1]
|
sites = next(os.walk('cached/'), (None, None, []))[1]
|
||||||
@@ -105,7 +107,7 @@ def server(http_port):
|
|||||||
conn.close()
|
conn.close()
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print("SERVER_HTTP FALLED")
|
ic("SERVER_HTTP FALLED")
|
||||||
logging.critical(e, exc_info=True)
|
logging.critical(e, exc_info=True)
|
||||||
|
|
||||||
|
|
||||||
@@ -121,11 +123,11 @@ def recv(s, data_out):
|
|||||||
okay = True
|
okay = True
|
||||||
except:
|
except:
|
||||||
pass
|
pass
|
||||||
print(data)
|
ic(data)
|
||||||
data_out.put(data)
|
data_out.put(data)
|
||||||
|
|
||||||
# op = operation
|
# op = operation
|
||||||
def client(port, op = "ping", host = 'bore.pub'):
|
def client(port, op = "ping", host = 'bore.del.pw'):
|
||||||
# Если порт не определён
|
# Если порт не определён
|
||||||
if not port:
|
if not port:
|
||||||
return None
|
return None
|
||||||
@@ -174,8 +176,11 @@ def client(port, op = "ping", host = 'bore.pub'):
|
|||||||
return "old"
|
return "old"
|
||||||
|
|
||||||
# Скачиваем файлы
|
# Скачиваем файлы
|
||||||
g_site = get(f"http://{host}:{str(port)}/{site}.zip")
|
try:
|
||||||
print('SIZE: ', g_site.headers['Content-Length']) # Размер
|
g_site = get(f"http://{host}:{str(port)}/{site}.zip")
|
||||||
|
except:
|
||||||
|
return 'error'
|
||||||
|
ic('SIZE: ', g_site.headers['Content-Length']) # Размер
|
||||||
|
|
||||||
with open(f"verify/{site}.zip", "wb") as f:
|
with open(f"verify/{site}.zip", "wb") as f:
|
||||||
f.write(g_site.content)
|
f.write(g_site.content)
|
||||||
@@ -212,10 +217,10 @@ def client(port, op = "ping", host = 'bore.pub'):
|
|||||||
our_ver = our_conf["ver"]
|
our_ver = our_conf["ver"]
|
||||||
# Если версия не новее - злоумышленник
|
# Если версия не новее - злоумышленник
|
||||||
if our_ver >= dest_ver:
|
if our_ver >= dest_ver:
|
||||||
print("[!] Обнаружена подмена версии сайта.")
|
ic("[!] Обнаружена подмена версии сайта.")
|
||||||
# Сохраняем ключ злоумышленника
|
# Сохраняем ключ злоумышленника
|
||||||
os.replace(f"verify/{site}.pem", f"verify/{site}.pem.FAKE")
|
os.replace(f"verify/{site}.pem", f"verify/{site}.pem.FAKE")
|
||||||
print(f"[!] Порт злоумышленника: {port}")
|
ic(f"[!] Порт злоумышленника: {port}")
|
||||||
# Удаляем фальшивые файлы
|
# Удаляем фальшивые файлы
|
||||||
os.remove(f"verify/{site}.zip")
|
os.remove(f"verify/{site}.zip")
|
||||||
os.remove(f"verify/{site}.sig")
|
os.remove(f"verify/{site}.sig")
|
||||||
@@ -233,11 +238,11 @@ def client(port, op = "ping", host = 'bore.pub'):
|
|||||||
copytree(f"verify/{site}", f"cached/{site}")
|
copytree(f"verify/{site}", f"cached/{site}")
|
||||||
rmtree(f"verify/{site}")
|
rmtree(f"verify/{site}")
|
||||||
else:
|
else:
|
||||||
print("[!] Обнаружена подмена сайта.")
|
ic("[!] Обнаружена подмена сайта.")
|
||||||
# Сохраняем ключ злоумышленника
|
# Сохраняем ключ злоумышленника
|
||||||
os.replace(f"verify/{site}.pem", f"verify/{site}.pem.FAKE")
|
os.replace(f"verify/{site}.pem", f"verify/{site}.pem.FAKE")
|
||||||
print(f"[!] Порт злоумышленника: {port}")
|
ic(f"[!] Порт злоумышленника: {port}")
|
||||||
print(f"[!] Ключ (вероятно) злоумышленника сохранён в verify/{site}.pem.FAKE\n")
|
ic(f"[!] Ключ (вероятно) злоумышленника сохранён в verify/{site}.pem.FAKE\n")
|
||||||
# Удаляем фальшивые файлы
|
# Удаляем фальшивые файлы
|
||||||
os.remove(f"verify/{site}.zip")
|
os.remove(f"verify/{site}.zip")
|
||||||
os.remove(f"verify/{site}.sig")
|
os.remove(f"verify/{site}.sig")
|
||||||
|
|||||||
@@ -1,17 +0,0 @@
|
|||||||
from os import system, name
|
|
||||||
from network import port_gen
|
|
||||||
|
|
||||||
port = input("Введите порт: ")
|
|
||||||
dest = port_gen(25300, 25500)
|
|
||||||
|
|
||||||
print(f"\nУдалённый ПОРТ: {dest}")
|
|
||||||
print("\n[!] Не закрывайте это окно [!]\n")
|
|
||||||
|
|
||||||
if name == "posix":
|
|
||||||
system(f"./bore local {port} --to bore.pub --port {dest}")
|
|
||||||
elif name == "nt":
|
|
||||||
system(f"bore.exe local {port} --to bore.pub --port {dest}")
|
|
||||||
else:
|
|
||||||
print("Увы, вероятно Ваша ОС не поддерживается.")
|
|
||||||
print("Завершение работы...")
|
|
||||||
exit()
|
|
||||||
@@ -1,24 +1,27 @@
|
|||||||
from os import system, name
|
from os import system
|
||||||
from threading import Thread
|
from threading import Thread
|
||||||
from time import sleep
|
from time import sleep
|
||||||
|
|
||||||
from status import *
|
from status import *
|
||||||
|
from db import read
|
||||||
|
|
||||||
global http_out ; http_out = None
|
global http_out ; http_out = None
|
||||||
def proxy_http(port):
|
def proxy_http(port):
|
||||||
global http_out
|
global http_out
|
||||||
if name == "posix":
|
os = read()['os']
|
||||||
http_out = system(f"./bore local 8000 --to bore.pub --port {port}")
|
if os == 'Linux':
|
||||||
elif name == "nt":
|
http_out = system(f'./bore local 8000 --to bore.del.pw --port {port}')
|
||||||
http_out = system(f"bore local 8000 --to bore.pub --port {port}")
|
elif os == 'Windows' or os == 'Android':
|
||||||
|
http_out = system(f'bore local 8000 --to bore.del.pw --port {port}')
|
||||||
|
|
||||||
global serv_out ; serv_out = None
|
global serv_out ; serv_out = None
|
||||||
def proxy_serv(port):
|
def proxy_serv(port):
|
||||||
global serv_out
|
global serv_out
|
||||||
if name == "posix":
|
os = read()['os']
|
||||||
http_out = system(f"./bore local 8001 --to bore.pub --port {port}")
|
if os == 'Linux':
|
||||||
elif name == "nt":
|
http_out = system(f'./bore local 8001 --to bore.del.pw --port {port}')
|
||||||
http_out = system(f"bore local 8001 --to bore.pub --port {port}")
|
elif os == 'Windows' or os == 'Android':
|
||||||
|
http_out = system(f'bore local 8001 --to bore.del.pw --port {port}')
|
||||||
|
|
||||||
|
|
||||||
def watch_http(port):
|
def watch_http(port):
|
||||||
|
|||||||
@@ -2,3 +2,4 @@ cryptography
|
|||||||
requests
|
requests
|
||||||
tqdm
|
tqdm
|
||||||
dash
|
dash
|
||||||
|
icecream
|
||||||
|
|||||||
@@ -1,51 +1,68 @@
|
|||||||
from os import system, name
|
from os import system
|
||||||
from urllib.request import urlretrieve as download
|
from urllib.request import urlretrieve as download
|
||||||
|
|
||||||
from db import *
|
from db import *
|
||||||
config = {}
|
|
||||||
|
|
||||||
# Устанавливаем зависимости
|
print('''1. Linux
|
||||||
system("pip install -r requirements.txt")
|
2. Windows
|
||||||
|
3. Android (Termux)''')
|
||||||
|
raw_os = input('ОС установки >> ')
|
||||||
|
oses = {'1': 'Linux', '2': 'Windows', '3': 'Android'}
|
||||||
|
os = oses[raw_os]
|
||||||
|
|
||||||
# Скачиваем bore (для проброса портов)
|
# Записываем ОС в конфиг
|
||||||
if name == "posix":
|
conf = read()
|
||||||
download("https://github.com/ekzhang/bore/releases/download/v0.5.0/bore-v0.5.0-x86_64-unknown-linux-musl.tar.gz", "bore.tar.gz")
|
conf['os'] = os
|
||||||
system("tar -zxvf bore.tar.gz")
|
write(conf)
|
||||||
system("rm -rf bore.tar.gz")
|
|
||||||
|
|
||||||
import getpass
|
if os == 'Android':
|
||||||
user = getpass.getuser()
|
print('''---
|
||||||
|
Устанавливаем зависимости rust...
|
||||||
|
---''')
|
||||||
|
system('pkg install rust')
|
||||||
|
|
||||||
#system("mkdir ~/.streamlit")
|
print('''---
|
||||||
#with open(f"/home/{user}/.streamlit/credentials.toml", "w") as f:
|
[1/3] Устанавливаем зависимости Python...
|
||||||
# f.write('[general]\nemail = "a@a.a"')
|
---''')
|
||||||
#f.close()
|
system('pip install -r requirements.txt')
|
||||||
elif name == "nt":
|
|
||||||
|
print('''---
|
||||||
|
[2/3] Скачиваем обратный прокси...
|
||||||
|
---''')
|
||||||
|
if os == 'Linux':
|
||||||
|
download('https://github.com/ekzhang/bore/releases/download/v0.5.0/bore-v0.5.0-x86_64-unknown-linux-musl.tar.gz', 'bore.tar.gz')
|
||||||
|
system('tar -zxvf bore.tar.gz')
|
||||||
|
system('rm -rf bore.tar.gz')
|
||||||
|
elif os == 'Windows':
|
||||||
from shutil import unpack_archive as unpack
|
from shutil import unpack_archive as unpack
|
||||||
download("https://github.com/ekzhang/bore/releases/download/v0.5.0/bore-v0.5.0-x86_64-pc-windows-msvc.zip", "bore.zip")
|
download('https://github.com/ekzhang/bore/releases/download/v0.5.0/bore-v0.5.0-x86_64-pc-windows-msvc.zip', 'bore.zip')
|
||||||
unpack("bore.zip")
|
unpack('bore.zip')
|
||||||
system("del bore.zip")
|
system('del bore.zip')
|
||||||
|
elif os == 'Android':
|
||||||
#system("mkdir C:\\Users\\windows\\.streamlit")
|
system('pkg install bore')
|
||||||
#with open("C:\\Users\\windows\\.streamlit\\credentials.toml", "w") as f:
|
|
||||||
# f.write('[general]\nemail = "a@a.a"')
|
|
||||||
#f.close()
|
|
||||||
else:
|
else:
|
||||||
print("Увы, вероятно Ваша ОС не поддерживается.")
|
print('Увы, вероятно Ваша ОС не поддерживается.')
|
||||||
print("Завершение работы...")
|
print('Завершение работы...')
|
||||||
exit()
|
exit()
|
||||||
|
|
||||||
# Создаём папку для кэшированных сайтов
|
print('''---
|
||||||
system("mkdir cached")
|
[3/3] Создаём папки для работы...
|
||||||
system("mkdir verify")
|
---''')
|
||||||
system("mkdir mysites")
|
system('mkdir cached')
|
||||||
|
system('mkdir verify')
|
||||||
|
system('mkdir mysites')
|
||||||
|
|
||||||
# TODO
|
# TODO
|
||||||
#print("Максимальный размер для кэшированных файлов. (в гигабайтах)")
|
#print('Максимальный размер для кэшированных файлов. (в гигабайтах)')
|
||||||
#print("Укажите 0 для отключения ограничения.")
|
#print('Укажите 0 для отключения ограничения.')
|
||||||
#max = input(">> ")
|
#max = input('>> ')
|
||||||
# Записываем в конфиг
|
# Записываем в конфиг
|
||||||
#config["max"] = max
|
#config['max'] = max
|
||||||
#write(config)
|
#write(config)
|
||||||
|
|
||||||
print("\nЧтобы подключится к jetwork выполните: python main.py")
|
print('''
|
||||||
|
---
|
||||||
|
Установка завершена!
|
||||||
|
|
||||||
|
Чтобы подключится к jetwork выполните: python main.py
|
||||||
|
---''')
|
||||||
|
|||||||
+109
-114
@@ -1,4 +1,4 @@
|
|||||||
from os import system, mkdir
|
from os import system, mkdir, walk
|
||||||
from db import *
|
from db import *
|
||||||
from shutil import copyfile, make_archive, rmtree, copytree
|
from shutil import copyfile, make_archive, rmtree, copytree
|
||||||
from tqdm import tqdm
|
from tqdm import tqdm
|
||||||
@@ -6,176 +6,171 @@ from time import sleep
|
|||||||
|
|
||||||
from verify import *
|
from verify import *
|
||||||
from network import *
|
from network import *
|
||||||
|
from domain_check import domain_list
|
||||||
|
|
||||||
print("(1) Создать сайт")
|
def your_sites():
|
||||||
print("(2) Обновить сайт")
|
sites = {}; num = 1
|
||||||
print("(3) Сменить тип")
|
for i in next(walk('cached/'), (None, None, []))[1]:
|
||||||
print("(4) Авто-раздача сайта")
|
sites[str(num)] = i
|
||||||
print("Enter для просто публикации.")
|
print(f'{str(num)}. {i}')
|
||||||
|
num += 1
|
||||||
|
return sites
|
||||||
|
|
||||||
op = input(">> ")
|
print('(1) Создать сайт')
|
||||||
|
print('(2) Обновить сайт')
|
||||||
|
print('(3) Сменить тип')
|
||||||
|
print('(4) Авто-раздача сайта')
|
||||||
|
print('Enter для просто публикации.')
|
||||||
|
|
||||||
if op == "1":
|
op = input('>> ')
|
||||||
|
|
||||||
|
if op == '1':
|
||||||
from domain_check import *
|
from domain_check import *
|
||||||
|
|
||||||
print("\nДомены: .jet, .jw, .404, .dash, .awesome, .mirror")
|
print(f'\nДоступные 1 lvl домены: {domain_list()}')
|
||||||
domain = input("Домен сайта: ")
|
domain = input('Домен сайта: ')
|
||||||
if not domain_ok(domain):
|
if not domain_ok(domain):
|
||||||
print("Неправильный формат или домен.")
|
print('Неправильный формат или домен.')
|
||||||
exit()
|
exit()
|
||||||
print("\n(1) Статичный / (2) Динамический")
|
print('\n(1) Статичный / (2) Динамический')
|
||||||
type = input("Тип: ")
|
type = input('Тип: ')
|
||||||
|
|
||||||
# Создаём папку и ключи для подписи
|
# Создаём папку и ключи для подписи
|
||||||
mkdir(f"mysites/{domain}")
|
mkdir(f'mysites/{domain}')
|
||||||
key_gen(f"mysites/{domain}")
|
key_gen(f'mysites/{domain}')
|
||||||
|
|
||||||
if type == "1":
|
if type == '1':
|
||||||
conf = {"type": "static", "ver": 1}
|
conf = {'type': 'static', 'ver': 1}
|
||||||
print("ПРИМЕЧАНИЕ: index.html обязателен.")
|
print('\nПРИМЕЧАНИЕ: index.html обязателен.')
|
||||||
elif type == "2":
|
|
||||||
port = input("Порт сервера: ")
|
|
||||||
conf = {"type": "dynamic", "ver": 1, "port": int(port)}
|
|
||||||
write(conf, f"mysites/{domain}/config.json")
|
|
||||||
|
|
||||||
if type == "1":
|
|
||||||
# Создаём index.html для загрузки сайта
|
# Создаём index.html для загрузки сайта
|
||||||
with open(f"mysites/{domain}/index.html", "w") as f:
|
with open(f'mysites/{domain}/index.html', 'w') as f:
|
||||||
f.write("<h1> Hello jetwork! </h1>")
|
f.write('<h1> Hello jetwork! </h1>')
|
||||||
f.close()
|
f.close()
|
||||||
|
elif type == '2':
|
||||||
|
port = input('Порт сервера: ')
|
||||||
|
conf = {'type': 'dynamic', 'ver': 1, 'port': int(port)}
|
||||||
|
write(conf, f'mysites/{domain}/config.json')
|
||||||
|
|
||||||
# Архивируем и создаём сигнатуру для подтверждения неизменности архива
|
# Архивируем и создаём сигнатуру для подтверждения неизменности архива
|
||||||
make_archive(f"mysites/{domain}", "zip", f"mysites/{domain}")
|
make_archive(f'mysites/{domain}', 'zip', f'mysites/{domain}')
|
||||||
sign(f"mysites/{domain}.zip", f"mysites/{domain}.key", f"mysites/{domain}")
|
sign(f'mysites/{domain}.zip', f'mysites/{domain}.key', f'mysites/{domain}')
|
||||||
|
|
||||||
elif op == "2":
|
elif op == '2':
|
||||||
domain = input("\nДомен сайта: ")
|
print()
|
||||||
if not os.path.exists(f"mysites/{domain}"):
|
sites = your_sites()
|
||||||
print("Не существует такого сайта.")
|
|
||||||
exit()
|
|
||||||
|
|
||||||
conf = read(f"mysites/{domain}/config.json")
|
domain = sites[input('Домен сайта: ')]
|
||||||
type = conf["type"]
|
|
||||||
if type == "dynamic":
|
conf = read(f'mysites/{domain}/config.json')
|
||||||
port = input("Порт сервера: ")
|
type = conf['type']
|
||||||
conf["port"] = port
|
if type == 'dynamic':
|
||||||
write(conf, f"mysites/{domain}/config.json")
|
port = input('Порт сервера: ')
|
||||||
|
conf['port'] = port
|
||||||
|
write(conf, f'mysites/{domain}/config.json')
|
||||||
|
|
||||||
# Обновляем версию
|
# Обновляем версию
|
||||||
conf = read(f"mysites/{domain}/config.json")
|
conf = read(f'mysites/{domain}/config.json')
|
||||||
conf["ver"] = conf["ver"] + 1
|
conf['ver'] = conf['ver'] + 1
|
||||||
write(conf, f"mysites/{domain}/config.json")
|
write(conf, f'mysites/{domain}/config.json')
|
||||||
|
|
||||||
# Архивируем и создаём сигнатуру для подтверждения неизменности архива
|
# Архивируем и создаём сигнатуру для подтверждения неизменности архива
|
||||||
make_archive(f"mysites/{domain}", "zip", f"mysites/{domain}")
|
make_archive(f'mysites/{domain}', 'zip', f'mysites/{domain}')
|
||||||
sign(f"mysites/{domain}.zip", f"mysites/{domain}.key", f"mysites/{domain}")
|
sign(f'mysites/{domain}.zip', f'mysites/{domain}.key', f'mysites/{domain}')
|
||||||
|
|
||||||
elif op == "3":
|
elif op == '3':
|
||||||
from os import rmdir
|
from os import rmdir
|
||||||
|
|
||||||
domain = input("\nДомен сайта: ")
|
print()
|
||||||
if not os.path.exists(f"mysites/{domain}"):
|
sites = your_sites()
|
||||||
print("Не существует такого сайта.")
|
domain = sites[input('Домен сайта: ')]
|
||||||
exit()
|
|
||||||
|
|
||||||
print("\n(1) Статичный / (2) Динамический")
|
print('\n(1) Статичный / (2) Динамический')
|
||||||
type = input("Тип: ")
|
type = input('Тип: ')
|
||||||
|
|
||||||
if type == "1":
|
if type == '1':
|
||||||
conf = read(f"mysites/{domain}/config.json")
|
conf = read(f'mysites/{domain}/config.json')
|
||||||
conf["type"] = "static"
|
conf['type'] = 'static'
|
||||||
conf.pop("port")
|
conf.pop('port')
|
||||||
with open(f"mysites/{domain}/index.html", "w") as f:
|
with open(f'mysites/{domain}/index.html', 'w') as f:
|
||||||
f.write("<h1> Hello jetwork! </h1>")
|
f.write('<h1> Hello jetwork! </h1>')
|
||||||
f.close()
|
f.close()
|
||||||
elif type == "2":
|
elif type == '2':
|
||||||
conf = read(f"mysites/{domain}/config.json")
|
conf = read(f'mysites/{domain}/config.json')
|
||||||
port = input("Порт сервера: ")
|
port = input('Порт сервера: ')
|
||||||
|
|
||||||
clean = input("Удалить все лишние файлы сайта (y/n): ")
|
clean = input('Удалить все лишние файлы сайта (y/n): ')
|
||||||
if clean == "y":
|
if clean == 'y':
|
||||||
# Удаляем папку, сохраняем конфиг и копируем публичный ключ
|
# Удаляем папку, сохраняем конфиг и копируем публичный ключ
|
||||||
rmtree(f"mysites/{domain}")
|
rmtree(f'mysites/{domain}')
|
||||||
sleep(0.1)
|
sleep(0.1)
|
||||||
system(f"mkdir mysites/{domain}")
|
system(f'mkdir mysites/{domain}')
|
||||||
|
|
||||||
conf["type"] = "dynamic"
|
conf['type'] = 'dynamic'
|
||||||
conf["port"] = int(port)
|
conf['port'] = int(port)
|
||||||
write(conf, f"mysites/{domain}/config.json")
|
write(conf, f'mysites/{domain}/config.json')
|
||||||
|
|
||||||
# Обновляем версию
|
# Обновляем версию
|
||||||
conf = read(f"mysites/{domain}/config.json")
|
conf = read(f'mysites/{domain}/config.json')
|
||||||
conf["ver"] = conf["ver"] + 1
|
conf['ver'] = conf['ver'] + 1
|
||||||
write(conf, f"mysites/{domain}/config.json")
|
write(conf, f'mysites/{domain}/config.json')
|
||||||
|
|
||||||
# Архивируем и создаём сигнатуру для подтверждения неизменности архива
|
# Архивируем и создаём сигнатуру для подтверждения неизменности архива
|
||||||
make_archive(f"mysites/{domain}", "zip", f"mysites/{domain}")
|
make_archive(f'mysites/{domain}', 'zip', f'mysites/{domain}')
|
||||||
sign(f"mysites/{domain}.zip", f"mysites/{domain}.key", f"mysites/{domain}")
|
sign(f'mysites/{domain}.zip', f'mysites/{domain}.key', f'mysites/{domain}')
|
||||||
|
|
||||||
elif op == "4":
|
elif op == '4':
|
||||||
domain = input("\nДомен сайта: ")
|
print()
|
||||||
if not os.path.exists(f"mysites/{domain}"):
|
sites = your_sites()
|
||||||
print("Не существует такого сайта.")
|
domain = sites[input('Домен сайта: ')]
|
||||||
exit()
|
|
||||||
|
|
||||||
print("\nВведите ваш порт сервера (при запуске main.py)")
|
serv_port = int( read()['our_port'] )
|
||||||
serv_port = int(input(">> "))
|
http_port = client(serv_port, f'is_{domain}')
|
||||||
http_port = client(serv_port, f"is_{domain}")
|
|
||||||
|
|
||||||
print("\nСтарт вечной раздачи...")
|
print('\nСтарт вечной раздачи...')
|
||||||
while True:
|
while True:
|
||||||
ports = port_check(serv_port)
|
ports = port_check(serv_port)
|
||||||
sleep(1)
|
sleep(1)
|
||||||
for port in tqdm(ports):
|
for port in tqdm(ports):
|
||||||
client(port, f"publish_{domain}<>{http_port}")
|
client(port, f'publish_{domain}<>{http_port}')
|
||||||
sleep(5)
|
sleep(5)
|
||||||
|
|
||||||
elif op == "":
|
host = 'bore.del.pw'
|
||||||
domain = input("\nДомен сайта: ")
|
# Проверяем тип сайта
|
||||||
if not os.path.exists(f"mysites/{domain}"):
|
type = read(f'mysites//{domain}/config.json')['type']
|
||||||
print("Не существует такого сайта.")
|
# Если динамический - вставляем спец страницу
|
||||||
exit()
|
if type == 'dynamic':
|
||||||
pub = "y"
|
port = read(f'mysites//{domain}/config.json')['port']
|
||||||
|
with open(f'mysites//{domain}/index.html', 'w') as f:
|
||||||
|
f.write(f"<iframe src='http://{host}:{port}' style='position:fixed; top:0; left:0; bottom:0; right:0; width:100%; height:100%; border:none; margin:0; padding:0; overflow:hidden; z-index:999999;'></iframe>")
|
||||||
|
f.close()
|
||||||
|
|
||||||
|
|
||||||
# Копируем файлы из mysites в cached
|
# Копируем файлы из mysites в cached
|
||||||
try:
|
try:
|
||||||
rmtree(f"cached/{domain}")
|
rmtree(f'cached/{domain}')
|
||||||
except:
|
except:
|
||||||
pass
|
pass
|
||||||
copytree(f"mysites/{domain}", f"cached/{domain}")
|
copytree(f'mysites/{domain}', f'cached/{domain}')
|
||||||
copyfile(f"mysites/{domain}.pem", f"cached/{domain}.pem")
|
copyfile(f'mysites/{domain}.pem', f'cached/{domain}.pem')
|
||||||
copyfile(f"mysites/{domain}.sig", f"cached/{domain}.sig")
|
copyfile(f'mysites/{domain}.sig', f'cached/{domain}.sig')
|
||||||
copyfile(f"mysites/{domain}.zip", f"cached/{domain}.zip")
|
copyfile(f'mysites/{domain}.zip', f'cached/{domain}.zip')
|
||||||
|
|
||||||
|
|
||||||
host = "jetwork.404.mn"
|
if op != '':
|
||||||
# Проверяем тип сайта
|
print('\nОпубликовать сайт?')
|
||||||
type = read(f"cached/{domain}/config.json")["type"]
|
pub = input('y/n >> ')
|
||||||
# Если динамический
|
|
||||||
if type == "dynamic":
|
|
||||||
port = read(f"cached/{domain}/config.json")["port"]
|
|
||||||
with open(f"cached/{domain}/index.html", "w") as f:
|
|
||||||
f.write(f'<iframe src="http://{host}:{port}" style="position:fixed; top:0; left:0; bottom:0; right:0; width:100%; height:100%; border:none; margin:0; padding:0; overflow:hidden; z-index:999999;"></iframe>')
|
|
||||||
f.close()
|
|
||||||
|
|
||||||
|
if pub == 'n':
|
||||||
if op != "":
|
|
||||||
print("Опубликовать сайт?")
|
|
||||||
pub = input("y/n >> ")
|
|
||||||
|
|
||||||
if pub == "n":
|
|
||||||
exit()
|
exit()
|
||||||
|
|
||||||
print("Введите ваш порт сервера (при запуске main.py)")
|
serv_port = int( read()['our_port'] )
|
||||||
serv_port = int(input(">> "))
|
http_port = client(serv_port, f'is_{domain}')
|
||||||
http_port = client(serv_port, f"is_{domain}")
|
|
||||||
|
|
||||||
print("Получаем все порты...")
|
print('Получаем все порты...')
|
||||||
ports = port_check(serv_port)
|
ports = port_check(serv_port)
|
||||||
|
|
||||||
print(ports)
|
print(ports)
|
||||||
|
|
||||||
print("Публикуем сайт...")
|
print('Публикуем сайт...')
|
||||||
for port in tqdm(ports):
|
for port in tqdm(ports):
|
||||||
client(port, f"publish_{domain}<>{http_port}")
|
client(port, f'publish_{domain}<>{http_port}')
|
||||||
|
|||||||
@@ -0,0 +1,10 @@
|
|||||||
|
while true
|
||||||
|
do
|
||||||
|
killall python
|
||||||
|
sleep 1s
|
||||||
|
killall python #Чтоб наверняка
|
||||||
|
sleep 60s # Ждём, чтобы не было ошибки при перезапуске "данный порт уже используется"
|
||||||
|
|
||||||
|
nohup python srv_main.py &
|
||||||
|
sleep 6h
|
||||||
|
done
|
||||||
@@ -0,0 +1,79 @@
|
|||||||
|
from dash import Dash, dcc, html, Input, Output, callback
|
||||||
|
app = Dash(__name__, title='Jetwork', update_title=None)
|
||||||
|
|
||||||
|
from db import *
|
||||||
|
from status import *
|
||||||
|
|
||||||
|
from os import walk
|
||||||
|
from os import system as sys
|
||||||
|
from platform import system
|
||||||
|
from threading import Thread
|
||||||
|
|
||||||
|
app.layout = html.Div([ html.Div([
|
||||||
|
|
||||||
|
dcc.ConfirmDialog(id='shut_mess', message='Ты совсем гений?'),
|
||||||
|
html.Button("Выключить клиент", className='off_btn', n_clicks=0, id='off_btn'),
|
||||||
|
html.Div([], id='our_port', className='our_port'),
|
||||||
|
html.Div([], id='servers', className='servers'),
|
||||||
|
html.Div([], id='sites', className='sites'),
|
||||||
|
dcc.Dropdown(options=[], id='search', placeholder='Поиск...'),
|
||||||
|
|
||||||
|
dcc.Interval(id='interval-component', interval=1*1000, n_intervals=0)
|
||||||
|
|
||||||
|
], className='main')], className='content')
|
||||||
|
|
||||||
|
|
||||||
|
# Кнопка выключения
|
||||||
|
@callback(
|
||||||
|
Output('shut_mess', 'displayed'),
|
||||||
|
Input('off_btn', 'n_clicks'),
|
||||||
|
prevent_initial_call=True
|
||||||
|
)
|
||||||
|
def shut_btn(n_clicks):
|
||||||
|
return True
|
||||||
|
|
||||||
|
# Обновление нашего порта (зачем?)
|
||||||
|
@callback(Output('our_port', 'children'),
|
||||||
|
Input('interval-component', 'n_intervals'))
|
||||||
|
def update_our_port(n):
|
||||||
|
return f"Ваш порт: {read()['our_port']}"
|
||||||
|
|
||||||
|
# Обновление доступных узлов
|
||||||
|
@callback(Output('servers', 'children'),
|
||||||
|
Input('interval-component', 'n_intervals'))
|
||||||
|
def update_servers(n):
|
||||||
|
res = []
|
||||||
|
for i in read()['ports']:
|
||||||
|
res.append(html.Div([i], className='serv_elem'))
|
||||||
|
return res
|
||||||
|
|
||||||
|
# Обновление доступных сайтов
|
||||||
|
@callback(Output('sites', 'children'),
|
||||||
|
Input('interval-component', 'n_intervals'),
|
||||||
|
Input('search', 'value'))
|
||||||
|
def update_sites(n, s_val):
|
||||||
|
# Префикс
|
||||||
|
base_url = read()['base_url']
|
||||||
|
# Если есть элемент в поиске
|
||||||
|
if s_val:
|
||||||
|
return html.Div([ dcc.Link(children=i, href=f'{base_url}/{s_val}',
|
||||||
|
target='_blank') ], className='sites_elem')
|
||||||
|
|
||||||
|
res = []
|
||||||
|
for i in next(walk('cached/'), (None, None, []))[1]:
|
||||||
|
conf = read(f'cached/{i}/config.json')
|
||||||
|
res.append(html.Div([ dcc.Link(children=i, href=f'http://{i}',
|
||||||
|
target='_blank') ], className='sites_elem'))
|
||||||
|
return res
|
||||||
|
|
||||||
|
# Обновление доступных сайтов в поиске
|
||||||
|
@callback(Output('search', 'options'),
|
||||||
|
Input('interval-component', 'n_intervals'))
|
||||||
|
def update_search(n):
|
||||||
|
res = []
|
||||||
|
for i in next(walk('cached/'), (None, None, []))[1]:
|
||||||
|
res.append(i)
|
||||||
|
return res
|
||||||
|
|
||||||
|
#app.run(debug=True, port = 5555)
|
||||||
|
app.run(debug=False, host = '0.0.0.0', port = 5555)
|
||||||
+9
-3
@@ -7,7 +7,9 @@ from multiprocessing import Process
|
|||||||
from network import *
|
from network import *
|
||||||
from updater import *
|
from updater import *
|
||||||
from proxy import *
|
from proxy import *
|
||||||
|
from web_proxy import *
|
||||||
from status import *
|
from status import *
|
||||||
|
|
||||||
from db import *
|
from db import *
|
||||||
|
|
||||||
#
|
#
|
||||||
@@ -21,7 +23,7 @@ def main():
|
|||||||
print('Проверка обновлений...')
|
print('Проверка обновлений...')
|
||||||
system('git pull')
|
system('git pull')
|
||||||
print('Перезагрузка скрипта...')
|
print('Перезагрузка скрипта...')
|
||||||
system('python main.py updated')
|
system('python srv_main.py updated')
|
||||||
exit()
|
exit()
|
||||||
print('\nУспешно перезагружено!')
|
print('\nУспешно перезагружено!')
|
||||||
|
|
||||||
@@ -55,15 +57,19 @@ def main():
|
|||||||
#updater = Thread(target = update_demon, args=(serv_port,))
|
#updater = Thread(target = update_demon, args=(serv_port,))
|
||||||
#updater.start()
|
#updater.start()
|
||||||
|
|
||||||
|
# Прокси для браузера
|
||||||
|
http_proxy = Thread(target = web_proxy)
|
||||||
|
http_proxy.start()
|
||||||
|
|
||||||
# Стартуем интерфейс
|
# Стартуем интерфейс
|
||||||
system('python interface.py')
|
system('python srv_interface.py')
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
# Запускаем главный процесс, чтобы потом легко убить его
|
# Запускаем главный процесс, чтобы потом легко убить его
|
||||||
p = Process(target=main)
|
p = Process(target=main)
|
||||||
p.start()
|
p.start()
|
||||||
|
|
||||||
status_set(True) # Устанавливаем статус, что программа работает
|
status_set('work') # Устанавливаем статус, что программа работает
|
||||||
|
|
||||||
st = status_check()
|
st = status_check()
|
||||||
while st:
|
while st:
|
||||||
|
|||||||
@@ -1,8 +0,0 @@
|
|||||||
#
|
|
||||||
# Установка/проверка статуса завершения
|
|
||||||
#
|
|
||||||
|
|
||||||
import os
|
|
||||||
|
|
||||||
if not os.path.exists('status'):
|
|
||||||
|
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
killall ./srv.sh
|
||||||
|
killall python
|
||||||
|
killall bore
|
||||||
+7
-4
@@ -6,6 +6,9 @@ from network import *
|
|||||||
|
|
||||||
# Логирование ошибок
|
# Логирование ошибок
|
||||||
import logging
|
import logging
|
||||||
|
# Просто логирование
|
||||||
|
from icecream import ic
|
||||||
|
ic.disable() # Отключение логирования
|
||||||
|
|
||||||
def update_demon(serv_port):
|
def update_demon(serv_port):
|
||||||
while True:
|
while True:
|
||||||
@@ -40,23 +43,23 @@ def update_demon(serv_port):
|
|||||||
if check[0] == el:
|
if check[0] == el:
|
||||||
# Сверяем версии
|
# Сверяем версии
|
||||||
if check[1] >= ver:
|
if check[1] >= ver:
|
||||||
print("Ver_ok: ", el)
|
ic("Ver_ok: ", el)
|
||||||
pass
|
pass
|
||||||
else:
|
else:
|
||||||
# Если версия новее
|
# Если версия новее
|
||||||
print("Ver_new: ", el)
|
ic("Ver_new: ", el)
|
||||||
http_port = client(port, f"is_{el}")
|
http_port = client(port, f"is_{el}")
|
||||||
client(http_port, f"get_{el}")
|
client(http_port, f"get_{el}")
|
||||||
found = True
|
found = True
|
||||||
break # Если нашли - выходим
|
break # Если нашли - выходим
|
||||||
|
|
||||||
if not found:
|
if not found:
|
||||||
print("Not_found: ", el)
|
ic("Not_found: ", el)
|
||||||
http_port = client(port, f"is_{el}")
|
http_port = client(port, f"is_{el}")
|
||||||
client(http_port, f"get_{el}")
|
client(http_port, f"get_{el}")
|
||||||
except:
|
except:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print("UPDATER FALLED")
|
ic("UPDATER FALLED")
|
||||||
logging.critical(e, exc_info=True)
|
logging.critical(e, exc_info=True)
|
||||||
|
|||||||
@@ -0,0 +1,82 @@
|
|||||||
|
import http.server
|
||||||
|
import socketserver
|
||||||
|
import urllib.request
|
||||||
|
import logging
|
||||||
|
from os.path import exists
|
||||||
|
|
||||||
|
from db import *
|
||||||
|
base_url = read()['base_url']
|
||||||
|
|
||||||
|
# Логирование
|
||||||
|
from icecream import ic
|
||||||
|
ic.disable() # Выключить отладку
|
||||||
|
|
||||||
|
class Proxy(http.server.SimpleHTTPRequestHandler):
|
||||||
|
# Отключение всех сообщений (чтобы не забивать вывод)
|
||||||
|
def log_message(self, format, *args):
|
||||||
|
pass
|
||||||
|
def do_GET(self):
|
||||||
|
ic(f"Request for: {self.path}")
|
||||||
|
|
||||||
|
# 'js-check.jet/favicon.ico' -> '127.0.0.1:8000/favicon.ico'
|
||||||
|
target = self.path
|
||||||
|
domain = target[7:]
|
||||||
|
domain = domain[:domain.find('/')]
|
||||||
|
|
||||||
|
if not exists(f'cached/{domain}'):
|
||||||
|
self.send_error(404, f"Site not found")
|
||||||
|
return 404
|
||||||
|
|
||||||
|
# Если статичный
|
||||||
|
if read(f'cached/{domain}/config.json')['type'] == 'static':
|
||||||
|
target = f'{base_url}/{target[7:]}' # http://127.0.0.1:8000 / js-check.jet
|
||||||
|
# Если динамический
|
||||||
|
elif read(f'cached/{domain}/config.json')['type'] == 'dynamic':
|
||||||
|
port = read(f'cached/{domain}/config.json')['port']
|
||||||
|
target = f'http://bore.del.pw:{port}/{target.replace(f"http://{domain}/", "")}'
|
||||||
|
|
||||||
|
ic(f"Modded request: {target}")
|
||||||
|
|
||||||
|
# Направление запроса по адресу
|
||||||
|
try:
|
||||||
|
with urllib.request.urlopen(target) as response:
|
||||||
|
self.send_response(response.getcode())
|
||||||
|
self.send_header("Content-type", response.headers.get_content_type())
|
||||||
|
self.end_headers()
|
||||||
|
self.wfile.write(response.read())
|
||||||
|
except Exception as e:
|
||||||
|
self.send_error(500, f"Error: {str(e)}")
|
||||||
|
|
||||||
|
def do_POST(self):
|
||||||
|
ic(f"Request for: {self.path}")
|
||||||
|
|
||||||
|
if not exists(f'cached/{domain}'):
|
||||||
|
self.send_error(404, f"Site not found")
|
||||||
|
return 404
|
||||||
|
|
||||||
|
if read(f'cached/{domain}/config.json')['type'] == 'static':
|
||||||
|
target = f'{base_url}/{target[7:]}' # http://127.0.0.1:8000 / js-check.jet
|
||||||
|
elif read(f'cached/{domain}/config.json')['type'] == 'dynamic':
|
||||||
|
port = read(f'cached/{domain}/config.json')['port']
|
||||||
|
target = f'http://bore.del.pw:{port}/{target.replace(f"http://{domain}/", "")}'
|
||||||
|
|
||||||
|
ic(f"Modded request: {target}")
|
||||||
|
|
||||||
|
# Направление запроса по адресу
|
||||||
|
try:
|
||||||
|
content_length = int(self.headers['Content-Length'])
|
||||||
|
post_data = self.rfile.read(content_length)
|
||||||
|
req = urllib.request.Request(self.path, data=post_data, method='POST')
|
||||||
|
with urllib.request.urlopen(req) as response:
|
||||||
|
self.send_response(response.getcode())
|
||||||
|
self.send_header("Content-type", response.headers.get_content_type())
|
||||||
|
self.end_headers()
|
||||||
|
self.wfile.write(response.read())
|
||||||
|
except Exception as e:
|
||||||
|
self.send_error(500, f"Error: {str(e)}")
|
||||||
|
|
||||||
|
def web_proxy():
|
||||||
|
PORT = 8080
|
||||||
|
with socketserver.TCPServer(("", PORT), Proxy) as httpd:
|
||||||
|
print(f"HTTP proxy on port {PORT}")
|
||||||
|
httpd.serve_forever()
|
||||||
Reference in New Issue
Block a user