导入相关依赖
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.55</version>
</dependency>
代码实现
import com.jcraft.jsch.*;
import java.io.*;
import java.nio.file.Files;
public class TestSSHDemo {
private static final String REMOTE_HOST = "192.168.5.133";
private static final int REMOTE_PORT = 22;
private static final String USERNAME = "root";
private static final String PASSWORD = "123456";
public static void uploadFile(String remotePath, String localFilePath) {
JSch jsch = null;
Session session = null;
Channel channel = null;
ChannelSftp sftpChannel = null;
FileInputStream fileInputStream = null;
try {
jsch = new JSch();
session = jsch.getSession(USERNAME, REMOTE_HOST, REMOTE_PORT);
session.setPassword(PASSWORD);
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
channel = session.openChannel("sftp");
channel.connect();
sftpChannel = (ChannelSftp) channel;
File localFile = new File(localFilePath);
fileInputStream = new FileInputStream(localFile);
sftpChannel.put(fileInputStream, remotePath + "/" + localFile.getName());
System.out.println("文件上传成功");
} catch (IOException | SftpException | JSchException e) {
e.printStackTrace();
} finally {
if (fileInputStream != null) {
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (sftpChannel != null) {
sftpChannel.exit();
}
if (channel != null) {
channel.disconnect();
}
if (session != null) {
session.disconnect();
}
}
}
public static void uploadFileShowUploadProgress(String remotePath, String localFilePath) {
JSch jsch = null;
Session session = null;
Channel channel = null;
ChannelSftp sftpChannel = null;
FileInputStream fileInputStream = null;
try {
jsch = new JSch();
session = jsch.getSession(USERNAME, REMOTE_HOST, REMOTE_PORT);
session.setPassword(PASSWORD);
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
channel = session.openChannel("sftp");
channel.connect();
sftpChannel = (ChannelSftp) channel;
File localFile = new File(localFilePath);
long fileSize = localFile.length();
fileInputStream = new FileInputStream(localFile);
showUploadProgress(sftpChannel, localFile, remotePath, fileSize);
System.out.println("文件上传成功");
} catch (IOException | SftpException | JSchException e) {
e.printStackTrace();
} finally {
if (fileInputStream != null) {
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (sftpChannel != null) {
sftpChannel.exit();
}
if (channel != null) {
channel.disconnect();
}
if (session != null) {
session.disconnect();
}
}
}
private static void showUploadProgress(ChannelSftp sftpChannel, File localFile, String remotePath, long fileSize) throws IOException, SftpException {
int barLength = 50;
final long[] bytesTransferred = {0};
long lastBytesTransferred = 0;
long startTime = System.currentTimeMillis();
sftpChannel.put(Files.newInputStream(localFile.toPath()), remotePath + "/" + localFile.getName(), new SftpProgressMonitor() {
@Override
public void init(int i, String s, String s1, long l) {
}
@Override
public boolean count(long count) {
bytesTransferred[0] += count;
double progress = (double) bytesTransferred[0] / fileSize;
long elapsedTime = System.currentTimeMillis() - startTime;
updateProgressBar(progress, barLength, elapsedTime);
return true;
}
@Override
public void end() {
}
private void updateProgressBar(double progress, int barLength, long elapsedTime) {
int pos = (int) (progress * barLength);
System.out.print("\r");
System.out.print("[");
for (int i = 0; i < barLength; i++) {
if (i < pos) System.out.print('=');
else if (i == pos) System.out.print('>');
else System.out.print(' ');
}
System.out.print("] " + ((int) (progress * 100)) + "% " + formatTime(elapsedTime));
}
private String formatTime(long timeMillis) {
long minutes = timeMillis / (1000 * 60);
long seconds = (timeMillis % (1000 * 60)) / 1000;
return String.format("%02d:%02d", minutes, seconds);
}
}, ChannelSftp.OVERWRITE);
}
public static void executeCommand(String command) {
JSch jsch = null;
Session session = null;
Channel channel = null;
try {
jsch = new JSch();
session = jsch.getSession(USERNAME, REMOTE_HOST, REMOTE_PORT);
session.setPassword(PASSWORD);
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
channel = session.openChannel("exec");
((ChannelExec) channel).setCommand(command);
InputStream in = channel.getInputStream();
channel.connect();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (channel != null) {
channel.disconnect();
}
if (session != null) {
session.disconnect();
}
}
}
public static void main(String[] args) {
String command = "cd /root/test && ls -ltr";
executeCommand(command);
}
}