来自 Java 的 Linux 命令

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/126116/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 11:07:15  来源:igfitidea点击:

Linux commands from Java

javalinux

提问by Sergio del Amo

Is it possbile to execute linux commands with java? I am trying to create a web servlet to allow ftp users to change their passwords without ssh login access. I would like to execute the next commands:

可以用java执行linux命令吗?我正在尝试创建一个 Web servlet,以允许 ftp 用户在没有 ssh 登录访问权限的情况下更改他们的密码。我想执行以下命令:

# adduser -s /sbin/nologin clientA -d /home/mainclient/clientA
# passwd clientA
# cd /home/mainclient; chgrp -R mainclient clientA
# cd /home/mainclient/clientA; chmod 770 .

回答by Craig Day

Check out this.

看看这个

However, doing what you are talking about is way outside spec, and I wouldnt reccommend it. To get it to work you are going to either run your app server as root, or use some other mechanism to give the user the app server is running as permission to execute these privileged commands. One small screw-up somewhere and you are "owned".

但是,做你所说的超出规范,我不会推荐它。为了让它工作,你要么以 root 身份运行你的应用程序服务器,要么使用其他一些机制来授予正在运行应用程序服务器的用户作为执行这些特权命令的权限。某个地方的一个小问题,你就“拥有”了。

回答by Josh Moore

Use:

利用:

Runtime.getRuntim().exec("Command");

where Command is the command string you want to execute.

其中 Command 是您要执行的命令字符串。

回答by Vilmantas Baranauskas

If you invoke those commands from Java, make sure to pack multiple commands to a single shell-script. This will make invocation much easier.

如果您从 Java 调用这些命令,请确保将多个命令打包到一个 shell 脚本中。这将使调用更加容易。

回答by Chris

The java RunTimeobject has exec methods to run commands in a separate process

java RunTime对象具有 exec 方法来在单独的进程中运行命令

回答by Andreas Kraft