本文目录导读:

- 使用
script和scriptreplay命令 - 使用
expect脚本回放 - 使用
ttyrec和ttyplay - 使用
asciinema - 自定义Shell脚本回放
- 使用
script的高级回放脚本 - 使用建议
- 示例:完整的记录和回放流程
在Shell脚本中回放终端操作记录,主要有以下几种方法:
使用 script 和 scriptreplay 命令
这是最标准的方法,适合记录和回放完整的终端会话。
记录会话:
# 开始记录,会生成两个文件 script -t timing.log 2> timing.txt -a output.txt # 执行你的命令 ls -la echo "Hello World" # ... 其他操作 # 结束记录 exit
回放会话:
# 回放记录 scriptreplay timing.txt output.txt # 如果需要加速回放 # 2倍速回放 scriptreplay -t timing.txt output.txt -d 2 # 从特定时间点开始回放 scriptreplay -t timing.txt output.txt -s 5
使用 expect 脚本回放
适合需要交互式操作的记录回放:
#!/usr/bin/expect -f # 记录操作 log_file session.log log_user 1 # 模拟操作 send "ls -la\r" expect "$\ " send "echo 'Hello'\r" expect "$\ " send "exit\r" # 回放时,重放这些命令 close $log_file
使用 ttyrec 和 ttyplay
更简单的记录和回放工具:
# 安装 sudo apt-get install ttyrec # Debian/Ubuntu sudo yum install ttyrec # RHEL/CentOS # 记录会话 ttyrec session.log # 回放 ttyplay session.log # 控制回放速度 ttyplay -s 2 session.log # 2倍速
使用 asciinema
功能更强大的终端记录工具:
# 安装 pip install asciinema # 记录会话 asciinema rec session.cast # 回放 asciinema play session.cast # 在线分享 asciinema upload session.cast
自定义Shell脚本回放
对于简单命令的重放:
#!/bin/bash
# 命令记录文件
COMMAND_LOG="commands.txt"
# 记录函数
record_command() {
echo "$(date '+%Y-%m-%d %H:%M:%S') $@" >> "$COMMAND_LOG"
"$@"
}
# 回放函数
replay_commands() {
while IFS= read -r line; do
# 提取时间戳和命令
timestamp=$(echo "$line" | cut -d' ' -f1-2)
command=$(echo "$line" | cut -d' ' -f3-)
echo "Replaying at $timestamp: $command"
sleep 0.5 # 模拟延时
eval "$command"
done < "$COMMAND_LOG"
}
# 使用示例
case "$1" in
record)
# 记录模式下运行
record_command ls -la
record_command echo "Hello"
;;
replay)
replay_commands
;;
esac
使用 script 的高级回放脚本
更专业的回放脚本:
#!/bin/bash
# 记录会话
record_session() {
local output_file="session_$(date +%Y%m%d_%H%M%S).log"
local timing_file="timing_$(date +%Y%m%d_%H%M%S).log"
echo "Recording session to $output_file"
script -q -t "$timing_file" "$output_file"
}
# 回放会话
replay_session() {
local timing_file="$1"
local output_file="$2"
if [[ -z "$timing_file" || -z "$output_file" ]]; then
echo "Usage: $0 replay <timing_file> <output_file>"
exit 1
fi
# 回放
scriptreplay -t "$timing_file" "$output_file"
}
# 菜单选择
case "${1:-help}" in
record)
record_session
;;
replay)
shift
replay_session "$@"
;;
list)
echo "Available recordings:"
ls -la session_*.log timing_*.log 2>/dev/null || echo "No recordings found"
;;
*)
echo "Usage: $0 {record|replay|list}"
exit 1
;;
esac
使用建议
- 简单场景:使用
script+scriptreplay - 需要分享:使用
asciinema - 需要精确控制:使用
expect - 简单命令重放:自定义Shell脚本
示例:完整的记录和回放流程
# 1. 记录 script -t timing.txt -a session.txt # 执行命令... exit # 2. 回放(实时速度) scriptreplay timing.txt session.txt # 3. 加速回放(2倍速) scriptreplay timing.txt session.txt -d 2 # 4. 只输出不显示(静默回放) scriptreplay timing.txt session.txt -q
选择哪种方法取决于你的具体需求:是否需要交互、是否需要分享、记录时间等。