java 连接linux服务器执行命令,Java后台连接服务器执行Linux命令

首先要引入依赖的Jar:  jsch-0.1.55.jar

maven导入依赖的 jsch-0.1.55.jar包:

com.jcraft

jsch

0.1.55

非maven构建的项目也可以直接去下载 :jsch-0.1.55.jar 导入即可。

一、命令执行工具类

ShellUtil.java

package com.web.util;

import com.jcraft.jsch.*;

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.util.*;

import java.util.concurrent.ExecutorService;

import java.util.concurrent.Executors;

public class ShellUtil {

private static final MapSHELL_SESSION_MAP = new HashMap<>();//sessionMap

private static final JSch jsch = new JSch();//session构造器

private static final Integer TIME_OUT_HOUR = 1;//超时时间

private static final Integer DEFAULT_PORT = 22;//默认连接端口

private static final String DEFAULT_CHANNEL_TYPE = "exec"; //默认类别

private static ExecutorService executorQueue = Executors.newSingleThreadExecutor();

public static void runExecute(Runnable paramRunnable) {

executorQueue.submit(paramRunnable);

}

public static final String shellCommand(final String address, final String username, final String password, final String command) {

return ShellUtil.shellCommand(address, username, password, ShellUtil.DEFAULT_CHANNEL_TYPE, command);

}

public static final String shellCommand(final String address, final String username, final String password,

final String channelType, final String command) {

return ShellUtil.shellCommand(address, username, password, ShellUtil.DEFAULT_PORT, channelType, command);

}

public static final String shellCommand(final String address, final String username, final String password,

final Integer port, final String channelType, final String command) {

if (!ShellUtil.checkNotNull(address, username, password, port, channelType, command))

throw new NullPointerException("params cannot be null");

if (!ShellUtil.SHELL_SESSION_MAP.containsKey(address + ":" + username))

ShellUtil.SHELL_SESSION_MAP.put(address + ":" + username, new ShellUtil.ShellSession(address, username, password, port));

ShellSession shellSession = ShellUtil.SHELL_SESSION_MAP.get(address + ":" + username);

shellSession.updateLastExecTime();//更新操作时间

//清除超时session实例

ShellUtil.SHELL_SESSION_MAP.entrySet().removeIf(

entry -> entry.getValue().lastExecTime.getTime() + ShellUtil.TIME_OUT_HOUR * 60 * 60 * 1000 < System.currentTimeMillis() );

}

return shellSession == null ? null : shellSession.execute(channelType, command);

}

private static final Boolean checkNotNull(Object... objects) {

if (objects == null)

return false;

for (Object obj : objects) {

if (obj == null)

return false;

}

return true;

}

static class ShellSession {

Session session;

Date lastExecTime;

private ShellSession(String address, String username, String password, Integer port) {

try {

session = ShellUtil.jsch.getSession(username, address, port);

session.setPassword(password);

session.setConfig("StrictHostKeyChecking", "no");//去掉连接确认的

session.connect(30000);

} catch (JSchException e) {

e.printStackTrace();

}

}

private void updateLastExecTime() {

lastExecTime = Calendar.getInstance().getTime();

}

private String execute(String channelType, String command) {

if (this.session == null)

return null;

Channel channel = null;

//InputStream input = null;

BufferedReader bufferedReader = null;

String resp = "";

try {

channel = this.session.openChannel(channelType);

((ChannelExec) channel).setCommand(command);

channel.setInputStream(null);

((ChannelExec) channel).setErrStream(System.err);

channel.connect();

bufferedReader = new BufferedReader(new InputStreamReader(channel.getInputStream()));

String line = null;

while ((line = bufferedReader.readLine()) != null) {

resp += line + "\n";

}

if (resp != null && !resp.equals("")) {

resp = resp.substring(0, resp.length() - 1);

}

System.out.println(resp);

} catch (JSchException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

} finally {

if (bufferedReader != null) {

try {

bufferedReader.close();

} catch (IOException e) {

e.printStackTrace();

}

}

if (channel != null) {

channel.disconnect();

}

}

return resp;

}

}

}

二、连接服务器,进入目录/home/geiri/deploy/portal/ ,显示当前目录下所有文件 :

cacbf3231311f8dc26d2c5dff07413e5.png

三、测试ShellUtil.java类

d010fb8c591f59dd4b0ab7abee9da1b9.png

执行结果:

a0de2b9547abff233d0b048fbb0a0949.png

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值