jar包下载地址:

http://www.ganymed.ethz.ch/ssh2/

此源码的好处就是没有依赖很多其他的包,拷贝过来干干净净。具体代码实现可以看下文,或参考官方文档,在下载的压缩包里ganymed-ssh2-build210\examples目录下有示例。

package com.system.action;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import com.system.service.MonitorService;
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;
import util.dataSource.SwitchDataSourceUtil;
import util.page.BaseAction; /**
* 服务器监控
* @author wangxiangyu
*
*/
@Controller
@RequestMapping("/monitor")
@SuppressWarnings("all")
public class MonitorController extends BaseAction { private static List<String> commands = null;
private static final String JNDI = "pn";//爱运维管理员权限数据源 @Autowired
MonitorService monitorService;
/**
* 进入监控页面,获取服务器配置(ip,登录名,密码)
* @param request
* @param model
* @return
*/
@RequestMapping(value = "/index.do")
public String index(HttpServletRequest request, Model model){
String hostName = request.getParameter("hostName"); List<Map<String, String>> serverConfigList = monitorService.getServerConfig(hostName);
model.addAttribute("serverConfigList", serverConfigList);
return "system/monitor/monitor";
} /**
* 初始化命令集合
*/
private void initCommands() { commands = new ArrayList<String>();
commands.add("top");
commands.add("free");
commands.add("df -hl");
commands.add("ps -ef|grep tomcat");
commands.add("ps aux|head -1;ps aux|grep -v PID|sort -rn -k +4|head");
} /**
* 获取服务器运行状态
* @param request
* @param response
* @throws Exception
*/
@RequestMapping("/findStatus.do")
public void findStatus(HttpServletRequest request, HttpServletResponse response) throws Exception {
//获取服务器配置信息
String hostName = request.getParameter("hostName");
List<Map<String, String>> serverConfigList = monitorService.getServerConfig(hostName);
String userName = serverConfigList.get(0).get("USER_NAME").toString();
String password = serverConfigList.get(0).get("PASSWORD").toString();
//预定义结果集
Map<String, Object> result = new HashMap<String, Object>();
//预定义命令结果集
List<Map<String, String>> commandResults = new ArrayList<Map<String, String>>();
try {
//连接服务器
Connection conn = new Connection(hostName);
conn.connect();
boolean isAuthenticated = conn.authenticateWithPassword(userName, password);
if (isAuthenticated == false) {
throw new IOException("Authentication failed.");
}
//初始化命令参数
initCommands();
for(String command : commands) {
Session sess = conn.openSession();
sess.execCommand(command);
InputStream stdout = new StreamGobbler(sess.getStdout());
BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
StringBuffer details = new StringBuffer("");
while (true){
String line = br.readLine();
if (line == null) {
break;
}
details.append(line).append("<br/>");
System.out.println(details);
}
//封装结果
Map<String, String> commandResult = new HashMap<String, String>();
commandResult.put("hostName", hostName);
commandResult.put("command", command);
commandResult.put("exitCode", null==sess.getExitStatus()?"无":sess.getExitStatus().toString());
commandResult.put("details", (null==details)?"无返回结果":details.toString());
commandResults.add(commandResult);
//关闭流
br.close();
sess.close();
}
conn.close();
result.put("rows", commandResults);
}catch(IOException e) {
e.printStackTrace(System.err);
}
write(response, result);
} /**
* 查看数据库表空间状态
* @param request
* @param response
* @throws IOException
*/
@RequestMapping("/getDBStatus.do")
public void getDBStatus(HttpServletRequest request, HttpServletResponse response) throws IOException {
List<Map<String, String>> dbResult = new ArrayList<Map<String,String>>();
try {
//切换数据源
SwitchDataSourceUtil.setCurrentDataSource(JNDI);
dbResult = monitorService.getDBStatus();
SwitchDataSourceUtil.clearDataSource();
}catch(Exception e) {
e.printStackTrace();
}finally {
SwitchDataSourceUtil.clearDataSource();
}
Map<String, Object> result = new HashMap<String, Object>();
result.put("rows", dbResult);
write(response, result);
}
}

