Linux 执行 .sh 文件的 Java 代码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6464797/
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
Java code to execute a .sh file
提问by user778900
I have a .sh
file stored in some Linux system. The full path of the file is:
我有一个.sh
文件存储在一些 Linux 系统中。文件的完整路径是:
/comviva/CPP/Kokila/TransactionHandler/scripts/stopTH.sh
I am tring to execute it by
我想通过
Runtime.getRuntime().exec(`/comviva/CPP/Kokila/TransactionHandler/scripts/stopTH.sh`)
but it is throwing some exception.
但它抛出了一些异常。
I want to execute that file from my java program in an MS-Windows environment; is it possible?
我想在 MS-Windows 环境中从我的 java 程序执行该文件;是否可以?
回答by user778900
Here is my code. As the comment says, works on Linux, fails on Windows (XP). AFAIK the problem with Windows is that cmd.exe is weird regarding it's parameters. For your specific sub-task you probably can get it to work by playing with quotes and maybe embedding the sub-task parameters in the subtask itself.
这是我的代码。正如评论所说,在 Linux 上工作,在 Windows (XP) 上失败。AFAIK Windows 的问题在于 cmd.exe 的参数很奇怪。对于您的特定子任务,您可能可以通过使用引号并可能在子任务本身中嵌入子任务参数来使其工作。
/** Execute an abritrary shell command.
* returns the output as a String.
* Works on Linux, fails on Windows,
* not yet sure about OS X.
*/
public static String ExecuteCommand( final String Cmd ) {
boolean DB = false ;
if ( DB ) {
Debug.Log( "*** Misc.ExecuteCommand() ***" );
Debug.Log( "--- Cmd", Cmd );
}
String Output = "";
String ELabel = "";
String[] Command = new String[3];
if ( Misc.OSName().equals( "WINDOWS" ) ) {
Command[0] = System.getenv( "ComSPec" );
Command[1] = "/C";
} else {
Command[0] = "/bin/bash";
Command[1] = "-c";
}
Command[2] = Cmd;
if (DB ) {
Debug.Log( "--- Command", Command );
}
if ( Misc.OSName().equals( "WINDOWS" ) ) {
Debug.Log( "This is WINDOWS; I give up" );
return "";
}
try {
ELabel = "new ProcessBuilder()";
ProcessBuilder pb = new ProcessBuilder( Command );
ELabel = "redirectErrorStream()";
pb.redirectErrorStream( true );
ELabel = "pb.start()";
Process p = pb.start();
ELabel = "p.getInputStream()";
InputStream pout = p.getInputStream();
ELabel = "p.waitFor()";
int ExitCode = p.waitFor();
int Avail;
while ( true ) {
ELabel = "pout.available()";
if ( pout.available() <= 0 ) {
break;
}
ELabel = "pout.read()";
char inch = (char) pout.read();
Output = Output + inch;
}
ELabel = "pout.close()";
pout.close();
} catch ( Exception e ) {
Debug.Log( ELabel, e );
}
if ( DB ) {
Debug.Log( "--- Misc.ExecuteCommand() finished" );
}
return Output;
}
}
}
回答by rompetroll
I did a quick test here, the following works assuming you have /bin/bash on your machine:
我在这里做了一个快速测试,假设你的机器上有 /bin/bash,下面的工作:
my /tmp/test.sh:
我的/tmp/test.sh:
#!/bin/bash
echo `ls`
my java code:
我的Java代码:
try {
InputStream is = Runtime.getRuntime().exec("/bin/bash /tmp/test.sh").getInputStream();
int i = is.read();
while(i > 0) {
System.out.print((char)i);
i = is.read();
}
} catch (IOException e) {
e.printStackTrace();
}
output: all files in current directory
输出:当前目录下的所有文件
edit: i kinda overlooked that "execute from windows" comment. I don't know what you mean with that.
编辑:我有点忽略了“从 Windows 执行”的评论。我不知道你是什么意思。
回答by sudocode
To execute a .sh
script on Windows, you would have to have a suitable command interpreter installed. For example, you could install the Cygwinenvironment on your Windows box and use it's bash
interpreter.
要.sh
在 Windows 上执行脚本,您必须安装合适的命令解释器。例如,您可以在 Windows 机器上安装Cygwin环境并使用它的bash
解释器。
However, Windows is not Linux even with Cygwin. Some scripts will not port from one environment to the other without alterations. If I had a problem executing a script via Java in Linux environment, I would prefer to debug the issue in that environment.
但是,即使使用 Cygwin,Windows 也不是 Linux。某些脚本无法在不进行更改的情况下从一种环境移植到另一种环境。如果我在 Linux 环境中通过 Java 执行脚本时遇到问题,我更愿意在该环境中调试问题。
Remember, you could start your Java process on Linux in debug mode and attach your IDE debugger in Windows to that remote process.
请记住,您可以在 Linux 上以调试模式启动 Java 进程,并将 Windows 中的 IDE 调试器附加到该远程进程。
回答by user778900
Thanks everybody for your responses. I found a solution to the problem. For this kind of situation we need to bind my Windows machine to Linux system. Here is the code that worked:
谢谢大家的回复。我找到了解决问题的方法。对于这种情况,我们需要将我的 Windows 机器绑定到 Linux 系统。这是有效的代码:
public String executeSHFile(String Username, String Password,String Hostname)
{
String hostname = Hostname;
String username = Username;
String password = Password;
try{
Connection conn = new Connection(hostname);
conn.connect();
boolean isAuthenticated = conn.authenticateWithPassword(username, password);
if (isAuthenticated == false)
throw new IOException("Authentication failed.");
Session sess = conn.openSession();
sess.execCommand("sh //full path/file name.sh");
System.out.println("Here is some information about the remote host:");
InputStream stdout = new StreamGobbler(sess.getStdout());
BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
while (true)
{
String line = br.readLine();
if (line == null)
break;
current_time=line;
System.out.println(line);
}
System.out.println("ExitCode: " + sess.getExitStatus());
/* Close this session */
sess.close();
/* Close the connection */
conn.close();
}catch(IOException e)
{
e.printStackTrace(System.err);
System.exit(2);
}finally{
}
}
Thank you.
谢谢你。
回答by Mokhtar Ashour
you may make a .bat file(batch file), that can run on windows. put the content of the .sh file in the .bat file start a process from your application like :
您可以制作一个可以在 Windows 上运行的 .bat 文件(批处理文件)。将 .sh 文件的内容放在 .bat 文件中,从您的应用程序启动一个进程,例如:
Process.Start("myFile.bat");