SSH工具类
引入依赖
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.3.2</version>
</dependency>
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.55</version>
</dependency>
工具类代码
import com.jcraft.jsch.*;
import org.apache.commons.io.IOUtils;
import org.junit.Test;
import java.io.*;
import java.util.Properties;
public class SSHUtils {
public static String exec(String host, Integer port, String username, String password, String command) throws JSchException, IOException {
JSch jSch = new JSch();
Session session = jSch.getSession(username, host, port);
session.setPassword(password);
session.setConfig("StrictHostKeyChecking", "no");
session.connect(30000);
ChannelExec channel = (ChannelExec) session.openChannel("exec");
channel.setCommand(command);
channel.setErrStream(System.err);
InputStream inputStream = channel.getInputStream();
channel.connect(3000);
String result = IOUtils.toString(inputStream);
channel.disconnect();
return result;
}
public static void ftp(String host, Integer port, String username, String password, File file, String remotePath) throws JSchException, IOException, SftpException {
JSch jsch = new JSch();
Session session = jsch.getSession(username, host, port);
session.setPassword(password);
Properties sshConfig = new Properties();
sshConfig.put("StrictHostKeyChecking", "no");
session.setConfig(sshConfig);
session.connect(30000);
ChannelSftp channel = (ChannelSftp) session.openChannel("sftp");
channel.connect(3000);
try {
channel.mkdir(remotePath);
} catch (Exception e) {
System.out.println("创建目录失败或目录已存在");
e.printStackTrace();
}
channel.cd(remotePath);
channel.put(new FileInputStream(file), file.getName());
channel.disconnect();
session.disconnect();
}
public static String shell(String host, Integer port, String username, String password, String... command) throws JSchException, IOException {
JSch jSch = new JSch();
Session session = jSch.getSession(username, host, port);
session.setPassword(password);
session.setConfig("StrictHostKeyChecking", "no");
session.connect(30000);
ChannelShell channelShell = (ChannelShell) session.openChannel("shell");
InputStream inputStream = channelShell.getInputStream();
channelShell.setPty(true);
channelShell.connect(30000);
OutputStream outputStream = channelShell.getOutputStream();
PrintWriter printWriter = new PrintWriter(outputStream);
for (String cmd : command) {
printWriter.println(cmd);
}
//printWriter.println("exit");
printWriter.flush();
String result = IOUtils.toString(inputStream);
outputStream.close();
inputStream.close();
channelShell.disconnect();
session.disconnect();
return result;
}
}