Javaでシェルスクリプトを実行するとエラーが発生する方法は?

Javaでシェルスクリプトを実行するとエラーが発生する方法は?

Javaを使用してシェルスクリプトを実行していますが、うまくいきます。ここでこのスクリプトからエラーを取得したいと思います。たとえば、スクリプトがあり、エラーがありますが、そのエラーの行とメッセージを取得したいとします。

これはシェルスクリプトを実行するコードです。

 try {
                 JSch jsch=new JSch();
                 com.jcraft.jsch.Session session=jsch.getSession(jTextField1.getText() ,jTextField3.getText(),22);
                 session.setPassword(jTextField2.getText());

          java.util.Properties config = new java.util.Properties(); 
          config.put("StrictHostKeyChecking", "no");
        session.setConfig(config);


                 session.connect();
                 ChannelExec channel=(ChannelExec) session.openChannel("exec");
                 channel.setInputStream(System.in);
                 channel.setOutputStream(System.out);
                 /*cp .mbb.sh to /
                 chmod +x mbb.sh
                 ./mbb.sh param1 param2*/

                 //chaine de caractére pour concatener les parametres 
                 String param="";
                 for ( int j=0 ; j<list.size();j++){
                     param=param+" "+list.get(j).getText();
                 }
                 DB_Operation db = new DB_Operation();
                 db.getConnection();

                 channel.setCommand("bash"+" "+valeururl+ param);
                                      //channel.setCommand("bash script.sh");


                 channel.connect(30000);
                 InputStream in = channel.getInputStream();
                 BufferedReader reader = new BufferedReader(new InputStreamReader(in));
                 String line ; 
                result.add("Build successful \n");
                 while((line =reader.readLine())!=null){
                     result.add(line);
                 }



                 if  ( session.isConnected()){
                     JOptionPane.showMessageDialog(rootPane, "Connecté");
                Resultexec  rs =new Resultexec(result);
                     xx.dispose();
                    rs.createAndShowGUI();

                 }



             } catch (JSchException ex) {

                 result.clear();
                  result.add("Build failed \n");
                 msg_console = ex.getMessage();
                 result.add(msg_console);

                       JOptionPane.showMessageDialog(rootPane, "Erreur de connexion ");
                Resultexec  rs =new Resultexec(result);
                     xx.dispose();
                    rs.createAndShowGUI();

             } catch (IOException ex) {
                 result.clear();
                 result.add("Build failed \n");
                 msg_console = ex.getMessage();                    
                 result.add(msg_console);   


                Resultexec  rs =new Resultexec(result);
                     xx.dispose();
                    rs.createAndShowGUI();

             }

答え1

こんにちは、コードをいくつか修正しましたが動作します。

package dashboard;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;

import java.awt.Color;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.LineBorder;
import javax.swing.border.TitledBorder;

/**
 *
 * @author ASUS
 */
public class NewJFrame extends javax.swing.JFrame  {
  private int valeurcol ; 
private static NewJFrame xx =new NewJFrame();
private static List <JTextField> list = new ArrayList();
 ArrayList<String> li = new ArrayList();
 private static List <String> result= new ArrayList();
 String valeururl;
String msg_console="";

// une variable pour récuperer warming message au cours de la connexion 



