Initial commit

This commit is contained in:
Digital Studium 2024-05-07 09:26:26 +03:00
commit b9bb606cdd
2 changed files with 196 additions and 0 deletions

3
.gitignore vendored Normal file
View File

@ -0,0 +1,3 @@
.idea
venv
__pycache__

193
sshtui Executable file
View File

@ -0,0 +1,193 @@
#!/usr/bin/env python3
import subprocess, curses, configparser
from pathlib import Path
# constants
KEY_BINDINGS = { # can be extended
"\n": 'ssh -i {identity} {user}@{server} -p {port}'
}
HELP_TEXT = "letters: filter mode, Esc: exit filter/exit sshcurs, Enter: connect to server, arrows/TAB/PgUp/PgDn: navigation"
MOUSE_ENABLED = True
SCREEN = curses.initscr() # screen initialization, needed for ROWS_HEIGHT working
HEADER_HEIGHT = 4 # in rows
FOOTER_HEIGHT = 3
ROWS_HEIGHT = curses.LINES - HEADER_HEIGHT - FOOTER_HEIGHT - 3 # maximum number of visible rows indices
WIDTH = curses.COLS
CONFIG = configparser.ConfigParser()
CONFIG.read(f"{str(Path.home())}/.sshtui.ini")
# classes
class CircularList:
def __init__(self, elements):
self.elements = elements
self.size = len(elements)
self.index = 0
def __getitem__(self, index):
start, stop, step = index.indices(self.size)
return [self.elements[(self.index + i) % self.size] for i in range(start, stop, step)]
def shift(self, steps):
self.index = (self.index + steps) % self.size
class Menu:
def __init__(self, title: str, rows: list, begin_x: int, width: int, rows_height: int):
self.title = title
self.rows = rows # all rows
self.filter = "" # filter for rows
self.filtered_rows = CircularList([x for x in self.rows if self.filter in x.lower()]) # filtered rows
self.visible_rows = lambda: self.filtered_rows[:rows_height] # visible rows
self.visible_row_index = 0 # index of the selected visible row
# selected row from visible rows
self.selected_row = lambda: self.visible_rows()[self.visible_row_index] if self.visible_rows() else None
self.rows_height = rows_height
self.width = width
self.begin_x = begin_x
self.win = curses.newwin(curses.LINES - FOOTER_HEIGHT, width, 0, begin_x)
# helper functions
def draw_row(window: curses.window, text: str, y: int, x: int, selected: bool = False):
window.addstr(y, x, text, curses.A_REVERSE | curses.A_BOLD if selected else curses.A_NORMAL)
window.clrtoeol()
window.refresh()
def draw_rows(menu: Menu):
for index, row in enumerate(menu.visible_rows()):
draw_row(menu.win, row, index + HEADER_HEIGHT, 2, selected=True if row == menu.selected_row() else False)
def draw_menu(menu: Menu):
menu.win.clear() # clear menu window
draw_row(menu.win, menu.title, 1, 2) # draw title
draw_rows(menu) # draw menu rows
draw_row(menu.win, f"/{menu.filter}" if menu.filter else "", curses.LINES - FOOTER_HEIGHT - 2, 2) # draw filter row
def handle_key_bindings(key: str, user: str, server: str, port: str, identity: str):
if not server:
return
curses.def_prog_mode() # save the previous terminal state
curses.endwin() # without this, there are problems after exiting vim
command = KEY_BINDINGS[key].format(user=user, server=server, identity=identity, port=port)
try:
subprocess.call(command, shell=True)
except:
pass
curses.reset_prog_mode() # restore the previous terminal state
SCREEN.refresh()
enable_mouse_support()
def handle_filter_state(key: str, menu: Menu):
if key in ["KEY_BACKSPACE", "\x08"] and not menu.filter:
return
elif key == "\x1b" and not menu.filter:
globals().update(selected_menu=None) # exit
elif key == "\x1b":
menu.filter = "" # Escape key exits filter mode
elif key in ["KEY_BACKSPACE", "\x08"]:
menu.filter = menu.filter[:-1] # Backspace key deletes a character (\x08 is also Backspace)
elif key.isascii():
menu.filter += key.lower()
menu.visible_row_index = 0
menu.filtered_rows = CircularList([x for x in menu.rows if menu.filter in x.lower()]) # update filtered rows
draw_menu(menu)
def handle_mouse(menu: Menu):
if not MOUSE_ENABLED:
return
try:
mouse_info = curses.getmouse()
except curses.error: # this fixes scrolling error
return
row_number = mouse_info[2] - HEADER_HEIGHT
column_number = mouse_info[1]
char_int = menu.win.inch(mouse_info[2], column_number - menu.begin_x - 1) # get char from current mouse position
char_str = chr(char_int & 0xFF)
if not char_str or ord(char_str) > 127 or ' ' in char_str:
return
if 0 <= row_number < len(menu.visible_rows()):
menu.visible_row_index = row_number
draw_rows(menu) # this will change selected row in menu
def handle_vertical_navigation(key: str, menu: Menu):
if len(menu.visible_rows()) <= 1:
return
keys_numbers = {"KEY_DOWN": 1, "KEY_UP": -1, "KEY_NPAGE": 1, "KEY_PPAGE": -1, 'KEY_HOME': 0, 'KEY_END': -1}
if key in ["KEY_DOWN", "KEY_UP"]:
if menu.filtered_rows.size > menu.rows_height:
menu.filtered_rows.shift(keys_numbers[key])
else:
menu.visible_row_index = (menu.visible_row_index + keys_numbers[key]) % menu.filtered_rows.size # index of the selected visible row
elif key in ["KEY_NPAGE", "KEY_PPAGE"]:
menu.filtered_rows.shift(keys_numbers[key] * len(menu.visible_rows()))
elif key in ['KEY_HOME','KEY_END']:
menu.visible_row_index = keys_numbers[key]
draw_rows(menu)
def catch_input(menu: Menu):
key = SCREEN.getkey()
if key in ["KEY_UP", "KEY_DOWN", "KEY_NPAGE", "KEY_PPAGE", "KEY_HOME", "KEY_END"]:
handle_vertical_navigation(key, menu)
elif key == "KEY_MOUSE":
handle_mouse(menu)
elif key in KEY_BINDINGS.keys():
handle_key_bindings(key, user(), server(), port(), identity())
elif key in ["\x1b", "KEY_BACKSPACE", "\x08"] or key.isascii(): # \x1b - escape, \x08 - backspace
handle_filter_state(key, menu)
def enable_mouse_support():
curses.mousemask(curses.REPORT_MOUSE_POSITION) # mouse tracking
print('\033[?1003h') # enable mouse tracking with the XTERM API. That's the magic
def get_servers() -> list:
servers = []
server_names = CONFIG.sections()
for server_name in server_names:
user = CONFIG[server_name]['User']
server = CONFIG[server_name]['Server']
identity = CONFIG[server_name]['Identity'] if 'Identity' in CONFIG[server_name] else "~/.ssh/id_rsa"
port = CONFIG[server_name]['Port'] if 'Port' in CONFIG[server_name] else "22"
servers.append(f"{server_name:<20} {user:<20} {server:<30} {port:<8} {identity}")
return servers
def init_menus():
global menus, selected_menu, user, server, identity, port
menu_title = '{: <20s} {: <20s} {: <30s} {: <8s} {}'.format("Name", "User", "Host", "Port", "Identity")
menus = [Menu(menu_title, get_servers(), 0, WIDTH, ROWS_HEIGHT)]
selected_menu = menus[0]
user = lambda: menus[0].selected_row().split()[-4] if menus[0].selected_row() else None
server = lambda: menus[0].selected_row().split()[-3] if menus[0].selected_row() else None
port = lambda: menus[0].selected_row().split()[-2] if menus[0].selected_row() else None
identity = lambda: menus[0].selected_row().split()[-1] if menus[0].selected_row() else None
SCREEN.refresh() # I don't know why this is needed but it doesn't work without it
SCREEN.keypad(True) # needed for arrow keys
curses.set_escdelay(1) # reduce Escape delay to 1 ms (curses can't set it to 0)
curses.curs_set(0) # make the cursor invisible
curses.use_default_colors() # don't change the terminal color
curses.noecho() # don't output characters at the top
enable_mouse_support()
def main(screen):
init_menus()
for menu in menus: # draw the main windows
draw_menu(menu)
draw_row(curses.newwin(3, curses.COLS, curses.LINES - FOOTER_HEIGHT, 0), HELP_TEXT, 1, 2) # and the help window
while selected_menu:
catch_input(selected_menu) # if a menu is selected, catch user input
if __name__ == "__main__":
curses.wrapper(main)