linux客户端连接工具

java连接linux客户端工具

package com.xxx.linux;

import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
import java.util.concurrent.TimeUnit;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;

/**
 * linux客户端
 * @author ChenWei
 * @email 582900710@qq.com
 * @date 2021年6月22日下午4:42:42
 *
 */
public class LinuxClient {
	/*
	 *  需要依赖的jar包
	 * <dependency>
	 *  <groupId>com.jcraft</groupId>
	 * 	<artifactId>jsch</artifactId>
	 * 	<version>0.1.55</version>
	 * </dependency>
	 */
	private String host;
	private int port = 22;
	private String username;
	private String password;
	private String prvkey;
	private Session session = null;
	private Channel channel = null;
	private InputStream in;
	private OutputStream out;
	public static LinuxClient build() {
		return new LinuxClient();
	}
	/**
	 * 请求地址
	 * @author ChenWei
	 * @email 582900710@qq.com
	 * @date 2021年6月23日下午6:45:22
	 * @param host
	 */
	public LinuxClient host(String host) {
		this.host = host;
		return this;
	}
	/**
	 * 端口号 默认22
	 * @author ChenWei
	 * @email 582900710@qq.com
	 * @date 2021年6月23日下午6:45:51
	 * @param port
	 */
	public LinuxClient port(int port) {
		this.port = port;
		return this;
	}
	/**
	 * 账号
	 * @author ChenWei
	 * @email 582900710@qq.com
	 * @date 2021年6月23日下午6:48:03
	 * @param username
	 */
	public LinuxClient username(String username) {
		this.username = username;
		return this;
	}
	/**
	 * 密码
	 * @author ChenWei
	 * @email 582900710@qq.com
	 * @date 2021年6月23日下午6:48:12
	 * @param password 如果设置了prvkey则可以不需要填
	 */
	public LinuxClient password(String password) {
		this.password = password;
		return this;
	}
	/**
	 * 私匙
	 * @author ChenWei
	 * @email 582900710@qq.com
	 * @date 2021年6月23日下午6:48:54
	 * @param prvkey 文件绝对路径
	 */
	public LinuxClient prvkey(String prvkey) {
		this.prvkey = prvkey;
		return this;
	}
	/**
	 * 连接服务器获得session对象
	 * @author ChenWei
	 * @email 582900710@qq.com
	 * @date 2021年6月23日下午7:00:00
	 * @return
	 * @throws JSchException
	 */
	public LinuxClient session() throws JSchException {
		this.session = this.getSession();
		return this;
	}
	public Channel getChannel() {
		return channel;
	}
	private LinuxClient() {}
	private LinuxClient(
			String username,
			String password,
			String prvkey) throws JSchException {
		this.username = username;
		this.password = password;
		this.prvkey = prvkey;
		this.session = this.getSession();
	}
	/**
	 * 初始化shell连接
	 * @author ChenWei
	 * @email 582900710@qq.com
	 * @date 2021年6月23日下午6:42:25
	 */
	public void initShell() {
		try {
			this.channel = this.session.openChannel("shell");
			this.channel.connect(3000);
		} catch (Exception e) {
			e.printStackTrace();
			closeIo(this.out,this.in);
			closeRunnable(this.session,this.channel);
		}
	}
	/**
	 * 发送shell命令
	 * @author ChenWei
	 * @email 582900710@qq.com
	 * @date 2021年6月23日下午6:42:39
	 * @param command
	 * @return
	 */
	public String sendShell(String command) {
		try {
			if(this.out == null)
				this.out = this.channel.getOutputStream();
			if(this.in == null)
				this.in = this.channel.getInputStream();
			this.out.write(command.getBytes());
			this.out.flush();
			TimeUnit.SECONDS.sleep(1);
			if (this.in.available() > 0) {
			     byte[] data = new byte[this.in.available()];
			     int len = this.in.read(data);
			     if (len > 0) 
			    	 return new String(data, 0, len, "UTF-8");
			 }
		} catch (Exception e) {
			e.printStackTrace();
		} 
        return null;
	}
	/**
	 * 关闭shell连接
	 * @author ChenWei
	 * @email 582900710@qq.com
	 * @date 2021年6月23日下午6:42:54
	 */
	public void closeShell() {
		closeIo(this.out,this.in);
		closeRunnable(this.session,this.channel);
	}
	public static void main(String[] args) throws JSchException, IOException {
		LinuxClient linuxClient = null;
		try {
			//
			linuxClient = LinuxClient.build()
					.host("42.xxx.xxx.56")
					.username("root")
					.prvkey("D:/files/ssh_key/chenwei.pem")
					.session();
//			linuxClient = new LinuxClient("root", null, "D:/files/ssh_key/chenwei.pem");
			linuxClient.initShell();
//			String commad = "ps -ef | grep tomcat | egrep -v grep | awk '{print $2}'\n";
			String sendShell = linuxClient.sendShell("free -m \n");
			System.out.println(sendShell);
		} finally {
			if(linuxClient != null)
				linuxClient.closeShell();
		}
	}
	
