SSH 聊天室实现原理

SSH 聊天室受到 sshtron (贪吃蛇) 的启发。OpenSSH Server 允许我们指定 “ForceCommand”,即该用户强制只能执行此命令。

Match user chat
  PermitEmptyPasswords yes
  ForceCommand /home/chat/startup

连接时需要 -t 的原因是,在 ssh 带参数时默认不会分配终端。startup 启动一个普通的 curses 程序,使用 Python curses 标准库 实现;大部分代码都由 GPT-4 生成。

Prompt: Give me a python code using curses, there is a input box in the bottom, while a file's content is constantly updated on the top panel in a separate thread. (Directly give the code without any explanation or tutorial setups.)

GPT-4-turbo 生成的代码 (同样,你可以预期 Github Copilot X 能够在多大程度上辅助程序员完成工作),经过修缮就可以使用了:

import curses
import threading
import time

def update_file_content(window, path):
    while True:
        with open(path, 'r') as file:
            lines = file.readlines()
        
        window.clear()
        for i, line in enumerate(lines):
            window.addstr(i, 0, line)
        window.refresh()
        time.sleep(1)  # Update every second

def input_box(stdscr):
    curses.echo()
    
    # Setup the window for file content
    file_content_height = curses.LINES - 3
    file_content_window = curses.newwin(file_content_height, curses.COLS, 0, 0)
    file_content_window.scrollok(True)
    
    # Setup the window for input box
    input_box_window = curses.newwin(3, curses.COLS, curses.LINES - 3, 0)
    input_box_window.box()
    input_box_window.addstr(1, 1, "Input: ")
    input_box_window.refresh()
    
    # Start thread for updating file content
    file_path = 'your_file_path_here.txt'  # Change this to your file path
    threading.Thread(target=update_file_content, args=(file_content_window, file_path), daemon=True).start()
    
    while True:
        # Get input from the user
        input_str = input_box_window.getstr(1, 8, 20)
        
        # Process the input (Here, just print it to the console)
        print(input_str.decode('utf-8'))

        # Clear the input box after getting input
        input_box_window.clear()
        input_box_window.box()
        input_box_window.addstr(1, 1, "Input: ")
        input_box_window.refresh()

def main():
    curses.wrapper(input_box)

if __name__ == "__main__":
    main()