Ganymed实现基本的自动化部署API

2024-09-08 07:38

本文主要是介绍Ganymed实现基本的自动化部署API,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

  • Ganymed
    SSH-2 for Java是一个纯Java实现的SHH2库,官网为http://www.ganymed.ethz.ch/ssh2/,最新的更新时间为2006年10月,在用之前,请仔细看一下FAQ,真的能避免很多很多问题
    在google上找到的ganymed-ssh2的官网是http://www.ganymed.ethz.ch/ssh2/,进去看官网的英文简介可以看到该网站已经不维护该项目,并已经迁移到http://www.cleondris.ch/,在这个网站点击右上角的Contact,再点击open source就可以看到这个项目的新家,http://www.cleondris.ch/opensource/ssh2/,上面简单介绍了该项目能远程连接上远程机器,支持命令模式和shell模式,本地和远程端口转发,没有任何JCE依赖等,最后特别指出这个项目是为瑞士苏黎世的一个项目所创建。下面提供了2010-08-23发布的ganymed-ssh2-build251beta1.zip可供下载使用,下面还有在线文档和FAQ供开发者参考。
  • JSch
    采用java编写,使用ssh来操作远程服务器。JSch 是SSH2的一个纯Java实现。它允许你连接到一个sshd 服务器,支持文件的上传和下载,支持在远程机上执行shell命令、shell脚本、重启等操作。
    但是这个类库偏向底层,仅是ssh2的实现,连文件夹的上传下载都不支持,并不是针对自动化部署的,编写的代码比较长,上手和实际使用起来不太方便,所以要对其进行必要的封装,比如封装连接的获取释放、文件夹和文件的拷贝、远程命令的执行等。
  • sshxcute
    sshxcute 框架是对JSch 的简单封装,提供了更为便捷的 API 接口,提供了更加灵活实用的功能,从而可以让开发人员更加得心应手的使用。sshxcute 是一个框架,它允许工程师利用 Java 代码通过 SSH 连接远程执行 Linux/UNIX 系统上的命令或者脚本,这种方式不管是针对软件测试还是系统部署,都简化了自动化测试与系统环境部署的步骤。
    但是它的封装比较简单,功能比较弱,只有上传和执行命令或脚本的功能。

  • 包装Ganymed。实现了文件的上传下载,文件夹的上传,远程执行命令,执行本地命令等基础API:

