ganymedssh2 java執行linux命令


 

 

需要下載ganymed-ssh2-262.jar

 

package ganymed;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;

public class SShUtil {
    public static String execShellScript(String host, String username,  
            String password,  
  
            String cmd, int port) throws IOException {  
  
        System.out.println(("running SSH cmd [" + cmd + "]"));
        Connection connection = null;  
  
        Session sess = null;  
  
        InputStream stdout = null;  
  
        BufferedReader br = null;  
  
        StringBuffer buffer = new StringBuffer("exec result:");  
        buffer.append(System.getProperty("line.separator"));// 換行  
        try {  
  
            
             connection = new Connection(host, port);
             connection.connect();
      
             if (!connection.authenticateWithPassword(username, password)) {
                 throw new RuntimeException("authenticateWithPassword failed");
             }
             
            sess = connection.openSession();  
  
            sess.execCommand(cmd);  
  
            stdout = new StreamGobbler(sess.getStdout());  
  
            br = new BufferedReader(new InputStreamReader(stdout));  
  
            while (true) {  
                String line = br.readLine();  
                if (line == null)  {
                    break;  
                }
                buffer.append(line);  
                buffer.append(System.getProperty("line.separator"));// 換行  
                System.out.println(line);
            }  
  
        } finally {
            if(br != null){
                br.close();
            }
            if(sess != null){
                sess.close();  
            }
            if(connection != null){
                connection.close();  
            }
        }  
  
        return buffer.toString();  
  
    }  
    
    public static void main(String[] args) {  
        String cmd = "cd /usr/local/mysql/bin&&./ndb_mgm -e show";  
        try {  
            String info = execShellScript("192.168.1.240", "root", "test",cmd,22);  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
  
    }  

}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM