java 远程执行linux命令

来源:互联网 发布:想在淘宝卖面膜 编辑:程序博客网 时间:2024/05/18 12:32
  1. package hb.linux;  
  2.   
  3. import java.io.BufferedReader;  
  4. import java.io.IOException;  
  5. import java.io.InputStream;  
  6. import java.io.InputStreamReader;  
  7.   
  8. import ch.ethz.ssh2.Connection;  
  9. import ch.ethz.ssh2.Session;  
  10. import ch.ethz.ssh2.StreamGobbler;  
  11.   
  12. public class TestCtrCommond {  
  13.   
  14.     public static void main(String[] args) {  
  15.           
  16.         String hostname = "129.17.17.20";  
  17.         String username = "weblogic";  
  18.         String password = "weblogic";  
  19.         //指明连接主机的IP地址  
  20.         Connection conn = new Connection(hostname);  
  21.         Session ssh = null;  
  22.         try {  
  23.             //连接到主机  
  24.             conn.connect();  
  25.             //使用用户名和密码校验  
  26.             boolean isconn = conn.authenticateWithPassword(username, password);  
  27.             if(!isconn){  
  28.                 System.out.println("用户名称或者是密码不正确");  
  29.             }else{  
  30.                 System.out.println("已经连接OK");  
  31.                 ssh = conn.openSession();  
  32.                 //使用多个命令用分号隔开  
  33. //              ssh.execCommand("pwd;cd /tmp;mkdir hb;ls;ps -ef|grep weblogic");  
  34.                 ssh.execCommand("cd /app/weblogic/Oracle/Middleware/user_projects/domains/base_domain;./startWebLogic.sh &");  
  35.                 //只允许使用一行命令,即ssh对象只能使用一次execCommand这个方法,多次使用则会出现异常  
  36. //              ssh.execCommand("mkdir hb");  
  37.                 //将屏幕上的文字全部打印出来  
  38.                 InputStream  is = new StreamGobbler(ssh.getStdout());  
  39.                 BufferedReader brs = new BufferedReader(new InputStreamReader(is));  
  40.                 while(true){  
  41.                     String line = brs.readLine();  
  42.                     if(line==null){  
  43.                         break;  
  44.                     }  
  45.                     System.out.println(line);  
  46.                 }  
  47.                   
  48.             }  
  49.             //连接的Session和Connection对象都需要关闭  
  50.             ssh.close();  
  51.             conn.close();  
  52.               
  53.         } catch (IOException e) {  
  54.             // TODO Auto-generated catch block  
  55.             e.printStackTrace();  
  56.         }  
  57.           
  58.     }  
  59.   




附件中有远程连接的SSH使用的jar包(j2ssh-core-0.2.9.jar),还有相关的demo

0 0
原创粉丝点击