---
title: "Java读取远程主机文件"
author: "listen-raining"
date: "2013-09-19T00:20:17Z"
tags: []
categories: ["编程语言"]
slug: "java"
draft: false
lastmod: "2013-09-19T00:20:17Z"
id: 1944136
url: "https://listen-raining.iteye.com/blog/1944136"
---

//Java利用第三方jar包（ganymed-ssh2-build210.jar）读取远程主机文件

package com.poson.cb.web.action.bill;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Properties;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.SFTPv3Client;
import ch.ethz.ssh2.SFTPv3FileAttributes;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;
import com.poson.cb.ext.domain.RealTimeBilling;
import com.poson.cb.lib.dr.DRApiHPImpl;
import com.poson.cb.service.AppException;
import com.poson.cb.web.action.BaseAction;

//实时清，账单文件查询
public class RealTimeBillingAction extends BaseAction{
	Runtime runtime=Runtime.getRuntime();
	String useHome=System.getProperty("user.home");
	String idxMasterPath = useHome+"ADR/cb/data/master/";   //主侧IDX文件路径
	String idxSlavePath = useHome+"ADR/cb/data/slave/";     //备侧文件路径
	String fileDirName={"bill","mobile","fixed","fileout"};
	short outTime=2;   //设置超时时间为2分钟
	String shIsMaster="Master";   //当前主侧默认是上海
	Connection con=null;
	
	public ActionForward realTimeActionForward(ActionMapping actionMapping,
			ActionForm actionForm, HttpServletRequest request,
			HttpServletResponse response) throws AppException, Exception {
		List bjList=new ArrayList();
		List shList=new ArrayList();
		InetAddress address=InetAddress.getLocalHost();
		
		// 1.0 获取主备角色
		short sysSate = new DRApiHPImpl().getSystemState();
		System.out.println("第三种方法获得主备角色：" + sysSate); // 0-主系统，1-备系统，2-非融灾系统
        
		//判断上海是否是主侧
		if(sysSate==1 && (getCurrentHostAddress().equals("132.32.24.105"))){
			shIsMaster="slave";
		}
		// 2.0 获取当前侧容灾平台正在处理的IDX(文件)名称
		Process p1 = runtime
				.exec(new String { "/bin/sh", "-c", "dr_stat -l" });
		BufferedReader bReader = new BufferedReader(new InputStreamReader(p1
				.getInputStream()));
		String firstLine = bReader.readLine();
		// 读取第二行的记录（第一行为unix返回的列）
		while ((firstLine = bReader.readLine()) != null) {
			String arrs = firstLine.split("\\s{1,}"); // 以空格为分隔符
			// 获取IDX文件名
			String idxName = arrs;
			if(idxName != null && !"".equals(idxName)){
				//得到当前侧的文件集合
			    RealTimeBilling  billing=getFileNameListByIdxOfCurr(idxName.trim(),sysSate);
				if(null !=billing){
					if(getCurrentHostAddress().equals("132.129.24.18") || getCurrentHostAddress().equals("132.129.24.5")){
						shList.add(billing);
					}else {
						bjList.add(billing);
					}
				}
			}
		}

		// 获得对端侧文件集合
		short endSysStat;
		if(sysSate==0){
			endSysStat=1;
		}else {
			endSysStat=0;
		}
		Session session=getEndtoSession();
		//获取对端idxName
		session.execCommand("dr_stat -l");
		BufferedReader bReader2=new BufferedReader(new InputStreamReader(session.getStdout()));
		String endFirstLine = bReader2.readLine();
		while((endFirstLine=bReader2.readLine())!=null){
			String endArrs = endFirstLine.split("\\s{1,}"); // 以空格为分隔符
			// 获取IDX文件名
			String endIdxName = endArrs.trim();
			RealTimeBilling  billing1 =getFileNameListByIdxOfEnd(session, endIdxName, endSysStat);
			if(null !=billing1){
				if(getCurrentHostAddress().equals("132.129.24.18") || getCurrentHostAddress().equals("132.129.24.5")){
					bjList.add(billing1);
				}else {
					shList.add(billing1);
				}
			}
		}
		session.close();
		p1.destroy();
		request.setAttribute("bjList", bjList);
		request.setAttribute("shList", shList);
		request.setAttribute("shIsMaster", shIsMaster);
		return actionMapping.findForward("realTimeBilling");
	}
	
