Windows 执行.sh文件的Java代码

Windows 执行.sh文件的Java代码,windows,linux,unix,java,shell,Windows,Linux,Unix,Java,Shell,我有一个.sh文件存储在一些Linux系统中。文件的完整路径为: /comviva/CPP/Kokila/TransactionHandler/scripts/stopTH.sh 我正试着用手来执行它 Runtime.getRuntime().exec(`/comviva/CPP/Kokila/TransactionHandler/scripts/stopTH.sh`) 但它抛出了一些例外 我想在MS Windows环境中从java程序执行该文件;可能吗?这是我的代码。正如评论所说,在Lin

我有一个
.sh
文件存储在一些Linux系统中。文件的完整路径为:

/comviva/CPP/Kokila/TransactionHandler/scripts/stopTH.sh
我正试着用手来执行它

Runtime.getRuntime().exec(`/comviva/CPP/Kokila/TransactionHandler/scripts/stopTH.sh`)
但它抛出了一些例外


我想在MS Windows环境中从java程序执行该文件;可能吗?

这是我的代码。正如评论所说,在Linux上工作,在Windows(XP)上失败。恐怕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;
}
/**执行一个abritary shell命令。
*以字符串形式返回输出。
*在Linux上工作,在Windows上失败,
*对OSX还不确定。
*/
公共静态字符串ExecuteCommand(最终字符串Cmd){
布尔DB=false;
中频(DB){
Debug.Log(“***Misc.ExecuteCommand()***”);
Log(“--Cmd”,Cmd);
}
字符串输出=”;
字符串ELabel=“”;
字符串[]命令=新字符串[3];
if(Misc.OSName().equals(“WINDOWS”)){
命令[0]=System.getenv(“ComSPec”);
命令[1]=“C”;
}否则{
命令[0]=“/bin/bash”;
命令[1]=“c”;
}
命令[2]=Cmd;
中频(DB){
Log(“--Command”,Command);
}
if(Misc.OSName().equals(“WINDOWS”)){
Log(“这是WINDOWS;我放弃”);
返回“”;
}
试一试{
ELabel=“newprocessbuilder()”;
ProcessBuilder pb=新的ProcessBuilder(命令);
ELabel=“redirectErrorStream()”;
pb.重定向错误流(真);
ELabel=“pb.start()”;
进程p=pb.start();
ELabel=“p.getInputStream()”;
InputStream pout=p.getInputStream();
ELabel=“p.waitFor()”;
int ExitCode=p.waitFor();
int Avail;
while(true){
ELabel=“pout.available()”;

如果(pout.available()我在这里做了一个快速测试,那么假设您的机器上有/bin/bash,那么下面的测试将起作用:

my/tmp/test.sh:

#!/bin/bash
echo `ls`
我的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();
}
输出:当前目录中的所有文件


编辑:我有点忽略了“从windows执行”的注释。我不知道你的意思。

要在windows上执行
.sh
脚本,你必须安装一个合适的命令解释器。例如,你可以在windows框上安装环境,并使用它的
bash
解释器

但是,即使使用Cygwin,Windows也不是Linux。有些脚本在没有改动的情况下无法从一个环境移植到另一个环境。如果在Linux环境中通过Java执行脚本时遇到问题,我宁愿在该环境中调试该问题


请记住,您可以在调试模式下启动Linux上的Java进程,并将Windows中的IDE调试器连接到该远程进程。

谢谢大家的回答。我找到了解决问题的方法。对于这种情况,我们需要将我的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{

        }
}
谢谢。

您可以制作一个可以在windows上运行的.bat文件(批处理文件)。 将.sh文件的内容放入.bat文件中 从应用程序启动一个流程,如:

Process.Start("myFile.bat");

不可能在Windows中以本机方式运行Unix shell脚本,这正是您尝试执行的操作--您需要将该Unix shell脚本转换(而不仅仅是重命名)为Windows批处理文件(具有.bat或.cmd文件扩展名/后缀)。引发了哪个异常?您使用的是哪个版本的Java?提问时始终列出异常。您提到了Linux系统和Windows系统。shell脚本位于您的Linux系统上,对吗?以及您的Java应用程序(应该启动shell脚本)位于Windows系统上。是否正确?什么是“某些异常”。这是一个重要信息!offtopic,属于stackoverflow;顺便说一句,您不能直接执行shell脚本,您必须执行
bash
。在Java中,方法和变量的第一个字符不应大写。您使用
连接
/
会话
类:它们来自哪个库?