2011-04-14 3 views
0

java ssh 도구를 사용하여 학교 계정에 ssh 연결을하고 파일을 찾은 다음 삭제합니다. 그러나 나는 같은 일을하지만 세 가지 기능을 다른 파일과 함께 만들고 있는데, 나는 한 파일에서 다른 파일을 만드는 대신 동일한 일을하는 방법을 찾고있다. 여기에 몇 가지 코드가 있습니다. 기본적으로 나는 하나의 ssh 연결 또는 일종의 포크 또는 멀티 스레딩에서이 모든 작업을 수행 할 수있는 방법이 있는지 알고 싶습니다.ssh through java

public void updateinterval() { 
    try { 
     JSch jsch = new JSch(); 

     String user = "***********"; 
     String host = "********"; 
     Session session = jsch.getSession(user, host, 22); 

     session.setPassword("*********"); 

     // username and password will be given via UserInfo interface. 
     UserInfo userInfo = new SftpUserInfo(); 

     session.setUserInfo(userInfo); 

     session.connect(); 

     // look for a file named feedinterval 

     String checkfortimeupdate = 
       "cd public_html/final;grep '-send' feedinterval"; 

     Channel channel = session.openChannel("exec"); 
     ((ChannelExec) channel).setCommand(checkfortimeupdate); 

     // X Forwarding 
     // channel.setXForwarding(true); 

     // channel.setInputStream(System.in); 
     channel.setInputStream(null); 

     // channel.setOutputStream(System.out); 

     // FileOutputStream fos=new FileOutputStream("/tmp/stderr"); 
     // ((ChannelExec)channel).setErrStream(fos); 
     ((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; 
       String returned = new String(tmp, 0, i); 

       String argument = returned.substring(6); 

       if (returned.contains("-send")) { 

        // if its there its calls the removeinterval function 
        // which removes the file it found 
        // by doing the same thing this function does but with a 
        // different ssh command 

        arduinoupdate hey = new arduinoupdate(); 

        hey.removeinterval(); 

        try { 
         Runtime rt = Runtime.getRuntime(); 

         String[] commands = { 
           "system.exe", "-send", argument }; 

         Process proc = rt.exec(commands); 
        } 

        catch (IOException e) { 
        } 
       } 
      } 

      if (channel.isClosed()) { 
       System.out.println("UpdateInterval Closed exit-status: " 
         + channel.getExitStatus()); 
       break; 
      } 
      try { 
       /* Thread.sleep(1000); */ 
      } catch (Exception ee) { 
      } 
     } 
     channel.disconnect(); 
     session.disconnect(); 
    } catch (Exception e) { 
     System.out.println(e); 
    } 
} 
+1

올바르게 코드의 형식을 최소한 몇 분 정도를 확인하시기 바랍니다. 편집기에서'{} '버튼을 사용하여 미리보기에서 코드를 읽을 수 있는지 확인하십시오. – Mat

+1

코드를 포맷하거나 불필요한 조각을 제거 할 수 있습니까? – smas

+1

마찬가지로,이 기능을 가독성을 위해 작은 1-4 선 방법으로 분해하는 것이 좋습니다. – Mike

답변

1

아마도 여러 작업을 실행하려는 경우 ExpectJ이 더 잘 작동합니다. ExpectJ는 JSCH를 사용하므로 쉽게 작업 할 수 있습니다.

final ExpectJ expectJ = new ExpectJ(); 
final Spawn spawn = expectJ.spawn("host", 22, "user", "pass"); 
spawn.send("cd public_html/final\n"); 
spawn.expect("someReturn"); 
... 
spawn.send("exit\n"); 
spawn.expectClose(); 
0

의견 작성자가 말한 것처럼 별도의 기능을 더 잘 고려해야합니다. 그러면 여러 명령에 대해 동일한 연결 (예 : Session)을 재사용하는 방법이 명확 해집니다.

public void updateInterval(Session s, String filename) { 
    String checkfortimeupdate = "fgrep '-send' \"public_html/final/" + filename + "\""; 

    ChannelExec channel = (ChannelExec)session.openChannel("exec"); 
    channel.setCommand(checkfortimeupdate); 

    channel.setInputStream(null); 
    channel.setErrStream(System.err); 
    BufferedReader in = new BufferedReader(new InputStreamReader(channel.getInputStream(), encoding)); 

    channel.connect(); 

    eatOutput(in); 

    if (channel.isClosed()) { 
     System.out.println("UpdateInterval Closed exit-status: " 
          + channel.getExitStatus()); 
     break; 
    } 
    channel.disconnect(); 
} 

는 그런 방법 eatOutput에서 (그것이 readLine 방법이있다)을, BufferedReader에서 독서를 넣어 세션을 열고 (다른 파일 이름으로) 여기에 표시된 세 번 메서드를 호출하는 다른 방법을 가지고 있고, 세션을 다시 닫습니다.

0

ExpectJ의 사용과 관련하여 기대 기반 기능을위한 기계 중요 제작 응용 프로그램에 사용할 수있는 가장 좋은 라이브러리는 입니까?

ExpectJ 또는 Expect4J 라이브러리? 그래도 두 라이브러리 모두 JSch를 사용합니다! 또는 Apache SSHD은 - 클라이언트 :

SshClient client = SshClient.setUpDefaultClient(); PipedOutputStream PipedIn...?