Java SSH远程执行Shell命令、shell脚本实现(Ganymed SSH)
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)的更多相关文章
- ssh远程执行nohup命令不退出
https://blog.csdn.net/oneinmore/article/details/50073443
- SSH远程执行命令环境变量问题
SSH命令格式 usage: ssh [-1246AaCfgKkMNnqsTtVvXxYy] [-b bind_address] [-c cipher_spec] [-D [bind_address: ...
- Java SSH远程执行Shell脚本实现(转)
前言 此程序需要ganymed-ssh2-build210.jar包(下载地址:http://www.ganymed.ethz.ch/ssh2/) 为了调试方便,可以将\ganymed-ssh2-bu ...
- Hadoop概念学习系列之Java调用Shell命令和脚本,致力于hadoop/spark集群(三十六)
前言 说明的是,本博文,是在以下的博文基础上,立足于它们,致力于我的大数据领域! http://kongcodecenter.iteye.com/blog/1231177 http://blog.cs ...
- linux利用ssh远程执行多台机器执行同样的命令
这篇文章主要介绍了ssh远程执行命令方法和Shell脚本实例,本文讲解了ssh执行远程操作方法和远程执行命令shell脚本示例,需要的朋友可以参考下 ssh执行远程操作命令格式代码如下: ssh -t ...
- 解决SSH远程执行命令找不到环境变量的问题
通过SSH执行远程主机的命令或脚本时,经常会出现找不到自定义环境变量的问题.但是,如果通过SSH登录远程主机,然后再执行相同的命令或脚本,那么此时执行又是成功的.两种相似的方法,得到的结果却截然不同, ...
- [转帖]ssh 远程执行命令
ssh 远程执行命令 https://www.cnblogs.com/youngerger/p/9104144.html SSH 是 Linux 下进行远程连接的基本工具,但是如果仅仅用它来登录那可是 ...
- 利用java实现可远程执行linux命令的小工具
在linux的脚本中,如果不对机器做其他的处理,不能实现在linux的机器上执行命令.为了解决这个问题,写了个小工具来解决这个问题. 后面的代码是利用java实现的可远程执行linux命令的小工具,代 ...
- 网络编程 - 1.简单的套接字通信/2.加上通信循环/3.bug修复/4.加上链接循环/5.模拟ssh远程执行命令
1.简单的套接字通信 服务端 ''' 服务端 接电话 客户端 打电话 1.先启动服务端 2.服务端有两种套接字 1.phone 用来干接收链接的 2.conn 用来干收发消息的 ''' import ...
- 模拟ssh远程执行命令,粘包问题,基于socketserver实现并发的socket
06.27自我总结 1.模拟ssh远程执行命令 利用套接字编来进行远程执行命令 服务端 from socket import * import subprocess server = socket(A ...
随机推荐
- POJ 1958 Strange Towers of Hanoi 解题报告
Strange Towers of Hanoi 大体意思是要求\(n\)盘4的的hanoi tower问题. 总所周知,\(n\)盘3塔有递推公式\(d[i]=dp[i-1]*2+1\) 令\(f[i ...
- suoi46 最大和和 (线段树)
<Segment tree Beats!>,反正我不会 #include<bits/stdc++.h> #define pa pair<int,int> #defi ...
- MD5 SHA1 CRC32
md5: import hashlib md5 = hashlib.md5() md5.update(bytes('http://www.baidu.com',encoding="utf-8 ...
- Java核心技术-映射
集是一个集合,它可以快速地查找现有的元素.但是,要查看一个元素,需要有要查找元素的精确副本.这不是一种非常通用的查找方式.通常,我们知道某些键的信息,并想要查找与之对应的元素.映射(map)数据结构就 ...
- Windows 10更新时出现0x80070422错误
Windows更新 更新状态 安装更新时出现一些问题,但我们稍后会重试.如果你继续看到此错误,并想要搜索Web或联系支持人员以获取相关信息,一下信息可能会对你有帮助:(0x80070422) 分析原因 ...
- CentOS 7 系统的初化始配置
安装好CentOS7系统后我们要进行初始设置来让我们的服务器方便管理与使用,但是发现在7以前的版本都能输入的命令不能输入了,去官网查查才发发生了很大的变化,关于有哪些变化的可以点击这里查看,初始配置的 ...
- jdbc url写法(集群)
mysql集群,jdbc url写法:jdbc:mysql://[host:port],[host:port].../[database][?propertyName1][=propertyValue ...
- 我的 $OI$, 退役前写点东西
离 \(NOIp2018\) 还有五天, 总想写点什么 马上退役了啊 是什么时候喜欢上信息技术的呢 记不清了, 很小的时候就喜欢捣鼓关于电脑的东西 当时也不知道有算法这种东西 只是知道有黑客 巨 j8 ...
- yolo3的改变
转自:https://zhuanlan.zhihu.com/p/35394369 YOLOv3的前世今生 2013年,R-CNN横空出世,目标检测DL世代大幕拉开. 各路豪杰快速迭代,陆续有了SPP, ...
- 离线方式部署Ambari2.6.0.0
Hadoop生态圈-离线方式部署Ambari2.6.0.0 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 我现在所在的公司用的是CDH管理Hadoop集群,前端时间去面试时发现很多 ...