java中使用ssh方式获取服务器的文件到本地

package com.chinacahe.LogContrast.ssh;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;


import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.SCPClient;

import com.chinacahe.LogContrast.base.LognameIntoDB;
import com.chinacahe.LogContrast.base.RemoteFileGetter;
import com.chinacahe.LogContrast.Constants;

public class SPZRemoteFileGetter implements RemoteFileGetter{

	Logger logger = Logger.getLogger(getClass());
	private String ip;
	private int port;
	private String path;
	private String dev_id;
	private String dev_name;
	private String date;


	ApplicationContext context = new ClassPathXmlApplicationContext(
			new String[] { "classpath*:applicationContext*.xml" });


	public void getRemoteFile() {
		
		
		LognameIntoDB lognameIntoDB=(LognameIntoDB)context.getBean("lognameIntoDB");
		
		
		Connection connection = null;
		List<String> lognames=new ArrayList<String>();
		try {
			connection = new Connection(ip, port);//远程服务器IP,端口
			connection.connect();//建立连接
			boolean isAuthenticated = connection.authenticateWithPassword(
					Constants.LOGIN_USER, Constants.LOGIN_PASSWORD);//服务器用户名,密码
			if (!isAuthenticated) {
				throw new IOException("Authentication Failed.");
			}
			
			logger.info("Connecting to "+ ip + ":" + port + "successful");
			SCPClient client = new SCPClient(connection);
		
				try{
					String servlogname=new File(path).getName();//path是服务器的文件名路径
					client.get(path, Constants.TEMP_DIR+ File.separator);//Constants.TEMP_DIR+ File.separator:要存入的本地目录
					
					if(new File(Constants.TARGET_DIR+File.separator + servlogname).exists()){

						new File(Constants.TARGET_DIR+File.separator + servlogname).delete();
						
					}
					FileUtils.moveFileToDirectory(
							new File(Constants.TEMP_DIR+ File.separator + servlogname),
							new File(Constants.TARGET_DIR),
							false);
					
									}
				catch(Exception e){
					logger.info("catching file "+ ip + ":" + port + ":" + path + " failed " + e.getMessage());
				}
			
			
			logger.info("Finished "+ ip + ":" + port);
			
		}
		catch(Exception e){
			logger.info("Failed connecting to "+ ip + ":" + port);
			
		}
		finally{
			if(connection != null){
				connection.close();
			}
		}
		
		
	}

	public void run() {
		getRemoteFile();
	}
	
	
	public  List<String> parseFiletoList(String filename){
		
		File file = new File(Constants.TARGET_DIR+ File.separator + filename);
		List<String> lognames=new ArrayList<String>();
		
		
			try {
			
				
				InputStream is = new FileInputStream(file);
				
				BufferedReader reader = new BufferedReader(new InputStreamReader(is));
				
				String line;
				int index = 0;
				while ((line = reader.readLine()) != null) {
					index++;
					lognames.add(line);
					
				}
				
				
			} catch (Exception e) {
				e.printStackTrace();
			}
		
		return lognames;
		
	}
	
	public String getIp() {
		return ip;
	}

	public void setIp(String ip) {
		this.ip = ip;
	}

	public int getPort() {
		return port;
	}

	public void setPort(int port) {
		this.port = port;
	}
	public String getPath() {
		return path;
	}

	public void setPath(String path) {
		this.path = path;
	}
	public String getDev_id() {
		return dev_id;
	}

	public void setDev_id(String devId) {
		dev_id = devId;
	}

	public String getDev_name() {
		return dev_name;
	}

	public void setDev_name(String devName) {
		dev_name = devName;
	}
	public String getDate() {
		return date;
	}

	public void setDate(String date) {
		this.date = date;
	}




}

 

 

 

执行远程服务器的系统命令并获取内容:

boolean isAuthenticated = connection.authenticateWithPassword(user, password);

	
			logger.info("Connecting to " + ip + ":" + port + "successful");

			Session sess = connection.openSession();

			sess.execCommand("/usr/local/squid/bin/rotateBilling.sh -v");

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

			BufferedReader br = new BufferedReader(new InputStreamReader(stdout));

			StringBuffer sb = new StringBuffer();
			while (true) {

				String line = br.readLine();
				if (line == null)
					break;
				sb.append(line);

			}
			if (sb.toString().indexOf("0.0.4") < 0) {
				sess.close();
				connection.close();
				logger.error(selectdev + ":" + dev_name + ":" + ip + ":" + errortime
						+ ": shell file version isn't 0.0.4");
				return;
			}
			sess.close();

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值