天天看点

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

}

}

}

}