java让服务器停止运行,java调用远程服务器的shell脚本以及停止的方法实现

最近接了个需求,要求远程调shell脚本,你没听错!!!需求就一句话,咱是谁,咱是优秀的开发选手。考虑再三,有两种实现方式:

方案一:脚本所在服务器安装一个客户端,也就是自己写的一个小程序,本地通过端口调目标服务器的程序,然后程序调本机上的shell脚本!

优点:通过端口调用,用户不用暴露服务器的账号密码,安全性高

缺点:我们需要一直维护这个客户端程序,而且每接入一台服务器,都得安装该客户端,另外非常考验客户端程序的健壮性。

方案二:本地直接通过IP,服务器账号密码调远程服务器的shell脚本

优点:代码易开发,扩展时只用扩展服务端代码即可

缺点:用户服务器的账号密码会暴露给服务端,密码安全问题

把每种方案的优缺点汇报给leader,leader说:按第二种来吧

来吧!!开干,废话不多说,直接上代码:

导入程序所需的软件包:

org.jvnet.hudson

ganymed-ssh2

build210-hudson-1

程序涉及的demo:

import java.io.IOException;

import java.io.InputStream;

import java.io.UnsupportedEncodingException;

import java.nio.charset.Charset;

import org.apache.commons.io.IOUtils;

import ch.ethz.ssh2.ChannelCondition;

import ch.ethz.ssh2.Connection;

import ch.ethz.ssh2.Session;

import ch.ethz.ssh2.StreamGobbler;

public class RemoteShellExecutor {

private Connection conn;

/** 远程机器IP */

private String ip;

/** 用户名 */

private String osUsername;

/** 密码 */

private String password;

private String charset = Charset.defaultCharset().toString();

private final String GET_SHELL_PID = "ps -ef | grep '%s' | grep -v grep |awk '{print $2}'";

private final String KILL_SHELL_PID = "kill -15 %s";

private static final int TIME_OUT = 1000 * 5 * 60;

/**

* 构造函数

* @param ip

* @param usr

* @param pasword

*/

public RemoteShellExecutor(String ip, String usr, String pasword) {

this.ip = ip;

this.osUsername = usr;

this.password = pasword;

}

/**

* 登录

* @return

* @throws IOException

*/

private boolean login() throws IOException {

conn = new Connection(ip);

conn.connect();

return conn.authenticateWithPassword(osUsername, password);

}

/**

* 执行脚本

*

* @param cmds

* @return

* @throws Exception

*/

public ExecuteResultVO exec(String cmds) throws Exception {

InputStream stdOut = null;

InputStream stdErr = null;

ExecuteResultVO executeResultVO = new ExecuteResultVO();

String outStr = "";

String outErr = "";

int ret = -1;

try {

if (login()) {

// Open a new {@link Session} on this connection

Session session = conn.openSession();

// Execute a command on the remote machine.

session.execCommand(cmds);

stdOut = new StreamGobbler(session.getStdout());

outStr = processStream(stdOut, charset);

stdErr = new StreamGobbler(session.getStderr());

outErr = processStream(stdErr, charset);

session.waitForCondition(ChannelCondition.EXIT_STATUS, TIME_OUT);

System.out.println("outStr=" + outStr);

System.out.println("outErr=" + outErr);

ret = session.getExitStatus();

executeResultVO.setOutStr(outStr);

executeResultVO.setOutErr(outErr);

} else {

throw new Exception("登录远程机器失败" + ip); // 自定义异常类 实现略

}

} finally {

if (conn != null) {

conn.close();

}

IOUtils.closeQuietly(stdOut);

IOUtils.closeQuietly(stdErr);

}

return ret;

}

/**

* @param in

* @param charset

* @return

* @throws IOException

* @throws UnsupportedEncodingException

*/

private String processStream(InputStream in, String charset) throws Exception {

byte[] buf = new byte[1024];

StringBuilder sb = new StringBuilder();

int len = 0;

while ((len=in.read(buf)) != -1) {

sb.append(new String(buf,0,len, charset));

}

return sb.toString();

}

public static void main(String args[]) throws Exception {

//调远程shell

RemoteShellExecutor executor = new RemoteShellExecutor("192.168.234.123", "root", "beebank");

System.out.println(executor.exec("sh /data/checkMysql.sh"));

//获取远程shell 进程 pid

ExecuteResultVO executeResultVO = executor.exec(String.format(GET_SHELL_PID,"sh /data/checkMysql.sh"));

//杀掉shell进程

ExecuteResultVO executeResultVO1 = executor.exec(String.format(KILL_SHELL_PID ,executeResultVO.getOutStr()));

}

public class ExecuteResultVO{

private String outStr;

private String outErr;

//省略get set

}

}

经过测试也确实好用啊,大家可以根据这个demo进行相应的修改。到此这篇关于java调远程服务器的shell脚本以及停止的方法实现的文章就介绍到这了,更多相关java调远程shell脚本内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在Java调用远程服务器Shell脚本,可以使用Java的Runtime类的exec()方法。这个方法可以让你在Java程序中执行命令。具体步骤如下: 1. 首先,确保你已经在本地和远程服务器上安装了Java环境和SSH服务。 2. 在Java程序中,使用Runtime.getRuntime().exec()方法来执行远程服务器上的Shell命令。你需要提供SSH连接的用户名、密码和远程服务器的IP地址。 3. 在exec()方法中,可以使用ssh命令来连接远程服务器,并执行相应的Shell脚本。例如,你可以使用以下命令: ``` Runtime.getRuntime().exec("ssh username@remote_server_ip 'sh /path/to/remote_script.sh'"); ``` 这个命令将使用ssh连接远程服务器,然后执行远程服务器上的Shell脚本。 需要注意的是,你需要替换命令中的"username"为你的SSH用户名,"remote_server_ip"为远程服务器的IP地址,以及"/path/to/remote_script.sh"为远程服务器Shell脚本的路径。 此外,你还可以使用SSH密钥对来进行认证,以增加安全性。详细的使用方法可以参考引用和引用所提供的链接。 希望这个回答可以帮到你。如果你还有其他问题,请随时提问。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [Java代码 调用远程服务器中的Shell脚本。](https://blog.csdn.net/u010797364/article/details/109256790)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值