用纯java操作sftp出现Auth fail 的问题

coura棘 2015-08-17 05:29:05
因为现在一个项目要用到纯java实现sftp操作,运行代码总是出现错误 com.jcraft.jsch.JSchException: Auth fail 防火墙已关闭,用户名密码已检查n遍。本机在Cygwin下命令行和filezilla客户端都可以实现sftp传输文件到服务器,想用纯java实现就出现问题。求大神。。。。
代码如下,很简单的连接

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();
}

}
...全文
6431 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
尼古拉斯y 2017-06-08
  • 打赏
  • 举报
回复
同样异常 找了各种原因 最后发现 是防火墙的原因
coura棘 2015-08-17
  • 打赏
  • 举报
回复
引用 1 楼 gukuitian 的回复:
这应该是密码错了. sshSession.setPassword("password"); password就是你的密码?
果然是密码的问题!~多了个引号 我的主函数里面创建实例的时候通过构造函数里面已经传密码进来了 应该是变量 我加了引号就变成字符串了 想死的心都有!~谢谢哥们 连接成功了
gukuitian 2015-08-17
  • 打赏
  • 举报
回复
这应该是密码错了. sshSession.setPassword("password"); password就是你的密码?

50,523

社区成员

发帖
与我相关
我的任务
社区描述
Java相关技术讨论
javaspring bootspring cloud 技术论坛(原bbs)
社区管理员
  • Java相关社区
  • 小虚竹
  • 谙忆
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