	/**
	 * 文件下载 
	 * @author ChenWei
	 * @email 582900710@qq.com
	 * @date 2021年6月22日下午4:14:54
	 * @param in
	 * @param targetPath
	 * @return
	 */
	public boolean fileUpload(
			InputStream in,
			String targetPath) {
		ChannelSftp sftp = null;
		Channel channel = null;
		Session sshSession = null;
		try {
			sshSession = this.getSession();
			channel = sshSession.openChannel("sftp");
			channel.connect();
			sftp = this.convertChannel(channel, ChannelSftp.class);
			// 文件上传 下面这种方式也可以
			sftp.put(in, targetPath);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}finally {
			closeRunnable(sftp,channel,sshSession);
		}
	}
	/**
	 * 获取会话
	 * @author ChenWei
	 * @email 582900710@qq.com
	 * @date 2021年6月22日下午4:17:22
	 * @return
	 * @throws JSchException
	 */
	private Session getSession() throws JSchException {
		JSch jsch = new JSch();
		if(this.prvkey != null)
			jsch.addIdentity(this.prvkey);
		jsch.getSession(username, host, port);
		Session sshSession = jsch.getSession(username, host, port);
		sshSession.setPassword(password);
		Properties sshConfig = new Properties();
		sshConfig.put("StrictHostKeyChecking", "no");
		sshSession.setConfig(sshConfig);
		sshSession.connect();
		return sshSession;
	}
	/**
	 * 文件下载
	 * @author ChenWei
	 * @email 582900710@qq.com
	 * @date 2021年6月22日下午4:39:46
	 * @param sourceFile 下载的源文件绝对路径
	 * @return 
	 */
	public InputStream fileDownload(String sourceFile) {
		ChannelSftp sftp = null;
		Channel channel = null;
		Session sshSession = null;
		try {
			sshSession = this.getSession();
			channel = sshSession.openChannel("sftp");
			channel.connect();
			sftp = this.convertChannel(channel, ChannelSftp.class);
			return sftp.get(sourceFile);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			closeRunnable(sftp,channel,sshSession);
		}
		return null;
	}
	/**
	 * 转换
	 * @author ChenWei
	 * @email 582900710@qq.com
	 * @date 2021年6月22日下午4:47:31
	 * @param channel 管道对象
	 * @param clazz 转换的类型
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public <T>T convertChannel(
			Channel channel,
			Class<T> clazz) {
		return (T)channel;
	}
	/**
	 * 关闭连接
	 * @author ChenWei
	 * @email 582900710@qq.com
	 * @date 2021年6月23日下午4:15:47
	 * @since <输入你的版本号>
	 * @param runnables
	 */
	public void closeRunnable(Runnable ...runnables) {
		for (Runnable runnable : runnables) {
			if(runnable instanceof Session) {
				Session session = (Session)runnable;
				if(session.isConnected())
					session.disconnect();
			}else
			if(runnable instanceof Channel) {
				Channel channel = (Channel)runnable;
				if(channel.isConnected())
					channel.disconnect();
			}
		}
	}
	/**
	 * 关闭io流
	 * @author ChenWei
	 * @email 582900710@qq.com
	 * @date 2021年6月23日下午4:15:57
	 * @param closeables
	 */
	public void closeIo(Closeable ...closeables) {
		for (Closeable closeable : closeables) {
			if(closeable != null)
				try {
					closeable.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
		}
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

我是一条酸菜鱼

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值