更优于 Shellinabox 的 web shell 工具 -- ttyd

ttyd 是一个运行在服务端,客户端通过web浏览器访问从而连接后台 tty (pts伪终端)接口的程序,把 shell 终端搬到 web 浏览器中。


WebSocket

WebSocket 是 HTML5 开始提供的一种基于HTTP协议与服务器WebServer进行单会话、长连接、全双工的网络技术,依靠这种技术可以实现客户端和服务端的长连接,双向实时通信,以及基于服务端主动向客户端的实时消息推送交互的底层技术栈。
它的最大特点就是,服务器可以主动向客户端推送信息,客户端也可以主动向服务器发送信息, 是真正的双向平等对话,属于服务器推送技术的一种。

其他特点包括:

  • 建立在 TCP 协议之上,服务器端的实现比较容易。
  • 与 HTTP 协议有着良好的兼容性。默认端口也是 80 和 443,并且握手阶段采用 HTTP 协议,因此握手时不容易屏蔽,能通过各种 HTTP 代理服务器。
  • 数据格式比较轻量,性能开销小,通信高效。
  • 可以发送文本,也可以发送二进制数据
  • 没有同源限制,客户端可以与任意服务器通信。
  • 协议标识符是ws(如果加密,则为wss),服务器网址就是 URL。

ttyd 不同于 Shellinabox 项目的底层原理,它使用基于HTML5的 WebSocket 协议,更少的http交互带来更高效、更高性能、更低延时的交互式会话服务。

ttyd 也可以通过 Nginx 7层HTTP代理访问,更高的灵活性。

ttyd 内建支持 SSL/TLS 传输层认证加密,支持客户端/服务端的单向/双向证书认证加密,更高的安全性。

OS Support:

* macOS
* Linux
* Microsoft Windows
* FreeBSD/OpenBSD
* OpenWrt/LEDE

Feature:

* C语言内建`libwebsockets`核心库,高速、低内存消耗、高性能特性。 
* 基于`Xterm.js`的全功能终端,支持 CJK 不同语言和 IME 输入法字符输入。
* 窗口图形化 `ZMODEM` 支持,服务端需安装 `lrzsz` 程序。
* 可实现基于简单的 Basic Auth 基本认证(不加密通信)。
* 可实现基于 OpenSSL 的传输层加密通信支持(加密通信)。
* 跨平台: macOS, Linux, FreeBSD/OpenBSD, OpenWrt/LEDE, Windows

Linux 平台安装方式:

  • 方式一:下载二进制程序文件,本地直接运行即可(推荐)
  • 方式二:下载源码文件,安装依赖库编译安装
    sudo apt-get install cmake g++ pkg-config git vim-common libwebsockets-dev libjson-c-dev libssl-dev
    git clone https://github.com/tsl0922/ttyd.git
    cd ttyd && mkdir build && cd build
    cmake ..
    make && make install
    
    如果安装libwebsockets-dev(版本过时)失败,你可能需要单独编译安装libwebsockets

使用方式:

程序帮助信息:

ttyd is a tool for sharing terminal over the web

USAGE:
    ttyd [options] <command> [<arguments...>]

VERSION:
    1.5.2