Java SSH远程执行Shell命令、shell脚本实现(Ganymed SSH)的更多相关文章

  1. ssh远程执行nohup命令不退出

    https://blog.csdn.net/oneinmore/article/details/50073443

  2. SSH远程执行命令环境变量问题

    SSH命令格式 usage: ssh [-1246AaCfgKkMNnqsTtVvXxYy] [-b bind_address] [-c cipher_spec] [-D [bind_address: ...

  3. Java SSH远程执行Shell脚本实现(转)

    前言 此程序需要ganymed-ssh2-build210.jar包(下载地址:http://www.ganymed.ethz.ch/ssh2/) 为了调试方便,可以将\ganymed-ssh2-bu ...

  4. Hadoop概念学习系列之Java调用Shell命令和脚本,致力于hadoop/spark集群(三十六)

    前言 说明的是,本博文,是在以下的博文基础上,立足于它们,致力于我的大数据领域! http://kongcodecenter.iteye.com/blog/1231177 http://blog.cs ...

  5. linux利用ssh远程执行多台机器执行同样的命令

    这篇文章主要介绍了ssh远程执行命令方法和Shell脚本实例,本文讲解了ssh执行远程操作方法和远程执行命令shell脚本示例,需要的朋友可以参考下 ssh执行远程操作命令格式代码如下: ssh -t ...

  6. 解决SSH远程执行命令找不到环境变量的问题

    通过SSH执行远程主机的命令或脚本时,经常会出现找不到自定义环境变量的问题.但是,如果通过SSH登录远程主机,然后再执行相同的命令或脚本,那么此时执行又是成功的.两种相似的方法,得到的结果却截然不同, ...

  7. [转帖]ssh 远程执行命令

    ssh 远程执行命令 https://www.cnblogs.com/youngerger/p/9104144.html SSH 是 Linux 下进行远程连接的基本工具,但是如果仅仅用它来登录那可是 ...

  8. 利用java实现可远程执行linux命令的小工具

    在linux的脚本中,如果不对机器做其他的处理,不能实现在linux的机器上执行命令.为了解决这个问题,写了个小工具来解决这个问题. 后面的代码是利用java实现的可远程执行linux命令的小工具,代 ...

  9. 网络编程 - 1.简单的套接字通信/2.加上通信循环/3.bug修复/4.加上链接循环/5.模拟ssh远程执行命令

    1.简单的套接字通信 服务端 ''' 服务端 接电话 客户端 打电话 1.先启动服务端 2.服务端有两种套接字 1.phone 用来干接收链接的 2.conn 用来干收发消息的 ''' import ...

  10. 模拟ssh远程执行命令,粘包问题,基于socketserver实现并发的socket

    06.27自我总结 1.模拟ssh远程执行命令 利用套接字编来进行远程执行命令 服务端 from socket import * import subprocess server = socket(A ...

随机推荐

  1. 洛谷 P1582 倒水 解题报告

    P1582 倒水 题目描述 一天,CC买了N个容量可以认为是无限大的瓶子,开始时每个瓶子里有1升水.接着~~CC发现瓶子实在太多了,于是他决定保留不超过K个瓶子.每次他选择两个当前含水量相同的瓶子,把 ...

  2. Centos6.5之ssh免密码登录配置

    Centos6.5之ssh免密码登录配置 centos ssh 免密码登录 0.说明 这里为了方便说明问题,假设有A和B两台安装了centos6.5的主机.目标是实现A.B两台主机分别能够通过ssh免 ...

  3. P3747 相逢是问候 欧拉定理+线段树

    巨难!!! 去年六省联考唯一的一道黑牌题,我今天一天从早到晚,把它从暴力15分怼到了90分,极端接近正解了. bzoj上A了,但是洛谷和loj上面就不行.伪正解会T,奇奇怪怪的类正解会WA.. 那么, ...

  4. A1082. Read Number in Chinese

    Given an integer with no more than 9 digits, you are supposed to read it in the traditional Chinese ...

  5. 【洛谷P1638】逛画展

    题目大意:给定 N 个数字组成的序列,求刚好拥有所有 M 种数字的最短区间. 题解:双指针算法是一种对于暴力的优化算法,对于这道题来说,一个显然的暴力是:对于序列中每一个位置 pos,计算出这个位置右 ...

  6. 【洛谷P1376】机器工厂

    题目大意:给定两个有 N 个数的序列 A,B,每个点有一个对应的权值,现需要计算答案的贡献:\(B[i]*min\{A[j]+s*(i-j),j\in[1,i] \}\) 的最小值. 题解:由于 B ...

  7. 权限管理-ACL

    权限管理-ACL 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.ACL权限简介与开启 1.ACL权限简介 比如在根下有一个目录(”/yinzhengjie“),这个目录的所有者 ...

  8. idea常用的插件

    ignore 插件 可以自动生成.ignore文件   非常的实用 gitee 插件 搜所gitee安装即可  码云的插件 maven helper 插件 idea 中解决maven 包冲突的问题 a ...

  9. Hi3519v101-uboot-start.S分析

    00032: #include <config.h>00033: #include <version.h> 1)#include <config.h>.config ...

  10. Hbase记录-HBase扫描/计数/权限

    HBase扫描   scan 命令用于查看HTable数据.使用 scan 命令可以得到表中的数据.它的语法如下: scan ‘<table name>’ 下面的示例演示了如何使用scan ...