Skip to content

Commit fce657a

Browse files
committed
init
0 parents  commit fce657a

27 files changed

+723
-0
lines changed

.gitignore

Lines changed: 160 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,160 @@
1+
# Byte-compiled / optimized / DLL files
2+
__pycache__/
3+
*.py[cod]
4+
*$py.class
5+
6+
# C extensions
7+
*.so
8+
9+
# Distribution / packaging
10+
.Python
11+
build/
12+
develop-eggs/
13+
dist/
14+
downloads/
15+
eggs/
16+
.eggs/
17+
lib/
18+
lib64/
19+
parts/
20+
sdist/
21+
var/
22+
wheels/
23+
share/python-wheels/
24+
*.egg-info/
25+
.installed.cfg
26+
*.egg
27+
MANIFEST
28+
29+
# PyInstaller
30+
# Usually these files are written by a python script from a template
31+
# before PyInstaller builds the exe, so as to inject date/other infos into it.
32+
*.manifest
33+
*.spec
34+
35+
# Installer logs
36+
pip-log.txt
37+
pip-delete-this-directory.txt
38+
39+
# Unit test / coverage reports
40+
htmlcov/
41+
.tox/
42+
.nox/
43+
.coverage
44+
.coverage.*
45+
.cache
46+
nosetests.xml
47+
coverage.xml
48+
*.cover
49+
*.py,cover
50+
.hypothesis/
51+
.pytest_cache/
52+
cover/
53+
54+
# Translations
55+
*.mo
56+
*.pot
57+
58+
# Django stuff:
59+
*.log
60+
local_settings.py
61+
db.sqlite3
62+
db.sqlite3-journal
63+
64+
# Flask stuff:
65+
instance/
66+
.webassets-cache
67+
68+
# Scrapy stuff:
69+
.scrapy
70+
71+
# Sphinx documentation
72+
docs/_build/
73+
74+
# PyBuilder
75+
.pybuilder/
76+
target/
77+
78+
# Jupyter Notebook
79+
.ipynb_checkpoints
80+
81+
# IPython
82+
profile_default/
83+
ipython_config.py
84+
85+
# pyenv
86+
# For a library or package, you might want to ignore these files since the code is
87+
# intended to run in multiple environments; otherwise, check them in:
88+
# .python-version
89+
90+
# pipenv
91+
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92+
# However, in case of collaboration, if having platform-specific dependencies or dependencies
93+
# having no cross-platform support, pipenv may install dependencies that don't work, or not
94+
# install all needed dependencies.
95+
#Pipfile.lock
96+
97+
# poetry
98+
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
99+
# This is especially recommended for binary packages to ensure reproducibility, and is more
100+
# commonly ignored for libraries.
101+
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
102+
#poetry.lock
103+
104+
# pdm
105+
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
106+
#pdm.lock
107+
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
108+
# in version control.
109+
# https://pdm.fming.dev/#use-with-ide
110+
.pdm.toml
111+
112+
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
113+
__pypackages__/
114+
115+
# Celery stuff
116+
celerybeat-schedule
117+
celerybeat.pid
118+
119+
# SageMath parsed files
120+
*.sage.py
121+
122+
# Environments
123+
.env
124+
.venv
125+
env/
126+
venv/
127+
ENV/
128+
env.bak/
129+
venv.bak/
130+
131+
# Spyder project settings
132+
.spyderproject
133+
.spyproject
134+
135+
# Rope project settings
136+
.ropeproject
137+
138+
# mkdocs documentation
139+
/site
140+
141+
# mypy
142+
.mypy_cache/
143+
.dmypy.json
144+
dmypy.json
145+
146+
# Pyre type checker
147+
.pyre/
148+
149+
# pytype static type analyzer
150+
.pytype/
151+
152+
# Cython debug symbols
153+
cython_debug/
154+
155+
# PyCharm
156+
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
157+
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
158+
# and can be added to the global gitignore or merged into this file. For a more nuclear
159+
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
160+
.idea/

