編寫java 程序與Linux進行遠程連接並運行linux下的腳本


我這里是通過連接到centos6.5的大數據集群的主節點,並通過運行hadoop的啟動腳本來啟動hadoop

本人采用的是SSH的方式連接

通過創建maven項目來編寫代碼,在編寫代碼之前需要先導入架包

在pom.xml文件里添加以下語句

 <dependency>
            <groupId>ch.ethz.ganymed</groupId>
            <artifactId>ganymed-ssh2</artifactId>
            <version>262</version>
        </dependency>

 

 

 

 編寫連接代碼:

package Studytest.com.jsion; import java.io.IOException; import ch.ethz.ssh2.Connection; import ch.ethz.ssh2.Session; import ch.ethz.ssh2.StreamGobbler; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; /* @author: Liu Yuanyuan purpose: test connecting remote computer and execute linux command */

public class TestRemoteConnect { public static void main(String[] args) { String hostname = "192.168.114.11"; String username = "hadoop"; String password = "666666"; //指明連接主機的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("sh /opt/modules/hadoop-2.6.0/sbin/start-all.sh"); //ssh.execCommand("perl /root/hello.pl"); //只允許使用一行命令,即ssh對象只能使用一次execCommand這個方法, //多次使用則會出現異常 //使用多個命令用分號隔開 //ssh.execCommand("cd /root; sh hello.sh"); //將Terminal屏幕上的文字全部打印出來
                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); } } } catch (IOException e) { e.printStackTrace(); } finally { //連接的Session和Connection對象都需要關閉
 ssh.close(); conn.close(); } } }

 

 

運行一下代碼

 

檢測集群的啟動進程:

 

 

 可以看到運行成功!!!

 


免責聲明!

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



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