Skip to content

Instantly share code, notes, and snippets.

@goyuninfo
Last active September 11, 2018 23:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save goyuninfo/d01822e2f37c9a5480a4 to your computer and use it in GitHub Desktop.
Save goyuninfo/d01822e2f37c9a5480a4 to your computer and use it in GitHub Desktop.
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
/**
*
* @author it.i88.ca
*/
public class NewClass {
public static void main(String[] args) {
String SFTPHOST = "192.168.3.70";
int SFTPPORT = 22;
String SFTPUSER = "user";
String SFTPPASS = "passwd";
String SFTPWORKINGDIR = "test";
Session session = null;
Channel channel = null;
ChannelSftp channelSftp = null;
try {
JSch jsch = new JSch();
session = jsch.getSession(SFTPUSER, SFTPHOST, SFTPPORT);
session.setPassword(SFTPPASS);
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
int timeOutMilliseconds = 60000;
session.connect(timeOutMilliseconds);
channel = session.openChannel("sftp");
channel.connect();
channelSftp = (ChannelSftp) channel;
channelSftp.cd(SFTPWORKINGDIR);
byte[] buffer = new byte[1024];
BufferedInputStream bis = new BufferedInputStream(channelSftp.get("test.txt"));
File newFile = new File("test.i88.ca.txt");
OutputStream os = new FileOutputStream(newFile);
BufferedOutputStream bos = new BufferedOutputStream(os);
int readCount;
while ((readCount = bis.read(buffer)) > 0) {
bos.write(buffer, 0, readCount);
}
bis.close();
bos.close();
channel.disconnect();
session.disconnect();
//return;
} catch (JSchException | SftpException | IOException ex) {
ex.printStackTrace();
}
}
}
@douglasrezende
Copy link

in windows worked very well, but in linux not worked

@douglasrezende
Copy link

var sftp = new JSch();
sftpSession = sftp.getSession(username, host, port)
sftpSession.setPassword(password)
sftpSession.setConfig("StrictHostKeyChecking", "no")
sftpSession.setConfig("PreferredAuthentications", "password")
sftpSession.connect()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment