大部分 code samples我见过正在尝试在没有本地回声的情况下从 stdin 读取。为此,他们修改了 "local modes"删除 setting to "Echo input characters" 的标志.我以为我可以将“输入模式”标志修改为 TIOCSTI
,它用于 "Insert the given byte in the input queue." .但是,即使我以 root 身份运行脚本,它也没有任何效果。我写到 fd 的任何东西似乎都进入了终端输出,而不是终端输入。基本上我想做的是 this exact thing , 但在纯 python 中。
"""
termfake.py
Usage: sudo python termfake.py /dev/ttys002
Get the tty device path of a different local termimal by running `tty`
in that terminal.
"""
import sys
import termios
fd = open(sys.argv[1], 'w')
fdno = fd.fileno()
# Returns [iflag, oflag, cflag, lflag, ispeed, ospeed, cc]
tatters = termios.tcgetattr(fdno)
print('original', tatters)
tatters[0] = termios.TIOCSTI
print('TIOCSTI', termios.TIOCSTI)
# Set iflag
termios.tcsetattr(fdno, termios.TCSANOW, tatters)
# Verify setting change
with open('/dev/ttys002', 'w') as fd2:
print('modified', termios.tcgetattr(fd2.fileno()))
fd.write('This is test\n')
fd.close()
最佳答案
TIOCSTI
是一个 ioctl(记录在 tty_ioctl(4) 中),而不是终端设置,因此您不能使用 tcsetattr()
- 您需要为每个ioctl()
的伪输入字符。以前从不需要从 Python 执行 ioctl,但下面的命令似乎适用于在不同的终端中运行 ls
(指定为参数,例如 /dev/pts/13 ) 正在运行 Bash:
import fcntl
import sys
import termios
with open(sys.argv[1], 'w') as fd:
for c in "ls\n":
fcntl.ioctl(fd, termios.TIOCSTI, c)
TIOCSTI
需要 root 权限(或 CAP_SYS_ADMIN
更具体,但在实践中通常是相同的)顺便说一句——参见 capabilities(7) .
关于python - 无法使用 termios.TIOCSTI 伪造终端输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29614264/