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

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

问题描述

我看到的大多数代码示例从标准输入读取而没有本地回显.为此,他们修改了本地模式" 标志以将其删除设置为回声输入字符" .我以为我可以将输入模式"标志修改为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\n')
fd.close()

推荐答案

TIOCSTI是一个ioctl(记录在tty_ioctl(4)中),而不是终端设置,因此您不能使用tcsetattr()-您需要将伪输入的每个字符输入ioctl().以前从未需要从Python进行过ioctl操作,但是以下操作似乎可以在正在运行Bash的另一个终端(指定为参数,例如/dev/pts/13 )中运行ls:

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\n":
        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天全站免登陆