java远程调用linux上jar包
首先在远程服务器上编写一个测试脚本test.sh,并赋予可执行权限:chmod +x test.sh#!/bin/bashecho $1$1是脚本传进来的第一个参数,现在打印一下传进来的第一个参数。在pom中添加依赖dependency> groupId>org.jvnet.hudsongroupId> artifactId>ganymed-ssh2artifactId>
·
首先在远程服务器上编写一个测试脚本test.sh,并赋予可执行权限:chmod +x test.sh
$1是脚本传进来的第一个参数,现在打印一下传进来的第一个参数。#!/bin/bash echo $1
在pom中添加依赖
|
package cn.ctyun.audit.utils;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
public class RemoteShellTool {
private Connection conn;
private String ipAddr;
private String charset = Charset.defaultCharset().toString();
private String userName;
private String password;
public RemoteShellTool(String ipAddr, String userName, String password,
String charset) {
this.ipAddr = ipAddr;
this.userName = userName;
this.password = password;
if (charset != null) {
this.charset = charset;
}
}
public boolean login() throws IOException {
conn = new Connection(ipAddr);
conn.connect(); // 连接
return conn.authenticateWithPassword(userName, password); // 认证
}
public boolean exec(String cmds) {
InputStream in = null;
String result = "";
boolean flag = false;
try {
if (this.login()) {
Session session = conn.openSession(); // 打开一个会话
session.execCommand(cmds);
in = session.getStdout();
result = this.processStdout(in, this.charset);
session.close();
conn.close();
flag = true; }
} catch (IOException e1) {
e1.printStackTrace();
}
return flag;
}
public String processStdout(InputStream in, String charset) {
byte[] buf = new byte[1024];
StringBuffer sb = new StringBuffer();
try {
while (in.read(buf) != -1) {
sb.append(new String(buf, charset));
}
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
public static void main(String[] args) {
RemoteShellTool tool = new RemoteShellTool("hdp03", "root",
"hadoop", "utf-8");
boolean exec = tool.exec("/root/apps/jdk1.7.0_67/bin/java -jar AuditService.jar ");
System.out.print(exec);
}
}
注意:如果要执行jar命令需要写jdk的全路径,否则会找不到java的环境变量!
如果不想输入密码,可以参考下面的文章
更多推荐
已为社区贡献1条内容
所有评论(0)