加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

假装在任何命令的bash中都是tty

发布时间:2020-12-15 19:04:01 所属栏目:安全 来源:网络整理
导读:参见英文答案 Trick an application into thinking its stdout is a terminal,not a pipe8个 每当我使用grep,并将其传递给其他程序时,都不会遵守–color选项.我知道我可以使用–color = always,但它还提供了一些其他命令,我想获得该命令的确切输出,如果我在t
参见英文答案 > Trick an application into thinking its stdout is a terminal,not a pipe8个
每当我使用grep,并将其传递给其他程序时,都不会遵守–color选项.我知道我可以使用–color = always,但它还提供了一些其他命令,我想获得该命令的确切输出,如果我在tty中,我将得到的输出.

所以我的问题是,是否有可能欺骗命令认为命令是在tty内运行的?

例如,跑步

grep --color word file # Outputs some colors
grep --color word file | cat # Doesn't output any colors

我希望能够写出如下内容:

IS_TTY=TRUE grep --color word file | cat  # Outputs some colors

This question似乎有一个可能做我想要的工具:empty – run processes and applications under pseudo-terminal (PTY),但从我在文档中可以阅读的内容,我不确定它可以帮我解决我的问题

有许多选项,如其他几个Stack Overflow答案所述(参见 Caarlos的 comment).我会在这里总结一下:

>使用脚本printf,不需要额外的依赖项:

0<&- script -qfce "ls --color=auto" /dev/null | cat

或者使用bash函数faketty来封装它:

faketty () {
    script -qfce "$(printf "%q " "$@")"
}
faketty ls --color=auto | cat

或者在鱼壳里:

function faketty
    script -qfce "(printf "%q " "$argv")"
end
faketty ls --color=auto | cat

(信用到这个answer)

http://linux.die.net/man/1/script
>使用unbuffer命令(作为期望的命令套件的一部分),遗憾的是这需要50mb安装,但这是最简单的解决方案:

sudo apt-get install expect-dev
unbuffer -p ls --color=auto | cat

或者如果你使用鱼壳:

function faketty
    unbuffer -p $argv
end
faketty ls --color=auto | cat

http://linux.die.net/man/1/unbuffer

这是一篇关于TTY如何工作以及伪TTY(PTY)是什么的伟大文章,如果你想了解linux shell如何使用文件描述符来传递输入,输出和信号,那么值得一看. http://www.linusakesson.net/programming/tty/index.php

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读