Java通过SSH2协议执行远程Shell脚本(ganymed-ssh2-build210.jar)



该工具Jar包可在:http://download.csdn.net/detail/shenjianox/7769783及文档下载地址

ganymed-ssh2简介:

Ganymed SSH-2 for Java是用纯Java实现SSH-2协议的一个包。在使用它的过程中非常容易,只需要指定合法的用户名口令,

或者授权认证文件,就可以创建到远程Linux主机的连接,在建立起来的会话中调用该Linux主机上的脚本文件,执行相关操作。

使用方法:

将 ganymed-ssh2-build210.jar 加入到项目的lib中。

简单示例:

假定我在192.168.0.114的Linux系统的/home/lldu目录下放了一个文件夹test,test文件夹对应测试Java类的包名test,我们在该机器上运用javac ./test/Main.java编译后,再通过调用下面的代码完成远程调用:

import ch.ethz.ssh2.Connection;

import ch.ethz.ssh2.ConnectionInfo;

import ch.ethz.ssh2.Session;

/**

*

* @author lldu

*/

public class Main {

public static void main(String[] args) {

try {

Connection con = new Connection("192.168.0.114");

ConnectionInfo info = con.connect();

boolean result = con.authenticateWithPassword("lldu", "123456");

Session session = con.openSession();

session.execCommand("java test.Main");

} catch (Exception ex) {

System.out.println(ex.getLocalizedMessage());

}

}

}

总结使用步骤:

1.首先构造一个连接器,传入一个需要登陆的ip地址

Connection conn = new Connection(ipAddr);

conn.connect(); // 连接

2.模拟登陆目的服务器 传入用户名和密码 ,

boolean isAuthenticated = conn.authenticateWithPassword(username, password);它会返回一个布尔值,true 代表成功登陆目的服务器,否则登陆失败

3.打开一个session,有点象Hibernate的session ,执行你需要的linux 脚本命令 。

Session sess = conn.openSession();

sess.execCommand("last");

4.接收目标服务器上的控制台返回结果,读取br中的内容

InputStream stdout = new StreamGobbler(sess.getStdout());

BufferedReader br = new BufferedReader(new InputStreamReader(stdout));

5.得到脚本运行成功与否的标志 :0-成功 非0-失败

System.out.println("ExitCode: " + sess.getExitStatus());

6.关闭session和connection

sess.close();

conn.close();

需要说明的是:

1.通过第2步认证成功后,当前目录就位于/home/username/目录之下,你可以指定脚本文件所在的绝对路径,或者通过cd导航到脚本文件所在的目录,然后传递执行脚本所需要的参数,完成脚本调用执行。

2.执行脚本以后,可以获取脚本执行的结果文本,需要对这些文本进行正确编码后返回给客户端,避免乱码产生。

3.如果你需要执行多个linux控制台脚本,比如第一个脚本的返回结果是第二个脚本的入参,你必须打开多个Session,也就是多次调用

Session sess = conn.openSession();,使用完毕记得关闭就可以了

=================================================================================================

摘录部分源码如下:

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStream;

import java.io.InputStreamReader;

import org.apache.log4j.Logger;

import ch.ethz.ssh2.Connection;

import ch.ethz.ssh2.SCPClient;

import ch.ethz.ssh2.Session;

import ch.ethz.ssh2.StreamGobbler;

public class CommandRunner {

private static final Logger logger = Logger.getLogger(CommandRunner.class);

//从其他网络计算机中拿去文件

public static void scpGet(String host, String username, String password,

String remoteFile, String localDir) throws IOException {

if (logger.isDebugEnabled()) {

logger.debug("spc [" + remoteFile + "] from " + host + " to "

+ localDir);

}

Connection conn = getOpenedConnection(host, username, password);

SCPClient client = new SCPClient(conn);

client.get(remoteFile, localDir);

conn.close();

}

//将文件拷贝到其他计算机上

public static void scpPut(String host, String username, String password,

String localFile, String remoteDir) throws IOException {

if (logger.isDebugEnabled()) {

logger.debug("spc [" + localFile + "] to " + host + remoteDir);

}

Connection conn = getOpenedConnection(host, username, password);

SCPClient client = new SCPClient(conn);

client.put(localFile, remoteDir);

conn.close();

}

//执行SSH命令.

public static int runSSH(String host, String username, String password,

String cmd) throws IOException {

if (logger.isDebugEnabled()) {

logger.debug("running SSH cmd [" + cmd + "]");

}

Connection conn = getOpenedConnection(host, username, password);

Session sess = conn.openSession();

sess.execCommand(cmd);

InputStream stdout = new StreamGobbler(sess.getStdout());

BufferedReader br = new BufferedReader(new InputStreamReader(stdout));

while (true) {

String line = br.readLine();

if (line == null)

break;

if (logger.isDebugEnabled()) {

logger.debug(line);

}

}

sess.close();

conn.close();

return sess.getExitStatus().intValue();

}

//获得连接

private static Connection getOpenedConnection(String host, String username,

String password) throws IOException {

if (logger.isDebugEnabled()) {

logger.debug("connecting to " + host + " with user " + username

+ " and pwd " + password);

}

Connection conn = new Connection(host);

conn.connect(); // make sure the connection is opened

boolean isAuthenticated = conn.authenticateWithPassword(username,

password);

if (isAuthenticated == false)

throw new IOException("Authentication failed.");

return conn;

}

//执行本地的cmd命令.(DOS命令)

public static int runLocal(String cmd) throws IOException {

if (logger.isDebugEnabled()) {

logger.debug("running local cmd [" + cmd + "]");

}

Runtime rt = Runtime.getRuntime();

Process p = rt.exec(cmd);

InputStream stdout = new StreamGobbler(p.getInputStream());

BufferedReader br = new BufferedReader(new InputStreamReader(stdout));

while (true) {

String line = br.readLine();

if (line == null)

break;

if (logger.isDebugEnabled()) {

logger.debug(line);

}

}

return p.exitValue();

}

}

