天天看點

通過java使用ssh通路遠端Linux

需要做一個監控遠端Linux磁盤空間的東西,絞盡腦汁終于發現一個東西。ch.ethz.ssh2。

它可以通過使用者名和密碼登入可以ssh登入的機器,并且可以執行指令,并将指令顯示的東西傳回來。

上代碼了:

Connection con = null;
			Session session = null;
			BufferedReader dr = null;
			try {
				String ipd = mc.getIpAddress();
				if(ipd.equals("127.0.0.1")){
					con = new Connection(mc.getIpAddress(),2222);
				}else{
					con = new Connection(mc.getIpAddress());
				}
				ConnectionInfo info = con.connect();
				boolean result = con.authenticateWithPassword(mc.getUserName(), mc.getPassword());
				session = con.openSession();
				session.execCommand("df -T");
				InputStream stdout = session.getStdout();
				stdout = new StreamGobbler(session.getStdout());
				dr = new BufferedReader(new InputStreamReader(stdout));
				String line;
				while ((line=dr.readLine()) != null) {
					System.out.println(line);
					if(line.startsWith("/dev/")){
						Pattern p = Pattern.compile("[\\s]+");
						String[] arrs = p.split(line);
						for (String s : arrs) {
							System.out.println(s);
						}
						if(!arrs[1].startsWith("iso")){
							if(Long.parseLong(arrs[4])<5L*1024*1024 || Double.parseDouble(arrs[5])>0.9d){
								doAfterThing(mc, arrs[0]);
							}
						}
					}
				}
			} catch (Exception e) {
				System.err.println(e.getMessage());
			} finally {
				try {
					dr.close();
					session.close();
					con.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}      

 要注意的地方有兩點:

1.

Connection con = new Connection(String ip);      

 接收一個遠端位址做參數,預設端口是22。如果不是這個端口,需要指定。比如我用的虛拟機,使用了端口轉發,是以寫成

Connection con = new Connection(mc.getIpAddress(),2222);      

 因為的端口是2222.

2.session.getStdout() 的傳回值是一個InputStream,但是需要包裝後才能用。

剛開始我寫成了

InputStream stdout = session.getStdout();
dr = new BufferedReader(new InputStreamReader(stdout));      

 怎麼也娶不到東西。

後來寫為

InputStream stdout  = new StreamGobbler(session.getStdout());      

 才好了。StreamGobbler是ch.ethz.ssh2自己的一個類,文檔如下:

/**
 * A <code>StreamGobbler</code> is an InputStream that uses an internal worker
 * thread to constantly consume input from another InputStream. It uses a buffer
 * to store the consumed data. The buffer size is automatically adjusted, if needed.
*/      

 =========================================另外補充一點Java檢視本地磁盤資訊的方法:

這也是在查找過程中找到的。

File[] roots = File.listRoots();
System.err.println("the count of roots is : "+roots.length);
double constm = 1024 * 1024 * 1024 ;
        double total = 0d;
        for (File _file : roots) {
            System.out.println(_file.getPath());
            double total0 = _file.getTotalSpace()/constm,free0=_file.getFreeSpace()/constm,used0=total0-free0;
            System.out.println("totol space = " + total0+" G");
            System.out.print("the free space = " + free0+" G");
            System.out.println("---------- "+free0*100/total0+"% ----------");
            System.out.print("the used space = " + used0+" G");
            System.out.println("---------- "+used0*100/total0+"% ----------");
            System.out.println();
            total+=_file.getTotalSpace();
        }
        System.out.println("the total space of the machine = "+doubleFormat(total/constm));      

 代碼很簡單,不過有一點要注意:getTotalSpace()獲得的是這個盤的總容量,getFreeSpace()獲得的是剩餘容量,還有個方法是getUsableSpace(),這個并不表示已經用了多少,而是磁盤可用空間。通常情況下,這個值和剩餘容量是相等的。