Skip to content

Commit

Permalink
update 5.1
Browse files Browse the repository at this point in the history
New ServerManager for manage multiple server with multiple protocol. ProWrapper for translate protocol from many protocol to one protocol (function).
  • Loading branch information
damp11113 committed Dec 6, 2024
1 parent 1b15383 commit 78a6459
Show file tree
Hide file tree
Showing 27 changed files with 1,410 additions and 283 deletions.
8 changes: 5 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
# What is PyserSSH

This library will be **Pyserminal** (Python Server Terminal) as it supports multiple protocols such as ssh telnet rlogin and mores...

PyserSSH is a free and open-source Python library designed to facilitate the creation of customizable SSH terminal servers. Initially developed for research purposes to address the lack of suitable SSH server libraries in Python, PyserSSH provides a flexible and user-friendly solution for implementing SSH servers, making it easier for developers to handle user interactions and command processing.

The project was started by a solo developer to create a more accessible and flexible tool for managing SSH connections and commands. It offers a simplified API compared to other libraries, such as Paramiko, SSHim, and Twisted, which are either outdated or complex for new users.
Expand Down Expand Up @@ -32,15 +34,15 @@ pip install git+https://git.damp11113.xyz/DPSoftware-Foundation/PyserSSH.git
# Quick Example
This Server use port **2222** for default port
```py
from PyserSSH import Server, Send, AccountManager
from PyserSSH import Server, AccountManager

useraccount = AccountManager(anyuser=True)
useraccount = AccountManager(allow_guest=True)
ssh = Server(useraccount)

@ssh.on_user("command")
def command(client, command: str):
if command == "hello":
Send(client, "world!")
client.send("world!")

ssh.run("your private key file")
```
Expand Down
107 changes: 30 additions & 77 deletions demo/demo1.py
Original file line number Diff line number Diff line change
@@ -1,34 +1,42 @@
import os
os.environ["damp11113_load_all_module"] = "NO"

from damp11113.utils import TextFormatter
from damp11113.file import sort_files, allfiles
import socket
import time
import cv2
import traceback
import requests
from bs4 import BeautifulSoup
import numpy as np
import logging

#import logging
#logging.basicConfig(level=logging.DEBUG)
# Configure logging
logging.basicConfig(format='[{asctime}] [{levelname}] {name}: {message}', datefmt='%Y-%m-%d %H:%M:%S', style='{', level=logging.DEBUG)

from PyserSSH import Server, AccountManager
from PyserSSH.interactive import Send, wait_input, wait_inputkey, wait_choose, Clear, wait_inputmouse
from PyserSSH.system.info import __version__, Flag_TH
from PyserSSH.interactive import Send, wait_input, wait_inputkey, wait_choose, Clear, wait_inputmouse
from PyserSSH.system.info import version, Flag_TH
from PyserSSH.extensions.processbar import indeterminateStatus, LoadingProgress
from PyserSSH.extensions.dialog import MenuDialog, TextDialog, TextInputDialog
from PyserSSH.extensions.moredisplay import clickable_url, Send_karaoke_effect
from PyserSSH.extensions.moreinteractive import ShowCursor
from PyserSSH.extensions.remodesk import RemoDesk
from PyserSSH.extensions.XHandler import XHandler
from PyserSSH.system.clientype import Client
from PyserSSH.system.remotestatus import remotestatus
from PyserSSH.system.RemoteStatus import remotestatus
from PyserSSH.utils.ServerManager import ServerManager

useraccount = AccountManager(allow_guest=True, autoload=True, autosave=True)

useraccount = AccountManager(allow_guest=True)
useraccount.add_account("admin", "") # create user without password
useraccount.add_account("test", "test") # create user without password
useraccount.add_account("demo")
useraccount.add_account("remote", "12345", permissions=["remote_desktop"])
useraccount.set_user_enable_inputsystem_echo("remote", False)
useraccount.set_user_sftp_allow("admin", True)
if not os.path.isfile("autosave_session.ses"):
useraccount.add_account("admin", "", sudo=True) # create user without password
useraccount.add_account("test", "test") # create user without password
useraccount.add_account("demo")
useraccount.add_account("remote", "12345", permissions=["remote_desktop"])
useraccount.set_user_enable_inputsystem_echo("remote", False)
useraccount.set_user_sftp_allow("admin", True)

