Python Tricks —— 使用 asciinema 录制命令行操作

asciinema 是一个由 Python 语言编写的开源的终端会话录制工具。它可以将命令行的输出内容根据时间保存在 JSON 格式的文件中,以供后续播放时使用。
同时该录制文件也可以通过 Web 浏览器进行播放(需要使用由 asciinema-player 提供的 Javascript 和 CSS 文件),或者直接上传到 asciinema.org 网站分享给其他互联网用户。

一、script 命令

script 命令是 Linux 系统自带一个的终端录制工具,功能与 asciinema 类似,可以将终端交互内容保存在本地的文本文件中,再使用 scriptreplay 命令进行播放。

录制
script -t 2>time.file -a output.file

其中 time.file 用于保存时间信息,output.file 则用于记录终端输出的内容及光标的移动等。
录制完成时使用 exit 命令或者 Ctrl+D 终止录制。

播放
scriptreplay time.file output.file

二、asciinema 本地录制

asciinema 安装比较简单,直接使用 pip 命令即可:
$ pip install asciinema

可使用如下命令将终端内容录制到本地文件中:
$ asciinema rec demo.cast
完成后使用 exitCtrl+D 结束录制。

使用如下命令播放前面录制的内容:
$ asciinema play demo.cast
播放时可使用 -s <n> 选项控制回放的速度,其中 n 为表示倍率的数字,数值越大播放速度越快。

其他选项的使用方法可通过 asciinema rec -hasciinema play -h 命令查看帮助信息。

三、浏览器播放

浏览器播放录制文件需要借助 asciinema-player 项目提供的两个库文件 asciinema-player.cssasciinema-player.js
这两个文件可以从该 Github 项目的 release 中下载,也可以直接通过 CDN 链接引入。

示例 HTML 代码(注意新增的 asciinema-player 标签)如下:

1
2
3
4
5
6
7
8
9
<html>
<head>
<link rel="stylesheet" type="text/css" href="asciinema-player.css" />
</head>
<body>
<asciinema-player src="demo.cast"></asciinema-player>
<script src="asciinema-player.js"></script>
</body>
</html>

播放效果如下:asciinema play

四、上传至 asciinema.org

首先访问 asciinema.org 创建一个新账户。
再使用 asciinema auth 命令生成自己电脑独有的 ID :

1
2
3
4
5
6
$ asciinema auth
Open the following URL in a web browser to link your install ID with your asciinema.org user account:

https://asciinema.org/connect/636713f1-db74-41c5-bb45-97fc213f3c94

This will associate all recordings uploaded from this machine (past and future ones) to your account, and allow you to manage them (change title/theme, delete) at asciinema.org.

通过浏览器访问上面生成的链接完成绑定,则此台设备上使用 asciinema rec 录制的内容都将自动上传至之前创建的账户中。

录制asciinema rec
停止录制后按下回车键自动上传至云端并返回播放链接。

1
2
3
4
5
6
asciinema: recording finished
asciinema: press <enter> to upload to asciinema.org, <ctrl-c> to save locally

View the recording at:

https://asciinema.org/a/9WlhbT4qnTr5cFWQQZNS0auIY

播放asciinema play <link>

个人账户界面如下:asciinema.org

如不方便将录制内容放置于外部的公网服务器上,也可以自行搭建类似的私人服务器。参考 asciinema-server 项目,可使用 docker 快速进行部署,不再做详细说明。

注意部署成功后修改 ~/.config/asciinema/config 配置文件,添加如下内容:

1
2
[api]
url = https://your.asciinema.host

参考资料

asciinema Docs