2016-07-14 7 views
1

私は、UNIXサーバにログインし、ユーザを切り替えて、いくつかのコマンドを実行し、これらのコマンドから作成したファイルを別のサーバにscpする必要があります。 私はサーバに接続し、sudoログインを実行してコマンドを実行できますが、別のリモートサーバに直接ファイルをscpすることはできません。Jschを使ったリモートサーバ間のファイル転送

私はこれにJsch jarを使用しています。以下は私のコードです。

公共ボイドexecuteChannel(セッションセッション、文字列コマンド、文字列PWD、リスト・ファイル)が例外をスロー{

logger.info("************************Start of executeChannel() method*****************************"); 
    Channel channel = session.openChannel("exec"); 

    // below line avoids "sudo: no tty present and no askpass program" error 

    ((ChannelExec) channel).setPty(true); 

    // this line ensures password prompt is not displayed after sudo user 
    /** 
    * -S The -S (stdin) option causes sudo to read the password from the standard input instead of the terminal device. 
    * -p The -p (prompt) option allows you to override the default password prompt and use a custom one. 
    */ 

    String filename = file.toString().replace("[", "").replace("]", "").replace(",", ""); 
    System.out.println("sudo -S -p '' "+command+" "+filename+" server2:/dir1/dir2/dir3/"); 

    ((ChannelExec)channel).setCommand("sudo -S -p '' "+command+" "+filename+" server2:/dir1/dir2/dir3/"); 

    channel.setInputStream(null);    
    ((ChannelExec)channel).setErrStream(System.err); 

    InputStream in = channel.getInputStream(); 
    OutputStream out=channel.getOutputStream(); 

    BufferedReader br = new BufferedReader(new InputStreamReader(in)); 

    channel.connect(); 
    out.write((pwd+"\n").getBytes()); 


    byte[] tmp=new byte[1024]; 
    while(true){ 
     logger.info("start of while(true) method, is channel connected? "+channel.isConnected()); 

     br.readLine(); 
     while(br.readLine() != null){ 
      System.out.println("channel.isConnected() "+channel.isConnected()); 
      int i = in.read(tmp, 0, 1024); 

      if(i<0) break; 

      System.out.println("printing putty console: \n"+new String(tmp,0,i)); 
     } 
     if (channel.isClosed()){ 
      System.out.println("Exit Status:- "+channel.getExitStatus()); 
      break; 
     } 

     try{ 
      Thread.sleep(1000); 
     } 
     catch(Exception e) { 
      e.printStackTrace(); 
     } 
    } 
    out.flush(); 
    br.close(); 
    System.out.println("DONE"); 

} 

コマンド=須藤SU -pentaho。 cd/dir1/dir2 /; ls -lrt; scp 上記のコードを実行すると、ls -lrtまでのコマンドが正しく実行され、出力を見ることができます。しかしその後、コードがハングします。 コードによって例外がスローされることはありません。したがって、私は何が起きているのか迷っています。

ご協力いただければ幸いです。

答えて

0

私はパテコンソールの出力を正しく表示していませんでした。私は問題を理解した。解決策はコマンドを変更することでした。

コマンドからsudo -S -p "を削除し、元のコマンドをsudoに置き換えます。su - user -c" my commands "がトリックを行いました。

関連する問題