使用JAVA代码通过SSH访问远程windows,获取磁盘信息

已知JAVA中的File类可以获取本机的计算机的磁盘存储信息,代码如:

package com.java.test;

import java.io.File;

public class FileListen {

	public static void main(String[] args) {
		
		File file = new File("e:");
		long totalSpace = file.getTotalSpace();
		long freeSpace = file.getFreeSpace();
		long usedSpace = totalSpace - freeSpace;
		System.out.println("总空间大小 : " + totalSpace / 1024 / 1024 / 1024 + "G");  
                System.out.println("剩余空间大小 : " + freeSpace / 1024 / 1024 / 1024 + "G");  
                System.out.println("已用空间大小 : " + usedSpace / 1024 / 1024 / 1024 + "G");  
	}
}

为了能够获取远程计算机的磁盘存储信息,可以使用SSH的方式,进行连接。
     什么是SSH协议?  详见 点击打开链接 
【1】首先第一步需要安装一个freeSSHd的软件。
  安装步骤传送门 : 点击打开链接  
  注意:1、使用freeSSHd软件时请务必右键“以管理员身份运行”
     2、创建USER时,请将 Authorization 选项 选择为 Password stored as SHA1 hash
     3、之后在设置Authentication时,将Password authentication 选为 Required,Public key authication 为     Disabled。
【2】下载 ganymed-ssh2-build210.jar 
  下载链接 : 点击下载 
【3】写测试代码
 
package ***;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

import org.springframework.stereotype.Service;

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


@Service("listenSystemServiceImpl")
public class ListenSystemServiceImpl{

	private String HOST_NAME = "192.168.12.11"; //IP地址
	private int PORT = 22; //端口号
	private String LOGIN_NAME = "Administrator"; //登录账号
	private String PASS_WORD = "admin"; //登录密码
	
	private String CMD_WINDOWS="E:"; 
		//windows命令

	private long totalSpace = 0;
	private	long freeSpace = 0;
	private	long usedSpace = 0;
	/**
	 * 获取磁盘信息
	 * 
	 * @return
	 */
	public Map getDiskInfo() {
		Map map = new HashMap();
		Connection conn = new Connection(HOST_NAME, PORT);
		Session ssh = null;

		try {
			conn.connect();
			boolean flag = conn.authenticateWithPassword(LOGIN_NAME, PASS_WORD);
			if (!flag) {
				System.out.println("用户名或密码错误");
			} else {
				System.out.println("连接成功");
				ssh = conn.openSession();
					//windows
				map = this.getDiskByWindows(ssh,map);				
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (ssh != null) {
					ssh.close();
				}
				if (conn != null) {
					conn.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		return map;
	}

	/**
	 * 用于windows
	 * @param map
	 * @return
	 * @throws IOException 
	 */
	public Map getDiskByWindows(Session ssh,Map map) throws IOException{
		ssh.execCommand("wmic LogicalDisk where \"Caption='"+
					CMD_WINDOWS+"'\" get FreeSpace,Size /value");
		InputStream stdout = new StreamGobbler(ssh.getStdout());
		BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
		String len = null;
		while((len = br.readLine()) != null){
			if(len.startsWith("FreeSpace")){
				String[] str = len.split("=");
				freeSpace = Long.parseLong(str[1])/ 1024 / 1024 / 1024;
			}
			if(len.startsWith("Size")){
				String[] str = len.split("=");
				totalSpace = Long.parseLong(str[1])/ 1024 / 1024 / 1024;
			}
		}
		usedSpace = totalSpace - freeSpace;
		System.out.println("总空间大小 : " + totalSpace + "G");
		System.out.println("剩余空间大小 : " + freeSpace + "G");
		System.out.println("已用空间大小 : " + usedSpace + "G");
		map.put("total", totalSpace);
		map.put("free", freeSpace);
		map.put("used", usedSpace);
		
		return map;
	}
}

使用File类的方法来获取,虽然连接成功了,但是获取的是本机的信息。所以采用了执行命令行的方式来获取信息,之后再拆分字符串。

补上访问Linux的方法:
/**
	 * 用于linux
	 * @param ssh
	 * @param map
	 * @return
	 */
	public Map getDiskByLinux(Session ssh,Map map){
		BufferedReader in = null;
		try {
			ssh.execCommand("df -hl");
			InputStream stdout = new StreamGobbler(ssh.getStdout());
			in = new BufferedReader(new InputStreamReader(stdout));
			String str = null;
			String[] strArray = null;
			while ((str = in.readLine()) != null) {
				int m = 0;
				strArray = str.split(" ");
				for (String tmp : strArray) {
					if (tmp.trim().length() == 0)
						continue;
					++m;
					if (tmp.indexOf("G") != -1) {
						if (m == 3) {
							if (!tmp.equals("") && !tmp.equals("0"))
								usedSpace += Double.parseDouble(tmp.substring(0,
										tmp.length() - 1)) * 1024;
						}
						if (m == 4) {
							if (!tmp.equals("none") && !tmp.equals("0"))
								freeSpace += Double.parseDouble(tmp.substring(0,
										tmp.length() - 1)) * 1024;

						}
					}
					if (tmp.indexOf("M") != -1) {
						if (m == 3) {
							if (!tmp.equals("") && !tmp.equals("0"))
								usedSpace += Double.parseDouble(tmp.substring(0,
										tmp.length() - 1));
						}
						if (m == 4) {
							if (!tmp.equals("none") && !tmp.equals("0"))
								freeSpace += Double.parseDouble(tmp.substring(0,
										tmp.length() - 1));
						}
					}

				}

			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if(in != null){					
					in.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		System.out.println("已用空间:" + usedSpace/1024 +"G");
		System.out.println("可用空间:" + freeSpace/1024 +"G");
	//	map.put("total", totalSpace);
		map.put("free", freeSpace);
		map.put("used", usedSpace);
		return map;
	}



总结:由于条件不够,没能测试是否能在Linux中获取信息,但基本流程相似。Linux可以直接安装SSH服务,具体可见一下链接。

   
  
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值