package base;import java.io.IOException;
import java.io.InputStream;public final class ExecLocakCommand {public static final String processUseBasic(String cmd) {Process p = null;StringBuilder sb = new StringBuilder();try {String os = System.getProperty("os.name").toLowerCase();if (os.startsWith("win")) {String commands = "cmd /c " + cmd;p = Runtime.getRuntime().exec(commands);} else if (os.startsWith("linux")) {String[] commands = new String[] { "/bin/sh", "-c", cmd };p = Runtime.getRuntime().exec(commands);}String error = read(p.getErrorStream());String outInfo = read(p.getInputStream());String resultCode = "0";// 脚本中输出0表示命令执行成功if (error.length() != 0) { // 如果错误流中有内容,表明脚本执行有问题resultCode = "1";}sb.append(resultCode).append("\n");sb.append(error).append("\n");sb.append(outInfo);p.waitFor();} catch (Exception e) {e.printStackTrace();} finally {try {p.getErrorStream().close();p.getInputStream().close();p.getOutputStream().close();} catch (IOException e) {e.printStackTrace();}}return sb.toString();}public static final String read(InputStream in) throws IOException {StringBuilder sb = new StringBuilder();int ch;while (-1 != (ch = in.read()))sb.append((char) ch);return sb.toString();}public static void main(String[] args) {String comands = "dir";//String comands = "ls ";String ret = ExecLocakCommand.processUseBasic(comands);System.out.println(ret);}
}
package base;import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;public class propertyUtil {private static Properties prop = new Properties();private static void load(String fileName) {try {prop.load(new FileInputStream(fileName));} catch (IOException e) {e.printStackTrace();}}public static String getProperty(String fileName, String key) {load(fileName);return prop.getProperty(key);}public static void setProper(String fileName, String key, String value) {try {load(fileName);prop.setProperty(key, value);FileOutputStream fos = new FileOutputStream(fileName);prop.store(fos, null);fos.close();} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}public static void main(String[] args) {System.out.println(propertyUtil.getProperty("test.properties", "key"));propertyUtil.setProper("test.properties", "key", "xxxx");System.out.println(propertyUtil.getProperty("test.properties", "key"));}
}
package base;import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;import com.google.common.base.Splitter;import ch.ethz.ssh2.ChannelCondition;
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.SCPClient;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;public class RemoteExecutionApi {private int port = 22;private String username;private String password;public RemoteExecutionApi(int port, String username, String password) {super();this.port = port;this.username = username;this.password = password;}public RemoteExecutionApi(String username, String password) {super();this.username = username;this.password = password;}// 下载文件,目前只能下载单个文件public void getFile(String remoteFile, String localTargetDirectory, String ips) {Iterable<String> result = Splitter.on(',').trimResults().omitEmptyStrings().split(ips);for (String ip : result) {Connection conn = new Connection(ip, port);try {conn.connect();boolean isAuthenticated = conn.authenticateWithPassword(username, password);if (isAuthenticated == false) {System.err.println("authentication failed");}SCPClient client = new SCPClient(conn);client.get(remoteFile, localTargetDirectory);conn.close();} catch (IOException ex) {ex.printStackTrace();// Logger operatorSystem.exit(2);}}}//上传文件或者文件夹public void putFile(String localFile, String remoteTargetDirectory, String ips) {Iterable<String> result = Splitter.on(',').trimResults().omitEmptyStrings().split(ips);for (String ip : result) {Connection conn = new Connection(ip, port);try {conn.connect();boolean isAuthenticated = conn.authenticateWithPassword(username, password);if (isAuthenticated == false) {System.err.println("authentication failed");}// folderif (new File(localFile).isDirectory()) {// 先创建根目录String dirName = new File(localFile).getName();remoteTargetDirectory = remoteTargetDirectory + "/" + dirName;Session sess1 = conn.openSession();sess1.execCommand("mkdir -p " + remoteTargetDirectory);sess1.waitForCondition(ChannelCondition.EOF, 0);sess1.close();putDir(conn, localFile, remoteTargetDirectory);} else if (new File(localFile).isFile()) {// fileSCPClient client = new SCPClient(conn);client.put(localFile, remoteTargetDirectory);}conn.close();} catch (IOException ex) {ex.printStackTrace();// Logger operatorSystem.exit(2);}}}private void putDir(Connection conn, String localDirectory, String remoteTargetDirectory) throws IOException {String[] fileList = new File(localDirectory).list();for (String file : fileList) {String fullFileName = localDirectory + new File(localDirectory).separator + file;if (new File(fullFileName).isDirectory()) {final String subDir = remoteTargetDirectory + "/" + file;Session sess = conn.openSession();sess.execCommand("mkdir " + subDir);sess.waitForCondition(ChannelCondition.EOF, 0);sess.close();putDir(conn, fullFileName, subDir);} else {SCPClient client = new SCPClient(conn);client.put(fullFileName, remoteTargetDirectory);}}}// 执行命令public String runCommand(String command, String ips) {StringBuilder sb = new StringBuilder();Iterable<String> result = Splitter.on(',').trimResults().omitEmptyStrings().split(ips);for (String ip : result) {Connection conn = new Connection(ip, port);try {conn.connect();boolean isAuthenticated = conn.authenticateWithPassword(username, password);if (isAuthenticated == false) {System.err.println("authentication failed");}Session sess = conn.openSession();sess.execCommand(command);InputStream stdout = new StreamGobbler(sess.getStdout());BufferedReader br = new BufferedReader(new InputStreamReader(stdout));while (true) {String line = br.readLine();if (line == null)break;sb.append(line).append("\n");}System.out.println("ExitCode: " + sess.getExitStatus());br.close();sess.close();conn.close();} catch (IOException ex) {ex.printStackTrace(System.err);// Logger operatorSystem.exit(2);}}return sb.toString();}// 删除临时文件public void delTempDir(String remotePath, String ips) {runCommand("rm -rf " + remotePath, ips);}// 修改配置文件public void modfiyPropertyFile(String remoteFileName, String key, String value, String ips) {String tempDir = "tempDir";File folder = new File(tempDir);folder.mkdirs();Iterable<String> result = Splitter.on(',').trimResults().omitEmptyStrings().split(ips);for (String ip : result) {Connection conn = new Connection(ip, port);try {conn.connect();boolean isAuthenticated = conn.authenticateWithPassword(username, password);if (isAuthenticated == false) {System.err.println("authentication failed");}SCPClient client = new SCPClient(conn);client.get(remoteFileName, tempDir);String tmpFileName = tempDir + File.separator+ remoteFileName.substring(remoteFileName.lastIndexOf("/"));propertyUtil.setProper(tmpFileName, key, value);client.put(tmpFileName, remoteFileName.substring(0, remoteFileName.lastIndexOf('/')));conn.close();} catch (IOException ex) {ex.printStackTrace(System.err);// Logger operatorSystem.exit(2);}}clearDir(folder);}private void clearDir(File file) {if (file.isDirectory()) {for (File f : file.listFiles()) {clearDir(f);f.delete();}}file.delete();}// 在配置文件后添加新行public void propertyFileAddNewline(String remoteFileName, String newline, String ips) {runCommand("echo " + newline + " >> " + remoteFileName, ips);}// 重启机器public void reboot(String ips) {runCommand("reboot", ips);}// 执行本地命令public String runLoaclCommand(String command) {return ExecLocakCommand.processUseBasic(command);}public static void main(String[] args) {RemoteExecutionApi client = new RemoteExecutionApi("root", "123456");// client.getFile("/root/test.txt","C:", "192.168.238.129");//client.putFile("D:\\test", "/root", "192.168.238.129");// String ret = client.runCommand("ls /", "192.168.238.129");// System.out.println(ret);// client.putDir("D:\\test", "/root", "192.168.238.129");// client.modfiyPropertyFile("/root/test.proprety", "key", "yyy",// "192.168.238.129");// client.propertyFileAddNewline("/root/xx.txt", "yyyyy=xxxxx",// "192.168.238.129");String ret = client.runLoaclCommand("dir");System.out.println(ret);System.out.println("----");}}

这篇关于Ganymed实现基本的自动化部署API的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1147510

相关文章

使用Python实现IP地址和端口状态检测与监控

《使用Python实现IP地址和端口状态检测与监控》在网络运维和服务器管理中,IP地址和端口的可用性监控是保障业务连续性的基础需求,本文将带你用Python从零打造一个高可用IP监控系统,感兴趣的小伙... 目录概述:为什么需要IP监控系统使用步骤说明1. 环境准备2. 系统部署3. 核心功能配置系统效果展

Python实现微信自动锁定工具

《Python实现微信自动锁定工具》在数字化办公时代,微信已成为职场沟通的重要工具,但临时离开时忘记锁屏可能导致敏感信息泄露,下面我们就来看看如何使用Python打造一个微信自动锁定工具吧... 目录引言:当微信隐私遇到自动化守护效果展示核心功能全景图技术亮点深度解析1. 无操作检测引擎2. 微信路径智能获

redis中使用lua脚本的原理与基本使用详解

《redis中使用lua脚本的原理与基本使用详解》在Redis中使用Lua脚本可以实现原子性操作、减少网络开销以及提高执行效率,下面小编就来和大家详细介绍一下在redis中使用lua脚本的原理... 目录Redis 执行 Lua 脚本的原理基本使用方法使用EVAL命令执行 Lua 脚本使用EVALSHA命令

Python中pywin32 常用窗口操作的实现

《Python中pywin32常用窗口操作的实现》本文主要介绍了Python中pywin32常用窗口操作的实现,pywin32主要的作用是供Python开发者快速调用WindowsAPI的一个... 目录获取窗口句柄获取最前端窗口句柄获取指定坐标处的窗口根据窗口的完整标题匹配获取句柄根据窗口的类别匹配获取句

在 Spring Boot 中实现异常处理最佳实践

《在SpringBoot中实现异常处理最佳实践》本文介绍如何在SpringBoot中实现异常处理,涵盖核心概念、实现方法、与先前查询的集成、性能分析、常见问题和最佳实践,感兴趣的朋友一起看看吧... 目录一、Spring Boot 异常处理的背景与核心概念1.1 为什么需要异常处理?1.2 Spring B

Python位移操作和位运算的实现示例

《Python位移操作和位运算的实现示例》本文主要介绍了Python位移操作和位运算的实现示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一... 目录1. 位移操作1.1 左移操作 (<<)1.2 右移操作 (>>)注意事项:2. 位运算2.1

如何在 Spring Boot 中实现 FreeMarker 模板

《如何在SpringBoot中实现FreeMarker模板》FreeMarker是一种功能强大、轻量级的模板引擎,用于在Java应用中生成动态文本输出(如HTML、XML、邮件内容等),本文... 目录什么是 FreeMarker 模板?在 Spring Boot 中实现 FreeMarker 模板1. 环

Qt实现网络数据解析的方法总结

《Qt实现网络数据解析的方法总结》在Qt中解析网络数据通常涉及接收原始字节流,并将其转换为有意义的应用层数据,这篇文章为大家介绍了详细步骤和示例,感兴趣的小伙伴可以了解下... 目录1. 网络数据接收2. 缓冲区管理(处理粘包/拆包)3. 常见数据格式解析3.1 jsON解析3.2 XML解析3.3 自定义

SpringMVC 通过ajax 前后端数据交互的实现方法

《SpringMVC通过ajax前后端数据交互的实现方法》:本文主要介绍SpringMVC通过ajax前后端数据交互的实现方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价... 在前端的开发过程中,经常在html页面通过AJAX进行前后端数据的交互,SpringMVC的controll

Spring Security自定义身份认证的实现方法

《SpringSecurity自定义身份认证的实现方法》:本文主要介绍SpringSecurity自定义身份认证的实现方法,下面对SpringSecurity的这三种自定义身份认证进行详细讲解,... 目录1.内存身份认证(1)创建配置类(2)验证内存身份认证2.JDBC身份认证(1)数据准备 (2)配置依