java利用 ganymed-ssh2-build.jar来上传文件到linux以及下载linux文件以及执行linux shell命令

 相关ssh2 jar包地址:http://www.ganymed.ethz.ch/ssh2/ganymed-ssh2-build210.zip

logger相关slf4j jar包地址:https://www.slf4j.org/dist/slf4j-1.8.0-beta4.zip

log4j1.2.17 jar地址:http://www.apache.org/dyn/closer.cgi/logging/log4j/1.2.17/log4j-1.2.17.zip

logger日志配置参考:https://www.cnblogs.com/zml-java/p/6148849.html

package api;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.InputStream;

import org.eclipse.jetty.util.statistic.SampleStatistic;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.SCPClient;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;

public class SshTest {
	public static void main(String[] args) {
		SshTest.exeCmd("df -m","root","123456","192.168.229.128", 22);
	}
	
	private static Logger logger = LoggerFactory.getLogger(SshTest.class);
	
	public static Connection getConnect(String user,String password ,String ip,int port ) {
		Connection conn=new Connection(ip, port);
		try {
			
			conn.connect();
			conn.authenticateWithPassword(user, password);
			System.out.println("ssh连接ok");
		}catch(Exception e) {
			e.printStackTrace();
		}
		return conn;
	}
	
	public static String exeCmd(String cmd,String user,String password ,String ip,int port){
		String line=null;
		Connection connection=null;
		Session session=null;
		try {
			connection=getConnect(user, password, ip, port);
			session=connection.openSession();
			session.execCommand(cmd);
			InputStream in = new StreamGobbler(session.getStdout());
	        BufferedReader brs = new BufferedReader(new InputStreamReader(in));
	        line = brs.readLine();
//	        logger.info(line);
		}catch(Exception e) {
			e.printStackTrace();
		}finally {
			session.close();
			connection.close();
		}
		return line;
	}	
	// downLoadFile from Linux
	public static boolean sftpDownload(String remoteFilePath,String localFilePath,String user,String password ,String ip,int port) {
		boolean bool=false;
		Connection connection=null;
		try {
			connection=getConnect(user, password, ip, port);
			SCPClient scpClient = connection.createSCPClient();
			scpClient.put(localFilePath, remoteFilePath);
			bool=true;
		}catch(IOException ioe) {
			ioe.printStackTrace();
			bool =false;
		}finally {
			connection.close();
		}
		return bool;
	}
	
	// uploadFile to Linux
	public static boolean uoloadFile(String remoteFilePath,String localFilePath,String user,String password ,String ip,int port) {
		boolean bool=false;
		Connection connection=null;
		try {
			connection=getConnect(user, password, ip, port);
			SCPClient scpClient = connection.createSCPClient();
            scpClient.get(remoteFilePath, localFilePath);
            bool=true;
		}catch(IOException ioe) {
			ioe.printStackTrace();
			bool =false;
		}finally {
			connection.close();
		}
		return bool;
	}
		
}


 

你可能感兴趣的:(Linux运维之道,java基础,自动化测试)