client/__init__.py

Whitespace-only changes.

client/tcp_forward_client.py

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
import ast
2+
import json
3+
import select
4+
import socket
5+
from threading import Thread, Lock
6+
from typing import List, Dict, Tuple, Set
7+
8+
import websocket
9+
10+
from common.logger_factory import LoggerFactory
11+
from constant.message_type_constnat import MessageTypeConstant
12+
from entity.message.message_entity import MessageEntity
13+
14+
15+
class TcpForwardClient:
16+
def __init__(self, name_to_addr: Dict[str, Tuple[str, int]], ws: websocket):
17+
self.uid_to_socket: Dict[str, socket.socket] = dict()
18+
self.socket_to_uid: Dict[socket.socket, str] = dict()
19+
self.name_to_addr: Dict[str, Tuple[str, int]] = name_to_addr
20+
self.uid_to_name: Dict[str, str] = dict()
21+
self.is_running = True
22+
self.ws = ws
23+
self.lock = Lock()
24+
25+
def start_forward(self):
26+
while self.is_running:
27+
with self.lock:
28+
s_list = list(self.uid_to_socket.values())
29+
if not s_list:
30+
continue
31+
try:
32+
rs, write_s, es = select.select(s_list, s_list, s_list, 5)
33+
except ValueError:
34+
LoggerFactory.get_logger().error('value error continue')
35+
for each in rs:
36+
uid = self.socket_to_uid[each]
37+
try:
38+
recv = each.recv(1024)
39+
except OSError:
40+
continue
41+
send_message: MessageEntity = {
42+
'type_': MessageTypeConstant.WEBSOCKET_OVER_TCP,
43+
'data': {
44+
'name': self.uid_to_name[uid],
45+
'data': recv.hex(),
46+
'uid': uid
47+
}
48+
}
49+
self.ws.send(json.dumps(send_message))
50+
if not recv:
51+
self.uid_to_socket.pop(uid)
52+
self.socket_to_uid.pop(each)
53+
each.close()
54+
55+
def create_socket(self, name: str, uid: str):
56+
with self.lock:
57+
if uid not in self.uid_to_socket:
58+
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
59+
s.connect(self.name_to_addr[name])
60+
self.uid_to_socket[uid] = s
61+
self.socket_to_uid[s] = uid
62+
self.uid_to_name[uid] = name
63+
64+
def close(self):
65+
with self.lock:
66+
for uid, s in self.uid_to_socket.items():
67+
s.close()
68+
self.uid_to_socket.clear()
69+
self.socket_to_uid.clear()
70+
self.uid_to_name.clear()
71+
self.is_running = False
72+
73+
def send_by_uid(self, uid, msg: bytes):
74+
self.uid_to_socket[uid].send(msg)

common/__init__.py

Whitespace-only changes.

common/logger_factory.py

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
import datetime
2+
import os
3+
import logging
4+
from logging.handlers import TimedRotatingFileHandler
5+
6+
from pytz import timezone
7+
8+
9+
class LoggerFactory:
10+
fmt = " %(asctime)s %(filename)s %(lineno)s %(funcName)s %(message)s"
11+
logger = logging.getLogger("loger")
12+
tz = 'Asia/Shanghai'
13+
14+
@classmethod
15+
def get_logger(cls):
16+
if hasattr(cls, '_log'):
17+
return cls.logger
18+
cls.logger.setLevel(logging.DEBUG)
19+
cls._add_file_handler(cls.logger)
20+
cls._add_console_handler(cls.logger)
21+
cls._log = cls.logger
22+
logging.Formatter.converter = lambda *args: datetime.datetime.now(tz=timezone(cls.tz)).timetuple()
23+
return cls.logger
24+
25+
@classmethod
26+
def _add_console_handler(cls, logger):
27+
handler = logging.StreamHandler()
28+
handler.setLevel(logging.DEBUG)
29+
handler.setFormatter(logging.Formatter(cls.fmt))
30+
logger.addHandler(handler)
31+
32+
@classmethod
33+
def _add_file_handler(cls, logger):
34+
os.makedirs('log', exist_ok=True)
35+
handler = TimedRotatingFileHandler(os.path.join('log', 'log.log'), when="d")
36+
formatter = logging.Formatter(cls.fmt)
37+
handler.setFormatter(formatter)
38+
logger.addHandler(handler)
39+
40+

