本文参与「新人创作礼」活动,一起开启掘金创作之路。
1、引入依赖
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.55</version>
</dependency>
2、操作工具类
package com.dwk.sftp;
import com.jcraft.jsch.*;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
/**
* 连接远程服务器工具类
*/
@Slf4j
public class SftpUtil {
private static final Logger log = LoggerFactory.getLogger(SftpUtil.class);
/**消息通道*/
private static ChannelSftp sftp;
/**连接客户端*/
private static JSch jSch;
/**会话*/
private static Session session;
/**ip*/
private static String host;
/**端口*/
private static int port;
/**用户名*/
private static String username;
/**密码*/
private static String password;
public static void setAttr(String host, int port, String username, String password){
SftpUtil.host = host;
SftpUtil.port = port;
SftpUtil.username = username;
SftpUtil.password = password;
jSch = new JSch();
}
/**
* 连接指定服务器
*/
public static void login(){
try {
session = jSch.getSession(username,host,port);
session.setPassword(password);
//设置连接方式,用密码连接
session.setConfig("PreferredAuthentications","password");
session.setConfig("StrictHostKeyChecking","no");
session.connect();
//建立sftp通信通道
Channel channel = session.openChannel("sftp");
channel.connect();
sftp = (ChannelSftp) channel;
log.info("服务器:"+host+"连接成功");
} catch (JSchException e) {
log.info("服务器:"+host+"连接失败");
e.printStackTrace();
}
}
/**
* 关闭连接
*/
public static void shutdown(){
//关闭通信通道
if (sftp != null){
if(sftp.isConnected()){
sftp.disconnect();
log.info("sftp is close already");
}
}
//关闭会话
if (session != null){
if(session.isConnected()){
session.disconnect();
log.info("session is close already");
}
}
}
/**
* 执行命令
*/
public static String runShell(String cmd){
String returnStr = null;
try {
ChannelExec channelExec = (ChannelExec) session.openChannel("exec");
channelExec.setCommand(cmd);
channelExec.connect();
StringBuilder resultLog = new StringBuilder("");
BufferedReader resultReader = new BufferedReader(new InputStreamReader(channelExec.getInputStream()));
String resultLine = null;
while ((resultLine = resultReader.readLine()) != null){
resultLog.append(resultLine).append("\n");
}
returnStr = resultLog.toString();
StringBuilder errLog = new StringBuilder("");
BufferedReader errorReader = new BufferedReader(new InputStreamReader(channelExec.getErrStream()));
String errorLine = null;
while ((errorLine = errorReader.readLine()) != null){
errLog.append(errorLine).append("\n");
}
} catch (JSchException e) {
log.error("shell命令执行错误");
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
return returnStr;
}
/**
* 创建文件
*/
public static boolean createFile(String path, String fileName, InputStream inputStream){
long start = System.currentTimeMillis();
boolean returnBoolean = true;
try {
if (sftp.ls(path) == null){
sftp.mkdir(path);
}
if (sftp.ls(path) != null){
sftp.cd(path);
}
sftp.put(inputStream,fileName);
} catch (SftpException e) {
log.info("文件保存失败");
e.printStackTrace();
returnBoolean = false;
}
long end = System.currentTimeMillis();
log.info("文件"+fileName+"保存成功,耗时"+(end-start));
return returnBoolean;
}
/**
* 删除文件
*/
public static void deleteFile(){
try {
sftp.rm("");
} catch (SftpException e) {
e.printStackTrace();
}
}
}
3、测试类
package com.dwk.sftp;
import java.util.Scanner;
public class SftpTest {
private static final String HOST = "请输入ip:";
private static final String PORT = "请输入端口:";
private static final String USERNAME = "请输入用户名:";
private static final String PASSWORD = "请输入密码:";
private static final String LOADING = "正在连接服务器...";
private static final String SHUTDOWN = "=======输入shutdown关闭连接=====";
public String scan(){
System.out.format("\33[36;4m> ");
return new Scanner(System.in).next();
}
public void print(String tip){
System.out.format("\33[33;4m" + tip + "%n");
}
public void test(){
print(HOST);
String host = scan();
print(PORT);
int port = Integer.valueOf(scan());
print(USERNAME);
String username = scan();
print(PASSWORD);
String password = scan();
print(LOADING);
SftpUtil.setAttr(host,port,username,password);
SftpUtil.login();
print(SHUTDOWN);
while (true) {
String command = scan();
if (("shutdown").equals(command)) {
SftpUtil.shutdown();
} else {
//执行shell命令
String result = SftpUtil.runShell(command);
System.out.format("\33[31;4m" + result + "%n");
}
}
}
public static void main(String[] args) {
SftpTest sftpTest = new SftpTest();
sftpTest.test();
}
}
4、运行结果: