java 可以利用jsch包实现远程执行linux shell 命令,分为交互命令和非交互式命令 代码如下:
package jsch_example;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.ChannelShell;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import org.apache.commons.lang3.StringUtils;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
public class JSchSSHUtil {
/**
* JSch,执行多条语句<
* pty 交互式命令
* @param host
* @param port
* @param username
* @param password
* @param commands
*/
public static void ssh2Shell(String host, int port, String username, String password, String[] commands) {
JSch jsch = new JSch();
Session session = null;
ChannelShell channelShell = null;
try {
session = jsch.getSession(username, host, port);
Properties sshConfig = new Properties();
sshConfig.put("StrictHostKeyChecking", "no");
session.setConfig(sshConfig);
session.setPassword(password);
session.connect();
channelShell = (ChannelShell) session.openChannel("shell");
channelShell.setPty(true);
channelShell.connect();<