Java code to execute a .sh file

后端 未结 5 1000
暖寄归人
暖寄归人 2020-12-22 05:34

I have a .sh file stored in some Linux system. The full path of the file is:

/comviva/CPP/Kokila/TransactionHandler/scripts/stopTH.sh
         


        
5条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-22 06:05

    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:

    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.

提交回复
热议问题