Commit e1c4dc5e authored by ibuler's avatar ibuler

重构项目开始

parent 2461ab04
...@@ -4,3 +4,4 @@ ...@@ -4,3 +4,4 @@
.access_key .access_key
*.log *.log
logs/* logs/*
conf.py
This diff is collapsed.
# Jumpserver terminal
Jumpserver terminal is a sub app of Jumpserver.
It's implement a ssh server and a web terminal server,
User can connect them except jumpserver openssh server and connect.py
pre version.
## Install
$ git clone http://xxxx
## Setting
You need update config.py settings as you need, Be aware of:
*YOU MUST SET SOME CONFIG THAT CONFIG POINT*
They are:
NAME:
JUMPSERVER_URL:
SECRET_KEY:
Also some config you need kown:
SSH_HOST:
SSH_PORT:
## Start
# python ssh_server.py
When your start ssh server, It will register with jumpserver api,
Then you need login jumpserver with admin user, active it in <Terminal>
If all done, your can use your ssh tools connect it.
ssh user@host:port
from .app import Coco
import os
import time
import threading
from .config import Config
from .sshd import SSHServer
from .logger import create_logger
__version__ = '0.4.0'
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
class Coco:
config_class = Config
default_config = {
'NAME': 'coco',
'CORE_HOST': 'http://127.0.0.1:8080',
'DEBUG': True,
'BIND_HOST': '0.0.0.0',
'SSHD_PORT': 2222,
'WS_PORT': 5000,
'ACCESS_KEY': '',
'ACCESS_KEY_FILE': os.path.join(BASE_DIR, 'keys', '.access_key'),
'SECRET_KEY': None,
'LOG_LEVEL': 'INFO',
'LOG_DIR': os.path.join(BASE_DIR, 'logs'),
'ASSET_SORT_BY': 'hostname', # hostname, ip
'SSH_PASSWORD_AUTH': True,
'SSH_PUBLIC_KEY_AUTH': True,
'HEARTBEAT_INTERVAL': 5,
}
def __init__(self, name=None):
self.config = self.config_class(BASE_DIR, defaults=self.default_config)
self.sessions = []
if name:
self.name = name
else:
self.name = self.config['NAME']
self.make_logger()
def make_logger(self):
create_logger(self)
@staticmethod
def bootstrap():
pass
def heartbeat(self):
pass
def run_forever(self):
print(time.ctime())
print('Coco version %s, more see https://www.jumpserver.org' % __version__)
print('Starting ssh server at %(host)s:%(port)s' % {
'host': self.config['BIND_HOST'], 'port': self.config['SSHD_PORT']})
print('Starting websocket server at %(host)s:%(port)s' % {
'host': self.config['BIND_HOST'], 'port': self.config['WS_PORT']})
print('Quit the server with CONTROL-C.')
try:
self.run_sshd()
self.run_ws()
except KeyboardInterrupt:
self.shutdown()
def run_sshd(self):
thread = threading.Thread(target=SSHServer.run, args=(self,))
def run_ws(self):
pass
def shutdown(self):
pass
def monitor_session(self):
pass
# -*- coding: utf-8 -*-
"""
coco.config
~~~~~~~~~~~~
the configuration related objects.
copy from flask
:copyright: (c) 2015 by Armin Ronacher.
:license: BSD, see LICENSE for more details.
"""
import os
import types
import errno
import json
from werkzeug.utils import import_string
class ConfigAttribute(object):
"""Makes an attribute forward to the config"""
def __init__(self, name, get_converter=None):
self.__name__ = name
self.get_converter = get_converter
def __get__(self, obj, type=None):
if obj is None:
return self
rv = obj.config[self.__name__]
if self.get_converter is not None:
rv = self.get_converter(rv)
return rv
def __set__(self, obj, value):
obj.config[self.__name__] = value
class Config(dict):
"""Works exactly like a dict but provides ways to fill it from files
or special dictionaries. There are two common patterns to populate the
config.
Either you can fill the config from a config file::
app.config.from_pyfile('yourconfig.cfg')
Or alternatively you can define the configuration options in the
module that calls :meth:`from_object` or provide an import path to
a module that should be loaded. It is also possible to tell it to
use the same module and with that provide the configuration values
just before the call::
DEBUG = True
SECRET_KEY = 'development key'
app.config.from_object(__name__)
In both cases (loading from any Python file or loading from modules),
only uppercase keys are added to the config. This makes it possible to use
lowercase values in the config file for temporary values that are not added
to the config or to define the config keys in the same file that implements
the application.
Probably the most interesting way to load configurations is from an
environment variable pointing to a file::
app.config.from_envvar('YOURAPPLICATION_SETTINGS')
In this case before launching the application you have to set this
environment variable to the file you want to use. On Linux and OS X
use the export statement::
export YOURAPPLICATION_SETTINGS='/path/to/config/file'
On windows use `set` instead.
:param root_path: path to which files are read relative from. When the
config object is created by the application, this is
the application's :attr:`~flask.Flask.root_path`.
:param defaults: an optional dictionary of default values
"""
def __init__(self, root_path, defaults=None):
dict.__init__(self, defaults or {})
self.root_path = root_path
def from_envvar(self, variable_name, silent=False):
"""Loads a configuration from an environment variable pointing to
a configuration file. This is basically just a shortcut with nicer
error messages for this line of code::
app.config.from_pyfile(os.environ['YOURAPPLICATION_SETTINGS'])
:param variable_name: name of the environment variable
:param silent: set to ``True`` if you want silent failure for missing
files.
:return: bool. ``True`` if able to load config, ``False`` otherwise.
"""
rv = os.environ.get(variable_name)
if not rv:
if silent:
return False
raise RuntimeError('The environment variable %r is not set '
'and as such configuration could not be '
'loaded. Set this variable and make it '
'point to a configuration file' %
variable_name)
return self.from_pyfile(rv, silent=silent)
def from_pyfile(self, filename, silent=False):
"""Updates the values in the config from a Python file. This function
behaves as if the file was imported as module with the
:meth:`from_object` function.
:param filename: the filename of the config. This can either be an
absolute filename or a filename relative to the
root path.
:param silent: set to ``True`` if you want silent failure for missing
files.
.. versionadded:: 0.7
`silent` parameter.
"""
filename = os.path.join(self.root_path, filename)
d = types.ModuleType('config')
d.__file__ = filename
try:
with open(filename, mode='rb') as config_file:
exec(compile(config_file.read(), filename, 'exec'), d.__dict__)
except IOError as e:
if silent and e.errno in (errno.ENOENT, errno.EISDIR):
return False
e.strerror = 'Unable to load configuration file (%s)' % e.strerror
raise
self.from_object(d)
return True
def from_object(self, obj):
"""Updates the values from the given object. An object can be of one
of the following two types:
- a string: in this case the object with that name will be imported
- an actual object reference: that object is used directly
Objects are usually either modules or classes. :meth:`from_object`
loads only the uppercase attributes of the module/class. A ``dict``
object will not work with :meth:`from_object` because the keys of a
``dict`` are not attributes of the ``dict`` class.
Example of module-based configuration::
app.config.from_object('yourapplication.default_config')
from yourapplication import default_config
app.config.from_object(default_config)
You should not use this function to load the actual configuration but
rather configuration defaults. The actual config should be loaded
with :meth:`from_pyfile` and ideally from a location not within the
package because the package might be installed system wide.
See :ref:`config-dev-prod` for an example of class-based configuration
using :meth:`from_object`.
:param obj: an import name or object
"""
if isinstance(obj, str):
obj = import_string(obj)
for key in dir(obj):
if key.isupper():
self[key] = getattr(obj, key)
def from_json(self, filename, silent=False):
"""Updates the values in the config from a JSON file. This function
behaves as if the JSON object was a dictionary and passed to the
:meth:`from_mapping` function.
:param filename: the filename of the JSON file. This can either be an
absolute filename or a filename relative to the
root path.
:param silent: set to ``True`` if you want silent failure for missing
files.
.. versionadded:: 0.11
"""
filename = os.path.join(self.root_path, filename)
try:
with open(filename) as json_file:
obj = json.loads(json_file.read())
except IOError as e:
if silent and e.errno in (errno.ENOENT, errno.EISDIR):
return False
e.strerror = 'Unable to load configuration file (%s)' % e.strerror
raise
return self.from_mapping(obj)
def from_mapping(self, *mapping, **kwargs):
"""Updates the config like :meth:`update` ignoring items with non-upper
keys.
.. versionadded:: 0.11
"""
mappings = []
if len(mapping) == 1:
if hasattr(mapping[0], 'items'):
mappings.append(mapping[0].items())
else:
mappings.append(mapping[0])
elif len(mapping) > 1:
raise TypeError(
'expected at most 1 positional argument, got %d' % len(mapping)
)
mappings.append(kwargs.items())
for mapping in mappings:
for (key, value) in mapping:
if key.isupper():
self[key] = value
return True
def get_namespace(self, namespace, lowercase=True, trim_namespace=True):
"""Returns a dictionary containing a subset of configuration options
that match the specified namespace/prefix. Example usage::
app.config['IMAGE_STORE_TYPE'] = 'fs'
app.config['IMAGE_STORE_PATH'] = '/var/app/images'
app.config['IMAGE_STORE_BASE_URL'] = 'http://img.website.com'
image_store_config = app.config.get_namespace('IMAGE_STORE_')
The resulting dictionary `image_store_config` would look like::
{
'type': 'fs',
'path': '/var/app/images',
'base_url': 'http://img.website.com'
}
This is often useful when configuration options map directly to
keyword arguments in functions or class constructors.
:param namespace: a configuration namespace
:param lowercase: a flag indicating if the keys of the resulting
dictionary should be lowercase
:param trim_namespace: a flag indicating if the keys of the resulting
dictionary should not include the namespace
.. versionadded:: 0.11
"""
rv = {}
for k, v in self.items():
if not k.startswith(namespace):
continue
if trim_namespace:
key = k[len(namespace):]
else:
key = k
if lowercase:
key = key.lower()
rv[key] = v
return rv
def __repr__(self):
return '<%s %s>' % (self.__class__.__name__, dict.__repr__(self))
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
import os
import logging
from logging import StreamHandler
from logging.handlers import TimedRotatingFileHandler
LOG_LEVELS = {
'DEBUG': logging.DEBUG,
'INFO': logging.INFO,
'WARN': logging.WARNING,
'WARNING': logging.WARNING,
'ERROR': logging.ERROR,
'FATAL': logging.FATAL,
'CRITICAL': logging.CRITICAL,
}
def create_logger(app):
level = app.config['LOG_LEVEL']
level = LOG_LEVELS.get(level, logging.INFO)
log_dir = app.config.get('LOG_DIR')
log_path = os.path.join(log_dir, 'coco.log')
logger = logging.getLogger()
main_formatter = logging.Formatter(
fmt='%(asctime)s [%(module)s %(levelname)s] %(message)s',
datefmt='%Y-%m-%d %H:%M:%S')
console_handler = StreamHandler()
file_handler = TimedRotatingFileHandler(
filename=log_path, when='D', backupCount=10)
for handler in [console_handler, file_handler]:
handler.setFormatter(main_formatter)
logger.addHandler(handler)
logger.setLevel(level)
#!coding: utf-8
import select
import uuid
import socket
BUF_SIZE = 1024
logger =
class Session:
def __init__(self, client, server):
self.id = str(uuid.uuid4())
self.client = client # Master of the session, it's a client sock
self.server = server # Server channel
self.watchers = [] # Only watch session
self.sharers = [] # Join to the session, read and write
self.running = True
def add_watcher(self, watcher):
"""
Add a watcher, and will be transport server side msg to it.
:param watcher: A client socket
:return:
"""
self.watchers.append(watcher)
def add_sharer(self, sharer):
"""
Add a sharer, it can read and write to server
:param sharer: A client socket
:return:
"""
self.sharers.append(sharer)
def bridge(self):
"""
Bridge clients with server
:return:
"""
while self.running:
try:
r, w, x = select.select([self.client + self.server]
+ self.watchers + self.sharers, [], [])
for sock in r:
if sock == self.server:
data = sock.recv(BUF_SIZE)
if len(data) == 0:
self.close()
for watcher in [self.client] + self.watchers + self.sharers:
watcher.send(data)
elif sock == self.client:
data = sock.recv(BUF_SIZE)
if len(data) == 0:
for watcher in self.watchers + self.sharers:
watcher.send("%s close the session" % self.client)
self.close()
self.server.send(data)
elif sock in self.watchers:
sock.send("WARN: Your didn't have the write permission\r\n")
elif sock in self.sharers:
data = sock.recv(BUF_SIZE)
if len(data) == 0:
sock.send("Leave session %s" % self.id)
self.server.send(data)
except Exception as e:
pass
def set_size(self, width, height):
self.server.resize_pty(width=width, height=height)
def record(self):
parent, child = socket.socketpair()
self.add_watcher(parent)
def close(self):
pass
#! coding: utf-8
class SSHServer:
def __init__(self, app=None):
self.app = app
@classmethod
def run(cls, app):
self = cls(app)
def shutdown(self):
pass
import os
BASE_DIR = os.path.dirname(__file__)
# 项目名称, 会用来向Jumpserver注册, 识别而已, 不能重复
APP_NAME = "coco"
# Jumpserver项目的url, api请求注册会使用
# CORE_HOST = 'http://127.0.0.1:8080'
# 启动时绑定的ip, 默认 0.0.0.0
# BIND_HOST = '0.0.0.0'
# 监听的SSH端口号, 默认2222
# SSHD_PORT = 2222
# 监听的WS端口号,默认5000
# WS_PORT = 5000
# 是否开启DEBUG
# DEBUG = True
# 项目使用的ACCESS KEY, 默认会注册,并保存到 ACCESS_KEY_STORE中,
# 如果有需求, 可以写到配置文件中, 格式 access_key_id:access_key_secret
# ACCESS_KEY = None
# ACCESS KEY 保存的地址, 默认注册后会保存到该文件中
# ACCESS_KEY_STORE = os.path.join(BASE_DIR, 'keys', '.access_key')
# 加密密钥
# SECRET_KEY = None
# 设置日志级别 ['DEBUG', 'INFO', 'WARN', 'ERROR', 'FATAL', 'CRITICAL']
# LOG_LEVEL = 'INFO'
# 日志存放的目录
# LOG_DIR = os.path.join(BASE_DIR, 'logs')
# 资产显示排序方式, ['ip', 'hostname']
# ASSET_LIST_SORT_BY = 'ip'
# 登录是否支持密码认证
# SSH_PASSWORD_AUTH = True
# 登录是否支持秘钥认证
# SSH_PUBLIC_KEY_AUTH = True
# 和Jumpserver 保持心跳时间间隔
# HEARTBEAT_INTERVAL = 5
#!/usr/bin/python
#
import os
from coco import Coco
import conf
try:
os.mkdir("logs")
os.mkdir("keys")
except:
pass
coco = Coco()
coco.config.from_object(conf)
if __name__ == '__main__':
coco.run_forever()
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment