使用 ganymed 工具远程登录资源执行脚本命令
package com.zxl.ganymed;
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
public final class GanymedDemo {
private Logger log = LoggerFactory.getLogger(getClass());
private Connection connection;
private Session session;
private BufferedReader stdout;
private PrintWriter printWriter;
private ExecutorService service = Executors.newFixedThreadPool(2);
private static List<String> commands = null;
private static void initCommands() {
commands = new ArrayList<String>();
commands.add("ll");
commands.add("cd /home/liang");
commands.add("pwd");
}
public void initSession(String hostName, String userName, String passwd, int port) throws IOException {
connection = new Connection(hostName,port);
connection.connect();
boolean authenticateWithPassword = connection.authenticateWithPassword(userName, passwd);
if (!authenticateWithPassword) {
throw new RuntimeException("Authentication failed. Please check hostName, userName and passwd");
}
session = connection.openSession();
session.requestDumbPTY();
session.startShell();
stdout = new BufferedReader(new InputStreamReader(new StreamGobbler(session.getStdout()), StandardCharsets.UTF_8));
printWriter = new PrintWriter(session.getStdin());
initCommands();
}
public void execCommand() throws IOException {
service.submit(new Runnable() {
@Override
public void run() {
String line;
try {
boolean flag = false;
while ((line = stdout.readLine()) != null) {
if (line.contains(commands.get(0))){
flag = true;
}
if (flag){
System.out.println(line);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
});
for (String command : commands) {
while (true) {
printWriter.write(command + "\r\n");
printWriter.flush();
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
break;
}
}
System.out.println("============结束===============");
}
public void close() {
try {
connection.close();
service.shutdown();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws IOException {
GanymedDemo conn = new GanymedDemo();
conn.initSession("127.0.0.1", "test", "test",2200);
conn.execCommand();
conn.close();
}
}
采纳博主:A_Beaver