2015年4月6日 星期一

[ Java 常見問題 ] JSch - Sending commands to server via JSch shell channel

Source From Here 
Question 
I can't figure it out how I can send commands via JSch shell channel. 

How-To 
From the downloaded package from JSch, it provides example for shell channel: 
- Shell.java 
  1. package examples;  
  2.   
  3. /* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */  
  4. /** 
  5. * This program enables you to connect to sshd server and get the shell prompt. 
  6. *   $ CLASSPATH=.:../build javac Shell.java  
  7. *   $ CLASSPATH=.:../build java Shell 
  8. * You will be asked username, hostname and passwd.  
  9. * If everything works fine, you will get the shell prompt. Output may 
  10. * be ugly because of lacks of terminal-emulation, but you can issue commands. 
  11. * 
  12. */  
  13. import com.jcraft.jsch.*;  
  14. import java.awt.*;  
  15. import javax.swing.*;  
  16.   
  17. public class Shell{  
  18.   public static void main(String[] arg){  
  19.       
  20.     try{  
  21.       JSch jsch=new JSch();  
  22.   
  23.       //jsch.setKnownHosts("/home/foo/.ssh/known_hosts");  
  24.   
  25.       String host=null;  
  26.       if(arg.length>0){  
  27.         host=arg[0];  
  28.       }  
  29.       else{  
  30.         host=JOptionPane.showInputDialog("Enter username@hostname",  
  31.                                          System.getProperty("user.name")+  
  32.                                          "@localhost");   
  33.       }  
  34.       String user=host.substring(0, host.indexOf('@'));  
  35.       host=host.substring(host.indexOf('@')+1);  
  36.   
  37.       Session session=jsch.getSession(user, host, 22);  
  38.   
  39.       String passwd = JOptionPane.showInputDialog("Enter password");  
  40.       session.setPassword(passwd);  
  41.   
  42.       UserInfo ui = new MyUserInfo(){  
  43.         public void showMessage(String message){  
  44.           JOptionPane.showMessageDialog(null, message);  
  45.         }  
  46.         public boolean promptYesNo(String message){  
  47.           Object[] options={ "yes""no" };  
  48.           int foo=JOptionPane.showOptionDialog(null,   
  49.                                                message,  
  50.                                                "Warning",   
  51.                                                JOptionPane.DEFAULT_OPTION,   
  52.                                                JOptionPane.WARNING_MESSAGE,  
  53.                                                null, options, options[0]);  
  54.           return foo==0;  
  55.         }  
  56.   
  57.         // If password is not given before the invocation of Session#connect(),  
  58.         // implement also following methods,  
  59.         //   * UserInfo#getPassword(),  
  60.         //   * UserInfo#promptPassword(String message) and  
  61.         //   * UIKeyboardInteractive#promptKeyboardInteractive()  
  62.   
  63.       };  
  64.   
  65.       session.setUserInfo(ui);  
  66.   
  67.       // It must not be recommended, but if you want to skip host-key check,  
  68.       // invoke following,  
  69.       // session.setConfig("StrictHostKeyChecking", "no");  
  70.   
  71.       //session.connect();  
  72.       session.connect(30000);   // making a connection with timeout.  
  73.   
  74.       Channel channel=session.openChannel("shell");  
  75.   
  76.       // Enable agent-forwarding.  
  77.       //((ChannelShell)channel).setAgentForwarding(true);  
  78.   
  79.       channel.setInputStream(System.in);  
  80.       /* 
  81.       // a hack for MS-DOS prompt on Windows. 
  82.       channel.setInputStream(new FilterInputStream(System.in){ 
  83.           public int read(byte[] b, int off, int len)throws IOException{ 
  84.             return in.read(b, off, (len>1024?1024:len)); 
  85.           } 
  86.         }); 
  87.        */  
  88.   
  89.       channel.setOutputStream(System.out);  
  90.   
  91.       /* 
  92.       // Choose the pty-type "vt102". 
  93.       ((ChannelShell)channel).setPtyType("vt102"); 
  94.       */  
  95.   
  96.       /* 
  97.       // Set environment variable "LANG" as "ja_JP.eucJP". 
  98.       ((ChannelShell)channel).setEnv("LANG", "ja_JP.eucJP"); 
  99.       */  
  100.   
  101.       //channel.connect();  
  102.       channel.connect(3*1000);  
  103.     }  
  104.     catch(Exception e){  
  105.       System.out.println(e);  
  106.     }  
  107.   }  
  108.   
  109.   public static abstract class MyUserInfo  
  110.                           implements UserInfo, UIKeyboardInteractive{  
  111.     public String getPassword(){ return null; }  
  112.     public boolean promptYesNo(String str){ return false; }  
  113.     public String getPassphrase(){ return null; }  
  114.     public boolean promptPassphrase(String message){ return false; }  
  115.     public boolean promptPassword(String message){ return false; }  
  116.     public void showMessage(String message){ }  
  117.     public String[] promptKeyboardInteractive(String destination,  
  118.                                               String name,  
  119.                                               String instruction,  
  120.                                               String[] prompt,  
  121.                                               boolean[] echo){  
  122.       return null;  
  123.     }  
  124.   }  
  125. }  
