从 Java 执行 sh 文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14987214/
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
Execute sh file from Java
提问by Keir Nellyer
I am trying to execute an sh file via the following code (CentOS machine btw)
我正在尝试通过以下代码执行 sh 文件(CentOS 机器顺便说一句)
Runtime.getRuntime().exec("sh " + file.getPath());
I use this code for windows and it works fine
我将此代码用于 Windows,它工作正常
Runtime.getRuntime().exec("cmd /c start " + file.getPath());
Could it be because I'm using Screen in the .sh file? I am also using the java command to start the server so maybe I need to include these?
可能是因为我在 .sh 文件中使用 Screen 吗?我也在使用 java 命令来启动服务器,所以也许我需要包含这些?
Here are the contents of the sh file
下面是sh文件的内容
#!/bin/sh
BINDIR=$(dirname "$(readlink -fn "Runtime.getRuntime().exec(new String[]{"/bin/sh" ,"-c", file.getPath()});
")")
cd "$BINDIR"
screen -S PrivateServer java -Xms2048M -Xmx2048M -jar somejar.jar -o true
I am also running this code from a shutdown hook, could this be the issue? This is intended because the software is a game server and it is intended so that the user can use a restart command or have it auto restart without needing to setup anything them self.
我也在从关闭挂钩运行此代码,这可能是问题吗?这是因为该软件是一个游戏服务器,它的目的是让用户可以使用重启命令或让它自动重启,而无需自己设置任何东西。
Edit: I decided to output the errors to a text file and found this "Must be connected to a terminal." any ideas? I believe this is an issue to do with using screen.
编辑:我决定将错误输出到一个文本文件,发现这个“必须连接到终端”。有任何想法吗?我相信这是与使用屏幕有关的问题。
采纳答案by iTech
Since you confirmed that the file has executable permission, try to pass the argument as follows:
由于您确认该文件具有可执行权限,请尝试按如下方式传递参数:
##代码##So mainly provide the complete path for sh
and use -c
所以主要提供完整的路径供sh
使用-c
回答by Marcelo Tataje
Yo need to set the permissions for the operation, usually the "sh" files require execution permission in order to run this scripts from a Java Application. You must run the Java application as root (sudo su) or sudo java -jar. Or set full access to your script "sudo chmod 777 ..." well, not full access, but at least chmod +x for any user that wants to execute your script.
您需要为操作设置权限,通常“sh”文件需要执行权限才能从 Java 应用程序运行此脚本。您必须以 root (sudo su) 或 sudo java -jar 身份运行 Java 应用程序。或者设置对您的脚本的完全访问权限“sudo chmod 777 ...”好吧,不是完全访问权限,但对于任何想要执行您的脚本的用户,至少 chmod +x 。
Best regards.
最好的祝福。
回答by zeddarn
I recommend using org.apache.commons.exec.* to run such.
我建议使用 org.apache.commons.exec.* 来运行它。
回答by srnvs
It does not seem to have executable permissions, try executing "chmod +x shell_script_filename"
before executing the shell script
好像没有可执行权限,"chmod +x shell_script_filename"
在执行shell脚本前尝试执行