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. Spark 集成开发

    WordCount.py # coding:utf-8 from pyspark import SparkContext from pyspark import SparkConf def SetLo ...

  2. Python数据类型(字典和集合)

    1.5 Dictionary(字典) 在Python中,字典用放在花括号{}中一系列键-值对表示.键和值之间用冒号分隔,键-值对之间用逗号分隔. 在字典中,你想存储多少个键-值对都可以.每个键都与一个 ...

  3. Power BI 实现实时更新Streaming Dataset

    一.在PowerBI portal端需要准备的操作: 1. https://app.powerbi.cn 登陆,点击左侧My Workspace,你需要有一个账号 2. 选入Datasets,点击页面 ...

  4. HDU 3081 Marriage Match II (网络流,最大流,二分,并查集)

    HDU 3081 Marriage Match II (网络流,最大流,二分,并查集) Description Presumably, you all have known the question ...

  5. Codeforces Round #525 (Div. 2) Solution

    A. Ehab and another construction problem Water. #include <bits/stdc++.h> using namespace std; ...

  6. [译]Golang中的优雅重启

    原文 Graceful Restart in Golang 作者 grisha 声明:本文目的仅仅作为个人mark,所以在翻译的过程中参杂了自己的思想甚至改变了部分内容,其中有下划线的文字为译者添加. ...

  7. linux centos7安装python3

    折腾 Python官网: https://www.python.org/ 查看相关评论,众人大呼python2与python3为两种语言,既然继承性不大,那我也就直接学python3了. 在系统选择, ...

  8. vue基础篇---修改对象或数组的值,页面实时刷新

    这个问题估计大家很难想到,如果一个数组[1,2,3,4],然后我们v-for遍历,我们改变数组的值,arr[1] = 5 ,难道不应该改变么?按理说根据vue的特性应该是改变的,但是事实上确实数组已经 ...

  9. 浅析 Bigtable 和 LevelDB 的实现

    在 2006 年的 OSDI 上,Google 发布了名为 Bigtable: A Distributed Storage System for Structured Data 的论文,其中描述了一个 ...

  10. HDU - 5340 Three Palindromes(manacher算法)

    http://acm.hdu.edu.cn/showproblem.php?pid=5340 题意 判断是否能将字符串S分成三段非空回文串 分析 manacher预处理出前缀和后缀回文的位置, 枚举第 ...