Below is a concise version sample code written in groovy: 
- ShellDemo.groovy 
  1. package examples  
  2.   
  3. /* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */  
  4. /** 
  5. * This program enables you to connect to sshd server and get the shell prompt. 
  6. *   $ CLASSPATH=.:../build javac Shell.java 
  7. *   $ CLASSPATH=.:../build java Shell 
  8. * You will be asked username, hostname and passwd. 
  9. * If everything works fine, you will get the shell prompt. Output may 
  10. * be ugly because of lacks of terminal-emulation, but you can issue commands. 
  11. * 
  12. */  
  13. import com.jcraft.jsch.*;  
  14.   
  15. import java.awt.*;  
  16.   
  17. import javax.swing.*;  
  18.   
  19. String user = "root"  
  20. String host = "xxx"  
  21. String passwd = "xxx"  
  22.   
  23. abstract class MyUserInfo2 implements UserInfo, UIKeyboardInteractive{  
  24.     public String getPassword(){  
  25.         return null;  
  26.     }  
  27.     public boolean promptYesNo(String str){  
  28.         return false;  
  29.     }  
  30.     public String getPassphrase(){  
  31.         return null;  
  32.     }  
  33.     public boolean promptPassphrase(String message){  
  34.         return false;  
  35.     }  
  36.     public boolean promptPassword(String message){  
  37.         return false;  
  38.     }  
  39.     public void showMessage(String message){  
  40.     }  
  41.     public String[] promptKeyboardInteractive(String destination,  
  42.             String name,  
  43.             String instruction,  
  44.             String[] prompt,  
  45.             boolean[] echo){  
  46.         return null;  
  47.     }  
  48. }  
  49.   
  50. JSch jsch=new JSch();  
  51.   
  52. Session session=jsch.getSession(user, host, 22);  
  53. session.setPassword(passwd)  
  54.   
  55. UserInfo ui = new MyUserInfo2(){  
  56.             public void showMessage(String message){  
  57.                 JOptionPane.showMessageDialog(null, message);  
  58.             }  
  59.             public boolean promptYesNo(String message){  
  60.                 return true  
  61.             }  
  62.   
  63.             // If password is not given before the invocation of Session#connect(),  
  64.             // implement also following methods,  
  65.             //   * UserInfo#getPassword(),  
  66.             //   * UserInfo#promptPassword(String message) and  
  67.             //   * UIKeyboardInteractive#promptKeyboardInteractive()  
  68.   
  69. };  
  70.   
  71. session.setUserInfo(ui);  
  72.   
  73. session.connect(100000);   // making a connection with timeout.  
  74.   
  75. Channel channel=session.openChannel("shell");  
  76.   
  77. channel.setInputStream(System.in);  
  78. channel.setOutputStream(System.out);  
  79.   
  80. /* 
  81. // Choose the pty-type "vt102". 
  82. ((ChannelShell)channel).setPtyType("vt102"); 
  83. */  
  84.   
  85. /* 
  86. // Set environment variable "LANG" as "ja_JP.eucJP". 
  87. ((ChannelShell)channel).setEnv("LANG", "ja_JP.eucJP"); 
  88. */  
  89.   
  90. //channel.connect();  
  91. channel.connect(3*1000);  
Another approach is to use class flib.util.jsch.ShellWrapper from flib library: 
  1. ...  
  2.     public static void main(String args[]) throws Exception  
  3.     {  
  4.         ShellWrapper sw = new ShellWrapper("192.168.140.129""john""john7810");  
  5.         System.out.printf("\t[Info] Login...%s\n", sw.connect());  
  6.           
  7.         // 1) Sending command 'dir' and wait 3 sec to collect output.  
  8.         System.out.printf("pwd:\n%s\n\n", sw.sendlineWithOut("dir"3000));  
  9.           
  10.         // 2) Sending command and collect output until pattern matching.  
  11.         // Tuple(Flag,Output)  
  12.         //   - Flag(Boolean):   True means pattern match; Otherwise False.  
  13.         //   - Output(String):  Console output  
  14.         Tuple rt = sw.sendlineWithOut("ps aux", Pattern.compile("john@route"), 1000);  
  15.         if(rt.getBoolean(0))  
  16.         {  
  17.             System.out.printf("\t[Info] Match pattern with output:\n%s\n", rt.getStr(1));             
  18.         }  
  19.         else  
  20.         {  
  21.             System.out.printf("\t[Info] Output:\n%s\n", rt.getStr(1));    
  22.         }  
  23.               
  24.         System.out.printf("\t[Info] Bye!\n");  
  25.         sw.close();  
  26.     }  
  27. ...  

沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...