Java通过SSH2协议执行远程Shell脚本(ganymed-ssh2-build210.jar)

时间: 2024-08-27 13:29:42

Java通过SSH2协议执行远程Shell脚本(ganymed-ssh2-build210.jar)的相关文章

jenkins:执行远程shell脚本时,脚本没有生效

问题: jenkins远程部署一台机器时,jenkins构建显示成功,但是查看服务日志却没有真正执行的sh run.sh脚本,导致服务并没有启动 解决: 只需要在命令最上方加上source /etc/profile就可以了 参考:https://blog.csdn.net/y6300023290/article/details/86246463 原文地址:https://www.cnblogs.com/gcgc/p/10823775.html

远程shell脚本执行工具类

/** * 远程shell脚本执行工具类 */public class RemoteShellExecutorUtils { private static final Logger logger = LoggerFactory.getLogger(RemoteShellExecutorUtils.class); private Connection conn; /** * 服务器IP */ private String ip; /** * 用户名 */ private String user;

把ps -ef & kill指令写成可以自动执行的shell脚本

之前重启服务器上的服务,均是先使用ps -ef | grep xxx指令查询出PID,然后再使用kill -9 PID指令杀死进程.由于重启的服务只止一个,每次都要重复输入,甚是麻烦. 示例 今天研究了一下,把以上手动查杀.重启服务的过程写成了shell脚本,重启服务只需执行脚本就可以了.附脚本样例: 1 #!/bin/sh 2 3 # restart das-web 4 ps -ef | grep /home/***/das-web/ | awk '{print $2}' | xargs -n

每秒执行一个shell脚本)(转)

Linux一个简单的每秒执行命令shell脚本 2012-08-06 11:47:06 分类: Python/Ruby 上周迁移了一台服务器,发现其中一个项目的数据没有更新,查询原服务器的数据,数据有更新,并找到了rsync服务,从其他服务器传输数据,那么如何找到这台服务器?因为是从远程传输到本地,而且不是很频繁,手动查找通信记录,没有结果. 写了一个脚本进行跟踪下,考虑到通信时间短的问题. 需要每秒执行一次命令,通过linux自带的cron却不能实现,新版的cron据说可以精确到秒. 1.编写

【原】Java程序调用远程Shell脚本

此程序的目的是执行远程机器上的Shell脚本. [环境参数]远程机器IP:192.168.234.123用户名:root密码:rootShell脚本的路径:/home/IFileGenTool /BakProvisionAndOccurEntrance.sh [具体步骤]1.在远程机器上,准备Shell脚本.[[email protected] IFileGenTool]# vim ./load_data.sh 1 #!/bin/sh 2 source /etc/profile 3 dbName

在Jenkins中配置执行远程shell命令

用过Jenkins的都知道,在Build配置那里有一个Add buld step, 有这样两个选项: 1. Execute Windows batch command 2. Execute shell 第1个是执行windows命令,第2个是执行shell脚本. 一开始我以为不管jenkins安装在windows下还是linux下都可以执行windows命令和linux命令,但是后来我发现在windows中,是可以执行第1个的,但是用第2个选项执行shell会失败,会报错说不能执行sh. 我想第

批量复制及执行命令shell脚本

平时在处理一个或几个机器运行环境时,一个机器一个机器处理也能接受,但是如果是一批机器,几十或几百台,要是一台一台去安装环境,光是输入同一的命令,估计你自己都想吐,所有聪明的人会想一些偷懒的办法,确实可以找到一些省时省力的方法,比如写一个批量处理shell脚本,这几天在处理一批(八九十台)机器环境,找了一些批量处理的脚本,包括批量传输(scp)文件到多台机器上.批量执行命令到多台机器.还有需要交互的命令,下面记录一些这些命令: 机器IP文件:ip.txt 192.168.10.201 192.16

ssh执行远程服务器脚本 提示php: command not found

设置环境变量 一台机器作为管理机,来管理其他服务器,并通过key认证,免密码登陆的. 在管理机上通过ssh登陆到其他服务器来远程执行命令 ssh [email protected] "cmd" 执行远程服务器上的某个脚本,却报错,提示PHP:command not found 找不到php命令 远程机 which php  结果是/usr/local/php/bin/php echo $PATH 结果是  已经添加到PATH中了,却不好使 解决:在远程机上执行 ln -s /usr/l

Linux学习笔记:bash特性之多命令执行,shell脚本

今天我们学习了bash特性多命令执行包括各个命令之间的逻辑关系.其中包含"与""或""非"命令的执行.下面即为我们所学习的这些逻辑命令关系之间的关系. 选择执行结构: 逻辑运算: 与:逻辑乘法,&& 0:成功执行 -->true 1-255:失败 -->false true && true =true true && false = false false && true