sftp连接问题

本文介绍了一种使用j2ssh包实现SFTP文件上传的方法。通过具体的代码示例,展示了如何建立SFTP连接并上传文件到服务器。为避免在连接过程中出现主机密钥验证提示,文章还提供了解决方案。

项目中需要用到sftp上传文件到服务器。使用了j2ssh包。

 

在开发过程中没有出现任何问题,连接步骤:

SshClient ssh = null;
ConfigurationLoader.initialize(false);
// Make a client connection
ssh = new SshClient();

// Connect to the host
ssh.connect(host,port);
KBIAuthenticationClient kbi = new KBIAuthenticationClient();
kbi.setUsername(username);

kbi.setKBIRequestHandler(new KBIRequestHandler(){
  public void showPrompts(String arg0, String arg1,KBIPrompt[] prompts)
{
    if(prompts != null)
    {
      prompts[0].setResponse(password);
    }
  }
});

// Try the authentication
int iresult = ssh.authenticate(kbi);
// Evaluate the result
if (iresult == AuthenticationProtocolState.COMPLETE) {
  // The connection is authenticated we can now do some real work!
  sftp = ssh.openSftpClient();
  attrs = sftp.stat(dir);
}
else
{
  ssh = null;
}
if(sftp != null && !sftp.isClosed())
{
  try {
    sftp.quit();
  } catch (IOException e) {
    Tracer.error("sFTP connect quit failed.Exception:" + e.toString());
  }
}
if(ssh != null && ssh.isConnected())
{
  ssh.disconnect();
}

 

后来在测试机器上运行发现,每次连接都会向服务器询问:Do you want to allow this host key? [Yes|No|Always]:

经过查看代码发现,在连接时,加入HostKeyVerification,可使连接默认选择,不再需要询问用户。

ssh.connect(host,port,new HostKeyVerification(){
/**
* 不用验证Host key,直接连接 
 */
  public boolean verifyHost(String arg0, SshPublicKey arg1) throws TransportProtocolException {
    return true;
  }
});

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值