远程shell脚本执行工具类

/**
* 远程shell脚本执行工具类
*/
public class RemoteShellExecutorUtils {
private static final Logger logger = LoggerFactory.getLogger(RemoteShellExecutorUtils.class);

private Connection conn;
/**
* 服务器IP
*/
private String ip;
/**
* 用户名
*/
private String user;
/**
* 密码
*/
private String password;
private String charset = Charset.defaultCharset().toString();

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

/**
* 构造函数
*
* @param ip 服务器地址
* @param user 用户名
* @param pwd 密码
*/
public RemoteShellExecutorUtils(String ip, String user, String pwd) {
this.ip = ip;
this.user = user;
this.password = pwd;
}


/**
* 登录
*
* @return
* @throws IOException
*/
private boolean login() throws IOException {
conn = new Connection(ip);
conn.connect();
return conn.authenticateWithPassword(user, password);
}


/**
* 执行脚本
*
* @param cmd shell命令
* @return
*/
public Map<String,String> exec(String cmd) {
InputStream stdOut = null;
InputStream stdErr = null;
String outStr = "";
String outErr = "";
Map<String,String> map = new HashMap<String,String>();
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(cmd);

stdOut = new StreamGobbler(session.getStdout());
outStr = processStream(stdOut, charset);
map.put("outStr",outStr);

stdErr = new StreamGobbler(session.getStderr());
outErr = processStream(stdErr, charset);
map.put("outErr",outErr);

session.waitForCondition(ChannelCondition.EXIT_STATUS, TIME_OUT);

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

ret = session.getExitStatus();
map.put("ret",ret+"");
} else {
logger.error("登录远程机器失败:" + ip);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (conn != null) {
conn.close();
}
if (stdOut != null) {
stdOut.close();
}
if (stdErr != null) {
stdErr.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return map;
}

/**
* @param in 输入流
* @param charset 字符编码
* @return
* @throws Exception
*/
private String processStream(InputStream in, String charset) throws IOException {
byte[] buf = new byte[1024];
StringBuilder sb = new StringBuilder();
while (in.read(buf) != -1) {
sb.append(new String(buf, charset));
}
return sb.toString();
}

/**
* 关闭连接
*/
public void close(){
if(conn != null){
conn.close();
}
}

public static void main(String[] args) {
RemoteShellExecutorUtils executorUtils = new RemoteShellExecutorUtils("172.22.2.118",
"hadoop", "hadoop");
String shell = String.format("sh %s %s %s %s", "/dataexchange/kafka/create.sh",
"topic_create_test", "1", "2");

// String shell = String.format("sh %s %s", "/dataexchange/kafka/topics.sh","topic_create_test");

Map<String,String> map = executorUtils.exec(shell);

if("".equals(map.get("outStr")) && "".equals(map.get("outErr")) && "0".equals(map.get("ret"))){
System.out.println("topic不存在");
} else if (!"".equals(map.get("outErr"))){
System.out.println("远程shell脚本执行异常>>>>"+map.get("outErr"));
} else if (!"".equals(map.get("outStr"))){
System.out.println("topic已存在");
}
}
}


依赖包
<dependency>
<groupId>org.jvnet.hudson</groupId>
<artifactId>ganymed-ssh2</artifactId>
<version>build210-hudson-1</version>
</dependency>
posted @ 2018-12-11 11:15  zhoufly  阅读(1146)  评论(0编辑  收藏  举报