JAVA:FTPClient报错 org.apache.commons.net.MalformedServerReplyException: Could not parse response code

报错信息如下:

Exception in thread "main" org.apache.commons.net.MalformedServerReplyException: Could not parse response code. Server Reply: SSH-2.0-OpenSSH_8.0 at org.apache.commons.net.ftp.FTP.getReply(FTP.java:344) at org.apache.commons.net.ftp.FTP.getReply(FTP.java:300) at org.apache.commons.net.ftp.FTP.connectAction(FTP.java:438) at org.apache.commons.net.ftp.FTPClient.connectAction(FTPClient.java:962) at org.apache.commons.net.ftp.FTPClient.connectAction(FTPClient.java:950) at org.apache.commons.net.SocketClient._connect(SocketClient.java:244) at org.apache.commons.net.SocketClient.connect(SocketClient.java:202) at com.lyk.myproject01.controller.Tesn.main(Tesn.java:58)

报错代码demo:

FTPClient ftpClient = new FTPClient();
ftpClient.connect("服务器ip", 22);
ftpClient.login("用户", "密码");
int reply = ftpClient.getReply();
if (!FTPReply.isPositiveCompletion(reply)) {
    ftpClient.disconnect();
}
ftpClient.setControlEncoding("GBK");
InputStream inputStream = ftpClient.retrieveFileStream("/home/test/abc.txt");
byte[] bytes = new byte[10];
OutputStream outputStream = new FileOutputStream("D:\\2temp\\home\\data\\abc.txt");
int len;
while ((len = inputStream.read(bytes)) != -1){
    outputStream.write(bytes, 0, len);
}
outputStream.close();
inputStream.close();

报错原因:服务器未开启FTP服务(未安装FTP软件)

解决方法:

1 、不改代码,依旧通过FTPClient 方式连接。此方式需服务器开启FTP服务(安装FTP软件)参考文档 linux下如何启动ftp服务,如何在linux下开启FTP服务_靖dede的博客-CSDN博客

2、换种连接方式,通过ChannelSftp 方式连接。参考文档 https://www.jianshu.com/p/65cd4f15f69c

代码实现:

添加maven依赖


      com.jcraft
      jsch
      0.1.49
Session session = null;
JSch jSch = new JSch();
session = jSch.getSession("用户名","服务器ip");
session.setPassword("密码");
Properties sshConfig = new Properties();
sshConfig.put("StrictHostKeyChecking", "no");
session.setConfig(sshConfig);
session.connect();
ChannelSftp channelSftp = (ChannelSftp)session.openChannel("sftp");
channelSftp.connect();
channelSftp.get("/home/test/abc.txt","D:\\2temp\\home\\data\\");
if (null != session){
    channelSftp.disconnect();
    session.disconnect();
}

你可能感兴趣的:(java)