	//设置跳转方法
	public ActionForward realTimeForward(ActionMapping actionMapping,
			ActionForm actionForm, HttpServletRequest request,
			HttpServletResponse response) throws AppException, Exception {
		request.setAttribute("bjList", "");
		request.setAttribute("shList", "");
		request.setAttribute("shIsMaster", "");
		return actionMapping.findForward("realTimeForward");
	}
	
	// 获得对端session
	public Session getEndtoSession(){
			String hAddress = "";
			String ip,user,pwd;
			Session session=null;
			
		try {
			//InetAddress iAddress = InetAddress.getLocalHost();
			hAddress =getCurrentHostAddress();
			System.out.println("本机的IP地址是：" + hAddress);
			String ipConfigFile = useHome + "web" + File.separator + "CB"
					+ File.separator + "WEB-INF" + File.separator
					+ "ipconfig.properties";
			Properties properties = new Properties();
			properties.load(new FileInputStream(ipConfigFile));
			if (hAddress.equals("132.129.24.18") || hAddress.equals(properties.get("sIp").toString().trim())) {
				ip=properties.get("bIp").toString().trim();
				user=properties.get("bUser").toString().trim();
				pwd=properties.get("bPwd").toString().trim();
			} else {
				ip=properties.get("sIp").toString().trim();
				user=properties.get("sUser").toString().trim();
				pwd=properties.get("sPwd").toString().trim();
			}
			System.out.println("对端服务器的IP="+ip+" 用户名："+user+" 密码："+pwd);
			con=new Connection(ip);
			con.connect();
			boolean isAuthenticate=con.authenticateWithPassword(user, pwd);
			if(isAuthenticate==false){
				System.out.println("连接对端服务器认证失败......");
				throw new IOException("Authentication failed....");
			}
			session=con.openSession();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return  session;
	}
	
	//获取对端文件集合
	public List getEndToFileNameList(){
		
		Session  session=getEndtoSession();
		//1.0 获得对端侧
		return null;
	}
	
	//这种方法可以获得主备系统
	public String getMachineRole(){
			String mRole="";
			try {
				String drStatStr="dr_stat -d|head -n1|sed 's/^.*=//'|tr  ";
				Process p2=Runtime.getRuntime().exec(new String{"/bin/sh","-c",drStatStr});
				InputStreamReader inReader=new InputStreamReader(p2.getInputStream());
				LineNumberReader lReader=new LineNumberReader(inReader);
				
				p2.waitFor();
				while((mRole=lReader.readLine()) !=null){
					System.out.println("用第二种方法获得主机角色："+mRole);
				}
			} catch (IOException e) {
				System.out.println("用第二种方法获得主机角色失败");
				e.printStackTrace();
			} catch (InterruptedException e) {
				System.out.println("用第二种方法获得主机角色失败");
				e.printStackTrace();
			}
			//output :master
			return mRole;
	}
	
	//通过文件idxName查找对应的文件名称
	
	public RealTimeBilling getFileNameListByIdxOfCurr(String idxName,int sysStat) throws Exception{
		RealTimeBilling rBilling=null;
		for (int i = 0; i < fileDirName.length; i++) {
			String filePath="";
			if(sysStat==0){
				//在主侧目录查找
				filePath=idxMasterPath+fileDirName*+File.separator+idxName;	
			}else if (sysStat==1) {
				//在备侧目录查找
				filePath=idxSlavePath+fileDirName*+File.separator+"processing"+File.separator+idxName;
			}
			File file=new File(filePath);
			if(file.exists()){
				rBilling=new RealTimeBilling();
				System.out.println("打印文件所在目录："+file.getPath());
				//读取idx文件并获取文件名称
				LineNumberReader lNumberReader=new LineNumberReader(new FileReader(file));
				String linInfo	="";
				while((linInfo=lNumberReader.readLine())!=null){
					if(linInfo.indexOf("FILE_NAME")>0){
						String fileName=lNumberReader.readLine().trim();
						rBilling.setFileName(fileName);
						if((Calendar.getInstance().getTimeInMillis()-file.lastModified())/1000/60 > outTime){
							rBilling.setOutTime(true);
						}else {
							rBilling.setOutTime(false);
						}
						System.out.println("打印当前侧文件名称："+fileName +"是否超过2分钟："+rBilling.isOutTime());
						break;
					}
				}
			}
			
		}
		return rBilling;
	}
	
	//在对端侧查找对应的文件
	public RealTimeBilling getFileNameListByIdxOfEnd(Session session ,String idxName,short sysStat) throws Exception{
		RealTimeBilling rBilling=null;
		for (int i = 0; i < fileDirName.length; i++) {
			String filePath="";
			if(sysStat==0){
				//在主侧目录查找
				filePath=idxMasterPath+fileDirName*;	
			}else if (sysStat==1) {
				//在备侧目录查找
				filePath=idxSlavePath+fileDirName*+File.separator+"processing";
			}
			session.execCommand("find "+filePath+" -name "+idxName);
			BufferedReader bReader1=new BufferedReader(new InputStreamReader(new StreamGobbler(session.getStdout()))) ;
			String pathStr;
			while((pathStr=bReader1.readLine())!=null){
				session.execCommand("cat "+pathStr);
				BufferedReader bReader2=new BufferedReader(new InputStreamReader(new StreamGobbler(session.getStdout()))) ;
				String endFileLine;
				while((endFileLine=bReader2.readLine())!=null){
					if(endFileLine.indexOf("FILE_NAME")>0){
						String fileName=bReader2.readLine().trim();
						System.out.println("对端提取的文件名称为："+fileName);
						rBilling=new RealTimeBilling();
						rBilling.setFileName(fileName);
					    SFTPv3FileAttributes sAttributes= new SFTPv3Client(con).lstat(filePath);
						Integer mtime= sAttributes.mtime;  //获得文件的修改时间  需要确认返回的值是否以毫秒为单位
					    if(((Calendar.getInstance().getTimeInMillis()-Long.parseLong(mtime.toString()))/1000/60) > outTime){
					    	rBilling.setOutTime(true);
					    }else {
							rBilling.setOutTime(false);
						}
					    System.out.println("对端提取的idxName文件所在路径为："+filePath +"  该文件的访问时间为："+mtime +"  是否超时："+rBilling.isOutTime());
						break;
					}
				}
			}
		}
		return rBilling;
	}
	
	
	public String getCurrentHostAddress(){
		String hoString="";
		try {
			InetAddress iAddress=InetAddress.getLocalHost();
			hoString= iAddress.getHostAddress();
		} catch (UnknownHostException e) {
			System.out.println("获取本机IP地址出错错误......");
			e.printStackTrace();
		}
		return hoString;
	}
	
	
	
	
	public static void main(String args) {
		new RealTimeBillingAction().getEndtoSession();
	}
}


利用第三方jar包（ganymed-ssh2-build210.jar）读取远程主机文件的主要步骤为：
1.0 获得session
    con=new ch.ethz.ssh2.Connection(ip);
    con.connect();
    boolean isAuthenticate=con.authenticateWithPassword(user, pwd);
    session=con.openSession(); 
2.0 通过session执行命令并读取返回结果
     session.execCommand("find "+filePath+" -name "+idxName);
    BufferedReader bReader1=new BufferedReader(new InputStreamReader(new StreamGobbler(session.getStdout()))) ;



                         2013-09-19 0:19 记 @sanliheludongkou.xichengqu.beijing