在 Linux 系统中,抢占 /dev/pts/X
(伪终端)通常是指一个进程接管或控制另一个进程正在使用的终端会话。这可以通过多种方式实现,但需要谨慎操作,因为可能会干扰现有会话。
1. 基本原理
/dev/pts/X
是伪终端(Pseudo-Terminal Slave),由ptmx
(主设备)动态创建。- 每个终端会话(如 SSH、tmux、screen)对应一个
/dev/pts/X
。 - 抢占终端的核心方法:
- 直接写入输出:向
/dev/pts/X
发送数据,影响当前显示。 - 劫持输入:模拟按键输入到目标终端(需权限)。
- 信号控制:发送
SIGSTOP
/SIGCONT
暂停/恢复进程的终端交互。
- 直接写入输出:向
2. 方法一:直接向终端写入数据
(1) 查找目标终端
# 查看当前活动的 pts
who
输出示例:
user pts/0 2024-01-01 10:00 (192.168.1.100)
user pts/1 2024-01-01 10:05 (tmux)
(2) 向目标终端发送消息
echo "Hello from another process!" > /dev/pts/1
这会直接在 pts/1
的屏幕上显示消息。
(3) 劫持 Shell(模拟用户输入)
如果需要让目标终端执行命令:
# 使用 script/socat/ttywrite 等工具写入输入流
printf "ls -l\r\n" > /dev/pts/1
⚠️ 注意:如果目标 shell 未正确处理输入,可能会导致混乱。
3. 方法二:通过 TIOCSTI
ioctl() 注入按键
更底层的方法是使用 ioctl(TIOCSTI)
,它允许将字符插入终端的输入缓冲区:
(1) C代码示例
#include <fcntl.h>
#include <sys/ioctl.h>
int main() {
int fd = open("/dev/pts/1", O_RDWR);
if (fd < 0) {
perror("open");
return -1;
}
char *cmd = "ls -l\r\n"; // \r\n = Enter键
while (*cmd != '\0') {
if (ioctl(fd, TIOCSTI, cmd++) < 0) { // TIOCSTI: Insert字符到输入队列
perror("ioctl");
break;
}
}
close(fd);
return 0;
}
编译并运行:
gcc inject_terminal.c -o inject_terminal && ./inject_terminal
此时 pts/1
会收到 ls -l
+ Enter,就像用户手动输入一样。
🔹 限制:需要 root / CAP_SYS_ADMIN (或与目标终端同一用户)。
4. 方法三:通过信号控制进程
如果目标是暂停某个占用终端的进程:
# (a) SIGSTOP: Pause the process using the terminal.
pkill -SIGSTOP -t pts/1
# (b) SIGCONT: Resume it later.
pkill -SIGCONT -t pts/1
# (c) Kill all processes on a terminal.
fuser -k /dev/pts/1
5. FAQ & Troubleshooting
❓ Q: Permission denied?
- ✅ Root/CAP_SYS_ADMIN can control any terminal.
- ✅ Same user can control their own terminals (
pts/*
).
❓ Q: Why doesn’t my input appear?
- Check if the terminal is in raw mode (
stty -a
) or blocked by another process.
❓ Q: How to prevent this?
- Use
mesg n
to disable non-root writes to your terminal:mesg n # Disable writes to current tty.
6. Advanced Topics
Method | Pros | Cons |
---|---|---|
echo > /dev/pts/X |
Simple | No input simulation |
TIOCSTI ioctl() |
Simulates real keypresses | Needs privileges |
Signal Control (SIGSTOP ) |
Freezes processes | Doesn’t inject data |
🛑 Warning: Unauthorized terminal takeover may violate security policies!
Use only for debugging or with permission.
如果你有具体的使用场景(如调试、自动化),可以进一步优化方案!
内容由零声教学AI助手提供,问题来源于学员提问