标准输入通过sudo处理。

huangapple go评论72阅读模式
英文:

Standard input through sudo

问题

Sure, here's the translated version:

我正在编写一个调用其他程序的Java程序,其中一些程序需要以root身份运行。

我考虑过将整个JAR文件以root身份运行,但这听起来像是一个安全风险,我宁愿只将某些程序以root身份运行。

目前,我创建了一个ProcessBuilder,并使用它的getStandardOutput方法实例化一个Writer,在命令sudo -S pacman <...>上。(-S表示‘从标准输入读取’)。

然后,我使用该读取器注入密码并进行刷新,目前为止一切正常。

然而,当pacman需要输入时(例如询问交互式的是/否问题),我尝试再次向Writer写入时,会因流已关闭而导致IOException。

如何获得一个真正可以将字符发送到pacman和其他以root身份运行的程序的Writer?

此程序只预计在UNIX系统上运行(Arch Linux、Debian、MacOS,以及可能的Windows的WSL),因此UNIX特定的解决方案是可以的,如果可能的话,我宁愿不使用JNI,因为它需要多次编译,但如果这是唯一的解决方案,也可以接受。我也可以将sudo替换为其他东西,只要它仍然以root身份运行即可。

英文:

I'm writing a Java program that calls other programs, and some of them need to be ran as root.

I thought about running the whole JAR as root but that sounds like a security risk, I'd rather run just some programs as root.

Currently, I create a ProcessBuilder and use its getStandardOutput method to instantiate a Writer, on the command sudo -S pacman &lt;...&gt;. (-S means ‘read from standard input’).

I then inject the password using that reader and flush it, so far so good.

However, when pacman expects input (for example when asking an interactive yes/no question), and I try to write to the Writer again, it fails with IOException because the stream is closed.

How can I get a Writer that can actually send characters to pacman and other programs ran as root?

This program is only expected to run on UNIX (Arch Linux, Debian, MacOS and maybe Window's WSL) so UNIX-specific solutions are fine, if possible I'd rather not use JNI because it requires to compile multiple times, but if that's the only solution it's fine. I'm also fine replacing sudo with something else as long as it's still ran as root.

答案1

得分: 1

如果这不是一个长期运行的服务,您可以运行 sudo -v 命令,以便让 sudo 缓存凭据,然后在您的 Java 程序中调用 sudo 而无需输入密码。如果您使用类似以下内容来调用您的 Java 程序,这将效果最佳:

#!/bin/bash

sudo -v
java -jar ...
英文:

If this is not a long-lived service, you could run sudo -v to have sudo cache the credentials and then invoke sudo in your Java program without needing to enter a password. This would work best if you invoked your Java program with something like:

#!/bin/bash

sudo -v
java -jar ...

huangapple
  • 本文由 发表于 2020年9月26日 20:32:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/64077708.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定