无法使用 termios.TIOCSTI 伪造终端输入 [英] Unable to fake terminal input with termios.TIOCSTI

查看:18
本文介绍了无法使用 termios.TIOCSTI 伪造终端输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我见过的大多数代码示例都试图从标准输入读取,没有本地回声.为此,他们修改了 "local mode" 标志以删除设置为回显输入字符".我以为我可以将输入模式"标志修改为 TIOCSTI 用于 "在输入队列中插入给定的字节.".但是,即使我以 root 身份运行脚本,它也没有任何效果.我写给 fd 的任何东西似乎都转到终端输出,而不是终端输入.基本上我想做的是这件事,但在纯python中.

Most of the code samples I've seen are trying to read from stdin without local echo. To do this they modify the "local modes" flag to remove the setting to "Echo input characters". I thought I could just modify the "input modes" flag to TIOCSTI which is for "Insert the given byte in the input queue.". However, even though I run the script as root, it has no effect. anything I write to the fd seems to go to the terminal output, rather than the terminal input. Basically what I want to do is this exact thing, but in pure 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
')
fd.close()

推荐答案

TIOCSTI 是一个 ioctl(记录在 tty_ioctl(4) 中),而不是终端设置,所以您不能使用 tcsetattr() - 您需要将假输入的每个字符提供给 ioctl().以前从未需要从 Python 执行 ioctl,但以下似乎适用于在不同的终端中运行 ls(指定为参数,例如 /dev/pts/13) 正在运行 Bash:

TIOCSTI is an ioctl (documented in tty_ioctl(4)), not a terminal setting, so you can't use tcsetattr() -- you need to feed each character of the fake input to ioctl() instead. Never had to do ioctl's from Python before, but the following seems to work for running an ls in a different terminal (specified as the argument, e.g. /dev/pts/13) that's running Bash:

import fcntl
import sys
import termios

with open(sys.argv[1], 'w') as fd:
    for c in "ls
":
        fcntl.ioctl(fd, termios.TIOCSTI, c)

顺便说一下,

TIOCSTI 需要 root 权限(或者 CAP_SYS_ADMIN 更具体,但这在实践中通常是相同的)——请参阅 capabilities(7).

TIOCSTI requires root privileges (or CAP_SYS_ADMIN to be more specific, but that's usually the same in practice) by the way -- see capabilities(7).

这篇关于无法使用 termios.TIOCSTI 伪造终端输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