XH = XHandler()
ssh = Server(useraccount,
Expand All @@ -42,64 +50,7 @@

servername = "PyserSSH"

loading = ["PyserSSH", "Extensions"]

class TextFormatter:
RESET = "\033[0m"
TEXT_COLORS = {
"black": "\033[30m",
"red": "\033[31m",
"green": "\033[32m",
"yellow": "\033[33m",
"blue": "\033[34m",
"magenta": "\033[35m",
"cyan": "\033[36m",
"white": "\033[37m"
}
TEXT_COLOR_LEVELS = {
"light": "\033[1;{}m", # Light color prefix
"dark": "\033[2;{}m" # Dark color prefix
}
BACKGROUND_COLORS = {
"black": "\033[40m",
"red": "\033[41m",
"green": "\033[42m",
"yellow": "\033[43m",
"blue": "\033[44m",
"magenta": "\033[45m",
"cyan": "\033[46m",
"white": "\033[47m"
}
TEXT_ATTRIBUTES = {
"bold": "\033[1m",
"italic": "\033[3m",
"underline": "\033[4m",
"blink": "\033[5m",
"reverse": "\033[7m",
"strikethrough": "\033[9m"
}

@staticmethod
def format_text_truecolor(text, color=None, background=None, attributes=None, target_text=''):
formatted_text = ""
start_index = text.find(target_text)
end_index = start_index + len(target_text) if start_index != -1 else len(text)

if color:
formatted_text += f"\033[38;2;{color}m"

if background:
formatted_text += f"\033[48;2;{background}m"

if attributes in TextFormatter.TEXT_ATTRIBUTES:
formatted_text += TextFormatter.TEXT_ATTRIBUTES[attributes]

if target_text == "":
formatted_text += text + TextFormatter.RESET
else:
formatted_text += text[:start_index] + text[start_index:end_index] + TextFormatter.RESET + text[end_index:]

return formatted_text
loading = ["PyserSSH", "openRemoDesk", "XHandler", "RemoteStatus"]

@ssh.on_user("pre-shell")
def guestauth(client):
Expand Down Expand Up @@ -185,7 +136,7 @@ def connect(client):
wm = f"""{Flag_TH()}{'–'*50}
Hello {client['current_user']},
This is testing server of PyserSSH v{__version__}.
This is testing server of PyserSSH v{version}.
Visit: {clickable_url("https://damp11113.xyz", "DPCloudev")}
{'–'*50}"""
Expand Down Expand Up @@ -258,9 +209,9 @@ def xh_typing(client: Client, messages, speed = 1):
Send(client, "")

@XH.command(name="renimtest")
def xh_renimtest(client: Client, path: str):
def xh_renimtest(client: Client):
Clear(client)
image = cv2.imread(f"opensource.png", cv2.IMREAD_COLOR)
image = cv2.imread("opensource.png", cv2.IMREAD_COLOR)
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

width, height = client['windowsize']["width"] - 5, client['windowsize']["height"] - 5
Expand Down Expand Up @@ -458,12 +409,14 @@ def xh_status(client: Client):
#@ssh.on_user("command")
#def command(client: Client, command: str):

ssh.run(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'private_key.pem'))
#ssh.run(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'private_key.pem'))

#manager = ServerManager()
manager = ServerManager()

# Add servers to the manager
#manager.add_server("server1", server1)
manager.add_server("ssh", ssh, os.path.join(os.path.dirname(os.path.realpath(__file__)), 'private_key.pem'))
manager.add_server("telnet", ssh, "", protocol="telnet")

# Start a specific server
#manager.start_server("server1", private_key_path="key")
manager.start_server("ssh")
manager.start_server("telnet")
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

setup(
name='PyserSSH',
version='5.0',
version='5.1',
license='MIT',
author='DPSoftware Foundation',
author_email='[email protected]',
Expand Down
55 changes: 10 additions & 45 deletions src/PyserSSH/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
"""
PyserSSH - A Scriptable SSH server. For more info visit https://github.com/DPSoftware-Foundation/PyserSSH
Copyright (C) 2023-2024 DPSoftware Foundation (MIT)
Copyright (C) 2023-present DPSoftware Foundation (MIT)
Visit https://github.com/DPSoftware-Foundation/PyserSSH
Expand Down Expand Up @@ -37,15 +37,15 @@
https://en.wikipedia.org/wiki/ANSI_escape_code
"""
import os
import ctypes
import logging

from .interactive import *
from .server import Server
from .account import AccountManager
from .system.info import system_banner
from .system.info import system_banner, version

if os.name == 'nt':
import ctypes
kernel32 = ctypes.windll.kernel32
kernel32.SetConsoleMode(kernel32.GetStdHandle(-11), 7)

Expand All @@ -67,45 +67,10 @@
if os.environ["pyserssh_systemmessage"] == "YES":
print(system_banner)

# Server Managers

class ServerManager:
def __init__(self):
self.servers = {}

def add_server(self, name, server):
if name in self.servers:
raise ValueError(f"Server with name '{name}' already exists.")
self.servers[name] = server

def remove_server(self, name):
if name not in self.servers:
raise ValueError(f"No server found with name '{name}'.")
del self.servers[name]

def get_server(self, name):
return self.servers.get(name)

def start_server(self, name, protocol="ssh", *args, **kwargs):
server = self.get_server(name)
if not server:
raise ValueError(f"No server found with name '{name}'.")
print(f"Starting server '{name}'...")
server.run(*args, **kwargs)

def stop_server(self, name):
server = self.get_server(name)
if not server:
raise ValueError(f"No server found with name '{name}'.")
print(f"Stopping server '{name}'...")
server.stop_server()

def start_all_servers(self, *args, **kwargs):
for name, server in self.servers.items():
print(f"Starting server '{name}'...")
server.run(*args, **kwargs)

def stop_all_servers(self):
for name, server in self.servers.items():
print(f"Stopping server '{name}'...")
server.stop_server()
__author__ = "damp11113"
__url__ = "https://github.com/DPSoftware-Foundation/PyserSSH"
__copyright__ = "2023-present"
__license__ = "MIT"
__version__ = version
__department__ = "DPSoftware"
__organization__ = "DOPFoundation"
Loading

0 comments on commit 78a6459

Please sign in to comment.