天天看點

java linux指令遠端執行_【Java】Java執行遠端機器上Linux指令

Java使用ethz通過ssh2執行遠端機器Linux上指令,

封裝定義Linux機器的環境資訊

package com.tom;

import java.io.File;

public class Env {

private String hostaddr; //Linux機器的IP位址

private Integer port; //SSH通路端口,預設22

private String username; //通過使用者名密碼通路Linux機器時的使用者名

private File pemFile; //通過SSH Key認證時,pemFile包含的是SSH Public Key内容

private String passwd;//通過使用者名密碼通路Linux機器時的密碼

private Authentication authentication;

public Env(String hostaddr, Integer port, String username, File pemFile, String passwd, Authentication authentication) {

this.hostaddr = hostaddr;

this.port = port;

this.username = username;

this.pemFile = pemFile;

this.passwd = passwd;

this.authentication = authentication;

}

public String getHostaddr() {

return hostaddr;

}

public Integer getPort() {

return port;

}

public String getUsername() {

return username;

}

public File getPemFile() {

return pemFile;

}

public String getPasswd() {

return passwd;

}

public Authentication getAuthentication() {

return authentication;

}

}

登入Linxu的認證方式

public enum Authentication {

USER_PASSWORD("user-password"), SSH_KEY("ssh-key");//使用者名密碼方式,ssh-key方式

private String name;

Authentication(String name) {

this.name = name;

}

@Override

public String toString() {

return this.name;

}

}

package com.tom;

import ch.ethz.ssh2.Connection;

import ch.ethz.ssh2.Session;

import java.io.*;

public class CommandExecutor {

private static final String LINE_SEPARATOR = System.getProperty("line.separator");

//Env封裝了遠端機器的通路資訊

//cmd是要執行的shell指令

public static String exec(Env v, String cmd) throws IOException {

Connection conn;

if (v.getPort() != null) {

conn = new Connection(v.getHostaddr(), v.getPort());

} else {

conn = new Connection(v.getHostaddr());

}

//使用Key認證

//PemFile是ssh public key檔案

boolean b = conn.authenticateWithPublicKey(v.getUsername(), v.getPemFile(), v.getPasswd());

if (!b) {

throw new IllegalArgumentException();

}

Session session = null;//Java程序與Linux建立會話

BufferedReader br = null;

try {

session = conn.openSession();

session.execCommand(cmd); //執行指令

InputStream stdIn = session.getStdout();//獲得指令執行的标準輸出

InputStream errIn = session.getStderr(); //獲得指令執行的标準錯誤輸出

StringBuilder sb = new StringBuilder("Standard output:").append(LINE_SEPARATOR);

br = new BufferedReader(new InputStreamReader(stdIn, "UTF-8"));

String str = null;

while ((str = br.readLine()) != null) {

sb.append(str).append(LINE_SEPARATOR);

}

br.close();

br = new BufferedReader(new InputStreamReader(errIn, "UTF-8"));

sb.append("Error output:").append(LINE_SEPARATOR);

while ((str = br.readLine()) != null) {

sb.append(str).append(LINE_SEPARATOR);

}

return sb.toString();

} finally {

closeReaders(br);

if (session != null) {

session.close();

}

}

}

private static void closeReaders(Reader... readers) {

if (readers == null) {

return;

}

for (Reader reader : readers) {

try {

reader.close();

} catch (IOException e) {

//Ignore

}

}

}

}