OPTIONS:
    -p, --port              Port to listen (default: 7681, use `0` for random port)
    -i, --interface         Network interface to bind (eg: eth0), or UNIX domain socket path (eg: /var/run/ttyd.sock)
    -c, --credential        Credential for Basic Authentication (format: username:password)
    -u, --uid               User id to run with
    -g, --gid               Group id to run with
    -s, --signal            Signal to send to the command when exit it (default: 1, SIGHUP)
    -a, --url-arg           Allow client to send command line arguments in URL (eg: http://localhost:7681?arg=foo&arg=bar)
    -R, --readonly          Do not allow clients to write to the TTY
    -t, --client-option     Send option to client (format: key=value), repeat to add more options
    -T, --terminal-type     Terminal type to report, default: xterm-256color
    -O, --check-origin      Do not allow websocket connection from different origin
    -m, --max-clients       Maximum clients to support (default: 0, no limit)
    -o, --once              Accept only one client and exit on disconnection
    -B, --browser           Open terminal with the default system browser
    -I, --index             Custom index.html path
    -6, --ipv6              Enable IPv6 support
    -S, --ssl               Enable SSL
    -C, --ssl-cert          SSL certificate file path
    -K, --ssl-key           SSL key file path
    -A, --ssl-ca            SSL CA file path for client certificate verification
    -d, --debug             Set log level (default: 7)
    -v, --version           Print the version and exit
    -h, --help              Print this text and exit

Visit https://github.com/tsl0922/ttyd to get more information and report bugs.

用例:

./ttyd -p 8080 bash -x
# 页面以当前用户的身份和环境变量进行后台连接,fork 的方式为 bash 调试方式运行。
./ttyd --max-clients 2 -u 500 top
# 以指定的系统用户身份的uid运行服务,登录页面即为运行 top 命令的输出结果。

运行系统账户登录认证

./ttyd --max-clients 2 login
# 以当前用户身份运行服务。

注意:如需root身份登录终端,需要在属主属组为 root 的 /etc/securetty文件中增加可登录的终端类型pts/0 pts/1 pts/2,当然也需要运行 ttyd 程序的用户有可读 /etc/securetty 文件的权限(当然也就是以 root 身份启动 ttyd 服务)。
所以,为安全性考虑,不建议以 root 身份启动 ttyd 服务,也就不建议直接以 root 账户登录 ttyd websockets页面伪终端。

运行特定的后台交互式服务

# console
./ttyd --max-clients 2 -a mysql -h localhost 
// -a, --url-arg 允许url携带参数,参数将直接应用到 command 程序中。


# browser 1  使用 command 默认参数
http://localhost:7681

Warning: Using a password on the command line interface can be insecure.
ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)



# browser 2   在url请求中使用指定的 command 参数
http://localhost:7681/?arg=-uadmin&arg=-pPASSWORD&arg=mysql

mysql> show tables;
+---------------------------+
| Tables_in_mysql           |
+---------------------------+
| columns_priv              |
| db                        |
| event                     |
| func                      |
| general_log               |
| help_category             |
| help_keyword              |
| help_relation             |
| help_topic                |
| innodb_index_stats        |
| innodb_table_stats        |
| ndb_binlog_index          |
| plugin                    |
| proc                      |
| procs_priv                |
| proxies_priv              |
| servers                   |
| slave_master_info         |
| slave_relay_log_info      |
| slave_worker_info         |
| slow_log                  |
| tables_priv               |
| time_zone                 |
| time_zone_leap_second     |
| time_zone_name            |
| time_zone_transition      |
| time_zone_transition_type |
| user                      |
+---------------------------+
28 rows in set (0.00 sec)

通过 ZMODEM 上传下载文件,服务端需安装 lrzsz

# 向客户端发送本地文件
sz a.log 

# 服务端接收客户端上传的文件
rz

使用 SSL 加密传输流量

本例使用本地自签证书示例

# CA certificate (FQDN must be different from server/client)
openssl genrsa -out ca.key 2048
openssl req -new -x509 -days 365 -key ca.key -subj "/C=CN/ST=GD/L=SZ/O=Acme, Inc./CN=Acme Root CA" -out ca.crt

# server certificate (for multiple domains, change subjectAltName to: DNS:example.com,DNS:www.example.com)
openssl req -newkey rsa:2048 -nodes -keyout server.key -subj "/C=CN/ST=GD/L=SZ/O=Acme, Inc./CN=localhost" -out server.csr
openssl x509 -sha256 -req -extfile <(printf "subjectAltName=DNS:localhost") -days 365 -in server.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out server.crt

# 双向认证 client certificate (the p12/pem format may be useful for some clients)(可选)
openssl req -newkey rsa:2048 -nodes -keyout client.key -subj "/C=CN/ST=GD/L=SZ/O=Acme, Inc./CN=client" -out client.csr
openssl x509 -req -days 365 -in client.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out client.crt
openssl pkcs12 -export -clcerts -in client.crt -inkey client.key -out client.p12
openssl pkcs12 -in client.p12 -out client.pem -clcerts

服务端单向认证

./ttyd --ssl --ssl-cert server.crt --ssl-key server.key bash

客户端/服务端双向认证,需增加--ssl-ca选项,桌面浏览器另外需要单独安装 client.p12证书到本地

./ttyd --ssl --ssl-cert server.crt --ssl-key server.key --ssl-ca ca.crt bash


在 curl 中测试证书验证

curl --insecure --cert client.p12[:password] -v https://localhost:7681

如需把服务挂靠在 Nginx 后端,请配置增加如下 ws 参数:

        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection upgrade;
        proxy_read_timeout 3600
原文地址:https://www.cnblogs.com/TopGear/p/14549139.html