    /**
     * Creates new form NewJFrame1
     */
    public NewJFrame() {
        initComponents(); 





        this.setExtendedState(this.MAXIMIZED_BOTH);
        this.setSize(Toolkit.getDefaultToolkit().getScreenSize());
              System.out.println(jLabel3.getLocation());

    }
    NewJFrame(int valeurcol, String valeururl)  {
            initComponents();
            this.valeururl=valeururl;
                  this.setExtendedState(this.MAXIMIZED_BOTH);
        this.setSize(Toolkit.getDefaultToolkit().getScreenSize());

       try {
           this.valeurcol = valeurcol ;



           DB_Operation db=new DB_Operation();
           ResultSet rs= db.searchQuery("select * from utilitaires where id_script='"+valeurcol+"'");
           while(rs.isBeforeFirst()){
               while(rs.next()){
                   descri.setText(rs.getString(3));
                     nscript.setText(rs.getString(2));
               }
           }          DB_Operation db1=new DB_Operation();
           ResultSet rs1 = db1.searchQuery("select * from parametres where id_script='"+valeurcol+"'");
           int cpt = 0 ; 

           while (rs1.isBeforeFirst()){
               while (rs1.next()){
                   // pur récuperer le libelé 
                    li.add(rs1.getString(2));
                   cpt++;

               }
           }
                 LineBorder a =new javax.swing.border.LineBorder(Color.black);


jTextField1.setBorder(a); 
jTextField2.setBorder(a); 
jTextField3.setBorder(a);


 for ( int  j =0 ; j<cpt ; j++){
          JTextField c=new JTextField();
            c.setText("");
            c.setBorder(a);
            c.setSize(190, 28);
         list.add(c);
            c.setLocation(263,456+55*j);
            jPanel1.add(c);
            jPanel1.revalidate();
            jPanel1.repaint();  


          JLabel l = new JLabel();
            l.setLocation(157,456+49*j);
            l.setSize(120, 20);
            l.setText(li.get(j));
            jPanel1.add(l);


          }
          JButton bt_exec = new JButton();
          bt_exec.setSize(100, 30);
          bt_exec.setText("Exécuter");
          bt_exec.setLocation(263, 456+55*cpt);
          jPanel1.add(bt_exec);

         bt_exec.addActionListener(new ActionListener() {
             @Override
               public void actionPerformed(ActionEvent e) {

                 try {
                     JSch jsch=new JSch();
                     com.jcraft.jsch.Session session=jsch.getSession(jTextField1.getText() ,jTextField3.getText(),22);
                     session.setPassword(jTextField2.getText());

              java.util.Properties config = new java.util.Properties(); 
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);


                     session.connect();
                       Channel channel = null;
                      channel= session.openChannel("exec");

                     String param="";
                     for ( int j=0 ; j<list.size();j++){
                         param=param+" "+list.get(j).getText();
                     }
                     DB_Operation db = new DB_Operation();
                     db.getConnection();
                     ( ( ChannelExec ) channel ).setCommand( "bash"+" "+valeururl+ param );

       channel.connect();

        BufferedReader reader = new BufferedReader( new InputStreamReader( channel.getInputStream() ) );
            BufferedReader errorReader = new BufferedReader( new InputStreamReader(
                    ( ( ChannelExec ) channel ).getErrStream() ) );



                     String lineerror ; 
                    result.add("Build successful \n");
                     while((lineerror =errorReader.readLine())!=null){
                         result.add(lineerror);

                     }
                   String line1 ; 
                    result.add("Build successful \n");
                     while((line1 =reader.readLine())!=null){
                         result.add(line1);

                     }

      reader.close();
            errorReader.close();


                if  ( session.isConnected()){
                         JOptionPane.showMessageDialog(rootPane, "Connecté");
                    Resultexec  rs =new Resultexec(result);
                         xx.dispose();
                        rs.createAndShowGUI();

                     }



                 } catch (JSchException ex) {

                     result.clear();
                      result.add("Build failed \n");
                     msg_console = ex.getMessage();
                     result.add(msg_console);

                           JOptionPane.showMessageDialog(rootPane, "Erreur de connexion ");
                    Resultexec  rs =new Resultexec(result);
                         xx.dispose();
                        rs.createAndShowGUI();

                 } catch (IOException ex) {

                     result.clear();
                     result.add("Build failed \n");
                     msg_console = ex.getMessage();                    
                     result.add(msg_console);   


                    Resultexec  rs =new Resultexec(result);
                         xx.dispose();
                        rs.createAndShowGUI();

                 } 
               }
           });

          JPanel exec = new JPanel();
           TitledBorder x =new javax.swing.border.TitledBorder(a);

             x.setTitle("Zone d'éxecution");
              exec.setBorder(x);
            exec.setLocation(100, 456+55*(cpt+1));
           exec.setSize(721, 257);
           exec.setBackground(Color.white);
       //  jPanel1.add(exec);


       } catch (SQLException ex) {
           Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
       }


    }
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jPanel2 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jPanel1 = new javax.swing.JPanel();
        jLabel4 = new javax.swing.JLabel();
        nscript = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        descri = new javax.swing.JTextArea();
        jLabel1 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jTextField2 = new javax.swing.JTextField();
        jTextField3 = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        jLabel13 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jPanel2.addAncestorListener(new javax.swing.event.AncestorListener() {
            public void ancestorMoved(javax.swing.event.AncestorEvent evt) {
                jPanel2AncestorMoved(evt);
            }
            public void ancestorAdded(javax.swing.event.AncestorEvent evt) {
            }
            public void ancestorRemoved(javax.swing.event.AncestorEvent evt) {
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 1174, Short.MAX_VALUE)
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 955, Short.MAX_VALUE)
        );

        jPanel1.setBackground(new java.awt.Color(255, 255, 255));

        jLabel4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/dashboard/Image/unnamed.jpg"))); // NOI18N

        nscript.setFont(new java.awt.Font("Tahoma", 1, 36)); // NOI18N
        nscript.setForeground(new java.awt.Color(102, 204, 204));
        nscript.setText("Nom script");

        descri.setEditable(false);
        descri.setColumns(20);
        descri.setRows(5);
        jScrollPane2.setViewportView(descri);

        jLabel1.setText("User");

        jTextField1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextField1ActionPerformed(evt);
            }
        });

        jLabel2.setText("Password");

        jLabel3.setText("Serveur");

        jTextField3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextField3ActionPerformed(evt);
            }
        });

        jLabel5.setIcon(new javax.swing.ImageIcon(getClass().getResource("/dashboard/Image/back.png"))); // NOI18N

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGap(100, 100, 100)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(jPanel1Layout.createSequentialGroup()
                                        .addGap(57, 57, 57)
                                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                            .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 190, javax.swing.GroupLayout.PREFERRED_SIZE)
                                            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                                .addGroup(jPanel1Layout.createSequentialGroup()
                                                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                                        .addComponent(jLabel1)
                                                        .addComponent(jLabel2))
                                                    .addGap(50, 50, 50)
                                                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 190, javax.swing.GroupLayout.PREFERRED_SIZE))
                                                .addGroup(jPanel1Layout.createSequentialGroup()
                                                    .addComponent(jLabel3)
                                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                                    .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, 190, javax.swing.GroupLayout.PREFERRED_SIZE)))))
                                    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 721, javax.swing.GroupLayout.PREFERRED_SIZE)))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGap(339, 339, 339)
                                .addComponent(nscript)))
                        .addGap(0, 330, Short.MAX_VALUE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 240, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jLabel5)))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel5)))
                .addGap(26, 26, 26)
                .addComponent(nscript)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(59, 59, 59)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel1))
                        .addGap(27, 27, 27)
                        .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jLabel2))
                .addGap(27, 27, 27)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3))
                .addContainerGap(1239, Short.MAX_VALUE))
        );

        jScrollPane1.setViewportView(jPanel1);

        jLabel13.setIcon(new javax.swing.ImageIcon(getClass().getResource("/dashboard/Image/back (1).png"))); // NOI18N
        jLabel13.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jLabel13MouseClicked(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(5, 5, 5)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 4, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(579, 579, 579)
                    .addComponent(jLabel13)
                    .addContainerGap(580, Short.MAX_VALUE)))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 933, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(40, 40, 40)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(934, 934, 934)
                    .addComponent(jLabel13, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(980, Short.MAX_VALUE)))
        );

        pack();
    }// </editor-fold>                        

    private void jPanel2AncestorMoved(javax.swing.event.AncestorEvent evt) {                                      
        // TODO add your handling code here:
    }                                     

    private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {                                            
        // TODO add your handling code here:
    }                                           

    private void jTextField3ActionPerformed(java.awt.event.ActionEvent evt) {                                            
        // TODO add your handling code here:
    }                                           

    private void jLabel13MouseClicked(java.awt.event.MouseEvent evt) {                                      
        PageAdmin pa = new PageAdmin();
        this.dispose();
        pa.setVisible(true);
    }                                     

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                xx.setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JTextArea descri;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel13;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField2;
    private javax.swing.JTextField jTextField3;
    private javax.swing.JLabel nscript;
    // End of variables declaration                   




}

関連情報