Java实现SSH2工具类以及创建SFTP用户
SSH2工具类
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.Channel;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
public class JSchUtils {
private Session session;
private String username;
private String password;
private String host;
private int port;
public JSchUtils(String username, String password, String host ,int port ) {
this.username = username;
this.password = password;
this.host = host;
this.port = port;
}
public void connect() throws JSchException {
JSch jsch = new JSch();
session = jsch.getSession(username, host, port);
session.setPassword(password);
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
}
public void disconnect() {
if (session != null && session.isConnected()) {
session.disconnect();
}
}
public String execCmd(String command) throws JSchException, IOException {
final StringBuilder stringBuilder = new StringBuilder(256);
BufferedReader reader = null;
Channel channel = null;
channel = session.openChannel("exec");
((ChannelExec) channel).setCommand(command);
channel.setInputStream(null);
((ChannelExec) channel).setErrStream(null);
channel.connect();
InputStream in = channel.getInputStream();
reader = new BufferedReader(new InputStreamReader(in, Charset.forName(String.valueOf(StandardCharsets.UTF_8))));
String buf;
while ((buf = reader.readLine()) != null) {
stringBuilder.append(buf);
stringBuilder.append(";");
}
channel.disconnect();
return stringBuilder.toString();
}
}
创建SFTP用户
useradd -d homePath -m -g groupName -s /bin/false username
echo "password"|passwd --stdin username