sftp连接问题
程序员文章站
2022-03-19 22:21:09
...
项目中需要用到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;
}
});