1

私の目的は、Java アプリケーションを使用して Linux サーバーに接続し、Linux コマンドを実行することです。JSch API を使用して既にこれを達成していますが、一度に複数のコマンドを実行する方法がわかりません。

特定のディレクトリに移動し、そのディレクトリから別のコマンドを実行する必要があるため、これは私にとって問題です。私のアプリケーションは、2 番目のコマンドが正しいディレクトリで実行される前に終了します。

これは、パラメーターとして渡されたときに1つのLinuxコマンドを文字列として実行し、出力を出力する私の方法です。

public void connect(String command1){

try {
        JSch jsch = new JSch();

        Session session = jsch.getSession(user, host, port);
        session.setPassword(password);
        session.setConfig("StrictHostKeyChecking", "no");
        session.connect();
        System.out.println("Connected");

        Channel channel = session.openChannel("exec");
        ((ChannelExec)channel).setCommand(command1);
        channel.setInputStream(null);
        ((ChannelExec)channel).setErrStream(System.err);

        InputStream in = channel.getInputStream();
        channel.connect();
        byte[] tmp = new byte[1024];
        while(true){
            while(in.available()>0){
            int i=in.read(tmp, 0, 1024);
            if(i<0)break;
            System.out.print(new String(tmp, 0, i));
          }
          if(channel.isClosed()){
            System.out.println("exit-status: "+channel.getExitStatus());
            break;
          }
          try {
              Thread.sleep(1000);
          }
          catch(Exception ee){
              ee.printStackTrace();
          }
        }

        channel.disconnect();
        session.disconnect();
        System.out.println("DONE");

  }
catch(Exception e){
        e.printStackTrace();
    }

}

一度に2つのコマンドを実行する方法はありますか?

4

1 に答える 1

2

リモート マシンで通常のシェルが開始されている場合は、;or&&構成を使用してさらに多くのことを行います。

のように

cd /home/foo/banana ; do_things

また

cd /home/foo/banan && do_things #do_things will only be run if the cd command is successfull
于 2012-09-06T13:48:27.040 に答える