您的位置:首页 > 运维架构 > Linux

Java远程执行Linux命令

2015-06-13 10:33 483 查看
  //指明连接主机的IP地址  
       Connection conn = new Connection(hostname);  
       Session ssh = null;  
       try {  
           //连接到主机  
           conn.connect();  
           //使用用户名和密码校验  
           boolean isconn = conn.authenticateWithPassword(username, password);  
           if(!isconn){  
               System.out.println("用户名称或者是密码不正确");  
           }else{  
               System.out.println("已经连接OK");  
               ssh = conn.openSession();  
               ssh.execCommand(command);  
               InputStream  is = new StreamGobbler(ssh.getStdout());  
               BufferedReader brs = new BufferedReader(new InputStreamReader(is));  
               while(true){  
                   String line = brs.readLine();  
                   if(line==null){  
                       break;  
                   }  
                   System.out.println(line);  
               }  
                 
           }  
           //连接的Session和Connection对象都需要关闭  
           ssh.close();  
           conn.close();  
             
       } catch (IOException e) {  
           // TODO Auto-generated catch block  
           e.printStackTrace();  
       }  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息