2012-01-24 32 views
1

Javaコードからいくつかのunixコマンドを実行しようとしています。私は現在、GoogleのExpect4Jライブラリを使用しており、十分に文書化されたライブラリを公開しています。javaからのsshコマンド出力のキャプチャ

問題は、最後に実行したコマンドの出力をキャプチャしようとしていますが、取得できません。誰もが知っている、私はここで間違って何ですか?

私がここで解決しようとしている問題は、私が接続できるかどうかに基づいて、私のjumphostに接続し、SSHをいくつかの他のサーバーに接続することです。

私が書いたコードは、以下に貼り付けられています。助けてください !!!

import java.io.IOException; 
import java.util.ArrayList; 
import java.util.Hashtable; 
import java.util.List; 

import org.apache.oro.text.regex.MalformedPatternException; 
import org.junit.internal.matchers.SubstringMatcher; 

import com.jcraft.jsch.ChannelShell; 
import com.jcraft.jsch.JSch; 
import com.jcraft.jsch.Session; 
import com.bean.Server; 

import expect4j.Closure; 
import expect4j.Expect4j; 
import expect4j.ExpectState; 
import expect4j.matches.Match; 
import expect4j.matches.RegExpMatch; 

public class ExpectTest1 { 

    public final String RETURN_CHAR = "\r "; 
    public String expectOut = ""; 

    private StringBuilder sBuilder = new StringBuilder(); 

    /** 
    * @param args 
    */ 
    public static void main(String[] args) { 
     Expect4j exp; 
     List<String> cmdsToRun = new ArrayList<String>(); 

     try { 
      ExpectTest1 test = new ExpectTest1(); 
      exp = test.SSH("jumpbox.xyz.com","user1","passwd", cmdsToRun); 
      exp.getLastState().toString(); 
     } catch (Exception e) { 
      e.printStackTrace(); 
    } 


} 

    public Expect4j SSH(String hostname, String username, String password, List<String> cmdsToRun) throws Exception { 
     return SSH(hostname, username, password, 22, cmdsToRun); 
    } 

    public Expect4j SSH(String hostname, String username, String password, int port, List<String> cmdsToRun) throws Exception { 

    JSch jsch=new JSch(); 
    Session session=jsch.getSession(username, hostname, port); 
    if(password != null) { 
     session.setPassword(password); 
    } 

    Hashtable config=new Hashtable(); 
    config.put("StrictHostKeyChecking", "no"); 
    session.setConfig(config); 
    session.setDaemonThread(true); 
    session.connect(3 * 1000); // making a connection with timeout. 

    ChannelShell channel = (ChannelShell) session.openChannel("shell"); 

    channel.setInputStream(System.in); 
    channel.setOutputStream(System.out); 

    channel.setPtyType("vt102"); 

    Expect4j expect = new Expect4j(channel.getInputStream(), channel.getOutputStream()); 

    channel.connect(5*1000); 

    Server hostServer = new Server(); 
    hostServer.setHostName("box1.xyz.com"); 
    hostServer.setUsername("user2"); 

    Server destServer = new Server(); 
    destServer.setHostName("box2.xyz.com"); 
    destServer.setUsername("user3"); 

    boolean isLogged = doSSH(hostServer, expect); 
    if(isLogged) { 
     doSSH(destServer, expect); 
    } 

    return expect; 
} 

    private boolean doSSH (Server server, Expect4j expect) throws IOException, MalformedPatternException, Exception { 
     String command = "ssh " + server.getUsername() + "@" + server.getHostName() + RETURN_CHAR; 
     System.out.println("Logging in to: " + command); 
     boolean logged; 
     expect.send(command); 
     Thread.sleep(4000); 
     command = "uname -a" + RETURN_CHAR; 
     System.out.println(command); 
     expect.send(command); 
     Thread.sleep(10000); 

      if(isMatch(expect,server.getHostName().substring(0,server.getHostName().indexOf(".")))) { 
      System.out.println("Logged in to:" + server.getHostName() + "....."); 
      return true; 
     } 

     if(isMatch(expect, "Last login")) { 
      System.out.println("Logged in to:" + server.getHostName() + "....."); 
      return true; 
     } 

     if(isMatch(expect, "not known")) { 
      System.out.println("Node or Service not known..."); 
      return false; 
     } 

     System.out.println("Node or Service not known..."); 
     return false; 

     /*expect.expect(new Match[] { 
      new RegExpMatch("Name or service not known", new Closure() { 
       public void run(ExpectState state) throws Exception { 
        System.out.println("Name or service not known..."); 
        expectOut = state.getBuffer(); 
      } 
     }) 
     }); 

     expect.expect(new Match[] { 
       new RegExpMatch("Last login: \\w{3} (.*) from", new Closure() { 
        public void run(ExpectState state) throws Exception { 
         System.out.println("Logged In...."); 
         expectOut = state.getBuffer(); 
        } 
       }) 
      }); 

     if(expectOut != null && expectOut.length()>0 && !expectOut.matches("Name or service not known")) 
      return true; 

     return false;*/ 

    } 

    private boolean isMatch(Expect4j expect, String regEx) throws MalformedPatternException, Exception { 
     /*expect.expect(new Match[] { 
       new RegExpMatch(regEx, new Closure() { 
        public void run(ExpectState state) throws Exception { 
         System.out.println(state.getBuffer()); 
         System.out.println(state.getMatch()); 
         expectOut = state.getMatch(); 
         //System.out.println(state.getMatch()); 
        } 
       }) 
      }); 

     if(expectOut != null 
       && expectOut.length()>0 
       && expectOut.matches(regEx)) { 
      //System.out.println(regEx); 
      return true; 
     }*/ 
     System.out.println("*************"); 
     System.out.println(expect.expect(regEx)); 
     System.out.println("*************"); 
     if(expect.expect(regEx) == 0) 
      return true; 

     return false; 
    } 

}

答えて

1

私があなたのsshコマンドは、パスワードを要求しようとしたり、 `known_hostsファイルにホスト鍵を追加するかどうかを尋ねてしようとしていると思われます。私はsshがttyに直接接続してこれらの質問をするので、Expect4jでそれらを実行できるかどうかはわかりません。私は私を自動化していた場合

How to make a ssh connection to a firewall(router) with java?

:しかし、この答えは、それを解決したようだ:

Using expect to pass a password to ssh

ここで役立つかもしれない同様の質問/回答はありますsshの接続では、パスワードの代わりに公開鍵/秘密鍵の暗号化を使用してサーバーに接続し、サーバーがクライアントからコマンドラインからパスワードなしで正常に接続されていることを確認してください。 フルホスト名が使用されていることを確認してください。これにより、 `known_hosts 'ファイルにホスト鍵が保存されるので、将来プロンプトが出されることはありません。

+0

お返事ありがとうございます。私はすでにjumphostからserver1まで、そしてserver1からserver2まで、パスワードの少ないエントリを設定しています。それは実際にサーバーにSSHすることができます、問題は私が存在しないサーバー名を渡すときです。コードはまだ私たちがサーバーにログオンしたことを認識します!! – Vivek

1

あなたの期待とキー管理を処理するJavaライブラリを使用することをお勧めします。ここに私が見つけたのは、そのトリックをするようだ。

http://www.jscape.com/products/components/java/ssh-factory/

詳細についてはSshScriptまたはSshSessionクラスやドキュメントを参照してください。

+0

はい、Jscapeは私が以前使用していたのでうまく動作します。マネジメントが本当に関心がない(少なくとも今のところは)有料の図書館しか問題ではありません。 – Vivek

関連する問題