50,682
社区成员
发帖
与我相关
我的任务
分享
import java.util.Properties;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpATTRS;
import com.jcraft.jsch.SftpException;
import com.jcraft.jsch.ChannelSftp.LsEntry;
public class SFTPTest {
private String host;
private String username;
private String password;
private int port = 22;
private ChannelSftp sftp = null;
private Session sshSession = null;
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public ChannelSftp getSftp() {
return sftp;
}
public void setSftp(ChannelSftp sftp) {
this.sftp = sftp;
}
public Session getSshSession() {
return sshSession;
}
public void setSshSession(Session sshSession) {
this.sshSession = sshSession;
}
public SFTPTest() {
}
public SFTPTest(String host, String username, String password, int port) {
this.host = host;
this.username = username;
this.password = password;
this.port = port;
}
/**
* connect server via sftp
*/
public void connect() {
try {
JSch jsch = new JSch();
sshSession = jsch.getSession(username, host, port);
System.out.println("Session created.");
sshSession.setPassword("password");
Properties sshConfig = new Properties();
sshConfig.put("StrictHostKeyChecking", "no");
sshSession.setConfig(sshConfig);
sshSession.connect();
System.out.println("Session connected.");
System.out.println("Opening Channel.");
ChannelSftp channelSftp = (ChannelSftp)sshSession.openChannel("sftp");
channelSftp.connect();
System.out.println("Connected to " + host + ".");
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
SFTPTest sftp = new SFTPTest("localhost", "Administrator", "ynashk",22);
sftp.connect();
}
}