Java程序运行时如何对linux服务器做出一些指令,可以直接执行shell命令或者脚本并输出控制台信息。
1.引入类
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
2.单个命令执行方法
public void exec(String deployHost, String deployUsername, String deployPassword, String cmd) {
try {
Connection conn = new Connection(deployHost);
conn.connect();
boolean isAuthenticated = conn.authenticateWithPassword(deployUsername, deployPassword);
if (isAuthenticated == false) {
throw new IOException("认证失败");
}
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;
logger.info(line);
}
logger.info("ExitCode: " + sess.getExitStatus());
//关闭连接
stdout.close();
sess.close();
conn.close();
} catch (IOException e) {
logger.error("Command execution error");
e.printStackTrace();
}
}
3.多条命令执行方法
public void execCommands(String deployHost, String deployUser, String deployPassword, String[] cmd) {
try {
Connection conn = new Connection(deployHost);
conn.connect();
boolean isAuthenticated = conn.authenticateWithPassword(deployUser, deployPassword);
if (isAuthenticated == false) {
throw new IOException("认证失败");
}
Session sess = null;
for (int i = 0; i < cmd.length; i++) {
sess = conn.openSession();
sess.execCommand(cmd[i]);
InputStream stdout = new StreamGobbler(sess.getStdout());
//字符流
BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
while (true) {
String line = br.readLine();
if (line == null)
break;
logger.info(line);
}
stdout.close();
sess.close();
}
// logger.info("ExitCode: over");
//关闭连接
conn.close();
} catch (IOException e) {
logger.error("Command execution error");
e.printStackTrace();
}