config_c.json

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
{
2+
"server": {
3+
"port": 18888,
4+
"host": "192.168.32.229",
5+
"https": false,
6+
"password": "helloworld"
7+
},
8+
"client": [
9+
{
10+
"name": "ssh",
11+
"remote_port": 1222,
12+
"local_port": 22,
13+
"local_ip": "127.0.0.1"
14+
},
15+
{
16+
"name": "mongo",
17+
"remote_port": 1223,
18+
"local_port": 27017,
19+
"local_ip": "127.0.0.1"
20+
}
21+
]
22+
}

config_s.json

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
{
2+
"port": 18888,
3+
"password": "helloworld"
4+
}

constant/__init__.py

Whitespace-only changes.

constant/message_type_constnat.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
class MessageTypeConstant:
2+
PUSH_CONFIG = 'push_config'
3+
4+
ERROR = 'error'
5+
6+
WEBSOCKET_OVER_TCP = 'websocket_over_tcp'

context/__init__.py

Whitespace-only changes.

context/context_utils.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
c = {}
2+
3+
4+
class ContextUtils:
5+
_port = '_port'
6+
_password_key = '_password_key'
7+
8+
@classmethod
9+
def get_password(cls) -> str:
10+
return c.get(cls._password_key)
11+
12+
@classmethod
13+
def set_password(cls, data: str):
14+
c[cls._password_key] = data
15+
16+
@classmethod
17+
def set_port(cls, data):
18+
c[cls._port] = data
19+
20+
@classmethod
21+
def get_port(cls):
22+
return c[cls._port]

entity/__init__.py

Whitespace-only changes.

entity/client_config_entity.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
from typing import List
2+
3+
from typing_extensions import TypedDict
4+
5+
6+
class _ServerEntity(TypedDict):
7+
port: int
8+
host: str
9+
10+
https: bool
11+
password: str
12+
13+
14+
class _ClientEntity(TypedDict):
15+
name: str
16+
remote_port: int
17+
local_port: int
18+
local_ip: str
19+
20+
21+
class ClientConfigEntity(TypedDict):
22+
server: _ServerEntity
23+
client: List[_ClientEntity]

entity/message/__init__.py

Whitespace-only changes.

entity/message/message_entity.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
from typing import List, Union
2+
3+
from typing_extensions import TypedDict
4+
5+
from entity.message.push_config_entity import PushConfigEntity
6+
from entity.message.tcp_over_websocket_message import TcpOverWebsocketMessage
7+
8+
9+
class MessageEntity(TypedDict):
10+
type_: str
11+
data: Union[List[PushConfigEntity], TcpOverWebsocketMessage]

entity/message/push_config_entity.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
from typing_extensions import TypedDict
2+
3+
4+
class PushConfigEntity(TypedDict):
5+
name: str
6+
remote_port: int
7+
local_port: int
8+
local_ip: str
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
from typing_extensions import TypedDict
2+
3+
4+
class TcpOverWebsocketMessage(TypedDict):
5+
uid: str # 连接id
6+
name: str
7+
data: str

entity/server_config_entity.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
from typing_extensions import TypedDict
2+
3+
4+
class ServerConfigEntity(TypedDict):
5+
port: int
6+
password: str

exceptions/__init__.py

Whitespace-only changes.

0 commit comments

Comments
 (0)