/** * @return 判断是否登入成功 * */ public boolean ftpLogin() { boolean isLogin = false; FTPClientConfig ftpClientConfig = new FTPClientConfig(); ftpClientConfig.setServerTimeZoneId(TimeZone.getDefault().getID()); this.ftpClient.setControlEncoding("GBK"); this.ftpClient.configure(ftpClientConfig); try { if (this.intPort > 0) { this.ftpClient.connect(this.strIp, this.intPort); } else { this.ftpClient.connect(this.strIp); } // FTP服务器连接回答 int reply = this.ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { this.ftpClient.disconnect(); System.out.println("登录FTP服务失败!"); return isLogin; } this.ftpClient.login(this.user, this.password); // 设置传输协议 this.ftpClient.enterLocalPassiveMode(); this.ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); System.out.println("恭喜" + this.user + "成功登陆FTP服务器"); //logger.info("恭喜" + this.user + "成功登陆FTP服务器"); isLogin = true; } catch (Exception e) { e.printStackTrace(); System.out.println(this.user + "登录FTP服务失败!" + e.getMessage()); //logger.error(this.user + "登录FTP服务失败!" + e.getMessage()); } this.ftpClient.setBufferSize(1024 * 2); this.ftpClient.setDataTimeout(30 * 1000); return isLogin; }
/** * Login to the FTP Server */ public boolean login() { FTPClientConfig fcc = new FTPClientConfig(); fcc.setServerTimeZoneId(TimeZone.getDefault().getID()); ftpClient.setControlEncoding(encoding); ftpClient.configure(fcc); try { if (port > 0) { ftpClient.connect(hostname, port); } else { ftpClient.connect(hostname); } // check reply code int code = ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(code)) { ftpClient.disconnect(); logger.error("Login FTP Server is failure!"); return false; } if(ftpClient.login(username, password)){ // setting this.ftpClient.enterLocalPassiveMode(); this.ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); this.ftpClient.setBufferSize(BUFFER_SIZE); this.ftpClient.setDataTimeout(TIMEOUT); // logger.info(username + " successfully logined to the FTP server."); return true; }else{ throw new Exception("Please check your username and password."); } } catch (Exception e) { logger.error(username + " failed to login to the FTP server", e); } return false; }
public boolean connect(String hostname, int port, String username, String password) throws IOException { // ���ӵ�FTP������ ftpClient.connect(hostname, port); // �������Ĭ�϶˿ڣ�����ʹ��ftp.connect(url)�ķ�ʽֱ������FTP������ if (FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) { if (ftpClient.login(username, password)) { return true; } } disconnect(); return false; }
@Override public FSDataInputStream open(Path file, int bufferSize) throws IOException { FTPClient client = connect(); Path workDir = new Path(client.printWorkingDirectory()); Path absolute = makeAbsolute(workDir, file); FileStatus fileStat = getFileStatus(client, absolute); if (fileStat.isDirectory()) { disconnect(client); throw new FileNotFoundException("Path " + file + " is a directory."); } client.allocate(bufferSize); Path parent = absolute.getParent(); // Change to parent directory on the // server. Only then can we read the // file // on the server by opening up an InputStream. As a side effect the working // directory on the server is changed to the parent directory of the file. // The FTP client connection is closed when close() is called on the // FSDataInputStream. client.changeWorkingDirectory(parent.toUri().getPath()); InputStream is = client.retrieveFileStream(file.getName()); FSDataInputStream fis = new FSDataInputStream(new FTPInputStream(is, client, statistics)); if (!FTPReply.isPositivePreliminary(client.getReplyCode())) { // The ftpClient is an inconsistent state. Must close the stream // which in turn will logout and disconnect from FTP server fis.close(); throw new IOException("Unable to open file: " + file + ", Aborting"); } return fis; }
/** * Simple test that connects to the inbuilt ftp server and logs on * * @throws Exception */ public void testFTPConnect() throws Exception { logger.debug("Start testFTPConnect"); FTPClient ftp = connectClient(); try { int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { fail("FTP server refused connection."); } boolean login = ftp.login(USER_ADMIN, PASSWORD_ADMIN); assertTrue("admin login not successful", login); } finally { ftp.disconnect(); } }
@Override public boolean connectClient() throws IOException { boolean isLoggedIn = true; client.setAutodetectUTF8(true); client.setControlEncoding("UTF-8"); client.connect(host, port); client.setFileType(FTP.BINARY_FILE_TYPE); client.enterLocalPassiveMode(); client.login(username, password); int reply = client.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { client.disconnect(); LogUtils.LOGD(TAG, "Negative reply form FTP server, aborting, id was {}:"+ reply); //throw new IOException("failed to connect to FTP server"); isLoggedIn = false; } return isLoggedIn; }
@Override public PathAttributes find(final Path file) throws BackgroundException { if(file.isRoot()) { return PathAttributes.EMPTY; } try { if(session.getClient().hasFeature(FTPCmd.MLST.getCommand())) { if(!FTPReply.isPositiveCompletion(session.getClient().sendCommand(FTPCmd.MLST, file.getAbsolute()))) { throw new FTPException(session.getClient().getReplyCode(), session.getClient().getReplyString()); } final FTPDataResponseReader reader = new FTPMlsdListResponseReader(); final AttributedList<Path> attributes = reader.read(file.getParent(), Arrays.asList(session.getClient().getReplyStrings()), new DisabledListProgressListener()); if(attributes.contains(file)) { return attributes.get(attributes.indexOf(file)).attributes(); } } throw new InteroperabilityException("No support for MLST in reply to FEAT"); } catch(IOException e) { throw new FTPExceptionMappingService().map("Failure to read attributes of {0}", e, file); } }
private BackgroundException handle(final FTPException e, final StringBuilder buffer) { final int status = e.getCode(); switch(status) { case FTPReply.INSUFFICIENT_STORAGE: case FTPReply.STORAGE_ALLOCATION_EXCEEDED: return new QuotaException(buffer.toString(), e); case FTPReply.NOT_LOGGED_IN: return new LoginFailureException(buffer.toString(), e); case FTPReply.FAILED_SECURITY_CHECK: case FTPReply.DENIED_FOR_POLICY_REASONS: case FTPReply.NEED_ACCOUNT: case FTPReply.NEED_ACCOUNT_FOR_STORING_FILES: case FTPReply.FILE_NAME_NOT_ALLOWED: case FTPReply.ACTION_ABORTED: return new AccessDeniedException(buffer.toString(), e); case FTPReply.UNAVAILABLE_RESOURCE: case FTPReply.FILE_UNAVAILABLE: // Requested action not taken. File unavailable (e.g., file not found, no access) return new NotfoundException(buffer.toString(), e); case FTPReply.SERVICE_NOT_AVAILABLE: return new ConnectionRefusedException(buffer.toString(), e); } return new InteroperabilityException(buffer.toString(), e); }
public void sendCommands(final List<String> commands, final FlowFile flowFile) throws IOException { if (commands.isEmpty()) { return; } final FTPClient client = getClient(flowFile); for (String cmd : commands) { if (!cmd.isEmpty()) { int result; result = client.sendCommand(cmd); logger.debug(this + " sent command to the FTP server: " + cmd + " for " + flowFile); if (FTPReply.isNegativePermanent(result) || FTPReply.isNegativeTransient(result)) { throw new IOException(this + " negative reply back from FTP server cmd: " + cmd + " reply:" + result + ": " + client.getReplyString() + " for " + flowFile); } } } }
private FTPClient initFtpClient(String remoteDir) throws IOException { FTPClient ftp = new FTPClient(); // 设置连接超时时间 ftp.setConnectTimeout(CONNECT_TIMEOUT); // 设置传输文件名编码方式 ftp.setControlEncoding(CONTROL_ENCODING); ftp.connect(host, ftpPort); int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { logger.debug("无法连接FTP"); return null; } boolean loginRet = ftp.login(ftpUsername, ftpPassword); if (!loginRet) { logger.debug("FTP登录失败"); return null; } // 进入被动模式 ftp.enterLocalPassiveMode(); boolean changeDirResult = MKDAndCWD(ftp, remoteDir); if (!changeDirResult) { logger.debug("创建/切换文件夹失败"); return null; } // 传输二进制文件 ftp.setFileType(FTP.BINARY_FILE_TYPE); return ftp; }
/** * Connect to the FTP server using configuration parameters * * * @return An FTPClient instance * @throws IOException */ private FTPClient connect() throws IOException { FTPClient client = null; Configuration conf = getConf(); String host = conf.get(FS_FTP_HOST); int port = conf.getInt(FS_FTP_HOST_PORT, FTP.DEFAULT_PORT); String user = conf.get(FS_FTP_USER_PREFIX + host); String password = conf.get(FS_FTP_PASSWORD_PREFIX + host); client = new FTPClient(); client.connect(host, port); int reply = client.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { throw NetUtils.wrapException(host, port, NetUtils.UNKNOWN_HOST, 0, new ConnectException("Server response " + reply)); } else if (client.login(user, password)) { client.setFileTransferMode(FTP.BLOCK_TRANSFER_MODE); client.setFileType(FTP.BINARY_FILE_TYPE); client.setBufferSize(DEFAULT_BUFFER_SIZE); } else { throw new IOException("Login failed on server - " + host + ", port - " + port + " as user '" + user + "'"); } return client; }
@Override public void connect( String server, int port ) throws IOException { if( ftp.isConnected() ) { throw new IllegalStateException( "Already connected" ); } debug( () -> "Connecting to " + server + " on " + (port > 0 ? port : ftp.getDefaultPort()) ); if( port > 0 ) { ftp.connect( server, port ); } else { ftp.connect( server ); } debug( () -> "Connected to " + server + " on " + (port > 0 ? port : ftp.getDefaultPort()) ); // After connection attempt, you should check the reply code to verifysuccess. if( !FTPReply.isPositiveCompletion( ftp.getReplyCode() ) ) { debug( () -> "Connection refused to " + server + " on " + (port > 0 ? port : ftp.getDefaultPort()) ); throw new ConnectException( "Failed to connect to " + server ); } }
/** * 连接FTP服务器 * @param host FTP服务器地址 * @param port FTP服务器端口号 * @param username 用户名 * @param password 密码 * @return */ public static boolean connect(String host, int port, String username, String password) { try{ ftpClient = new FTPClient(); ftpClient.connect(host, port); // 登录 ftpClient.login(username, password); ftpClient.setBufferSize(FTP_SERVER_BUFFER_SIZE_VALUE); ftpClient.setControlEncoding(FTP_CLIENT_ENCODING); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); ftpClient.setDataTimeout(FTP_SERVER_DATA_TIME_OUT); ftpClient.setSoTimeout(FTP_SERVER_SO_TIME_OUT); // 检验是否连接成功 int reply = ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { LOGGER.error("连接FTP服务器失败,响应码:"+reply); disConnectionServer(); return false; } }catch(IOException e){ LOGGER.error("连接FTP服务器失败",e); return false; } return true; }
public boolean exists(String filename) throws FileSystemException { // we have to be connected if (ftp == null) { throw new FileSystemException("Not yet connected to FTP server"); } try { // check if the file already exists FTPFile[] files = ftp.listFiles(filename); // did this command succeed? if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) { throw new FileSystemException("FTP server failed to get file listing (reply=" + ftp.getReplyString() + ")"); } if (files != null && files.length > 0) { // this file already exists return true; } else { return false; } } catch (IOException e) { throw new FileSystemException("Underlying IO exception with FTP server while checking if file exists", e); } }
/** * Connects the client to the FTP Server if is not already connected. */ public void connectToFtpServer() { try { ftpClient.connect(ftpServerName, port); ftpClient.login(username, password); ftpClient.enterLocalPassiveMode(); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); ftpClient.changeWorkingDirectory(ftpHomeDirectory); if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) { throw new IOException("FTP server refused connection."); } LOGGER.info(String.format("Connected to an FTP Server with IP (%s:%s).", ftpServerName, port)); } catch (IOException e) { LOGGER.error(String.format("Failed to connect to an FTP Server with IP (%s:%s).", ftpServerName, port), e); } }
private static InputStream getFTPInputStream(String ftpServerName, String checklistRemoteFilePath) throws IOException { FTPClient ftp = new FTPClient(); ftp.connect(ftpServerName); int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); throw new IOException("FTP server " + ftpServerName + " refused connection"); } if (!ftp.login(USERNAME, PASSWORD)) { ftp.logout(); throw new IOException("FTP server failed to login using username anonymous"); } ftp.setFileType(FTP.ASCII_FILE_TYPE); InputStream inputStream = ftp.retrieveFileStream(checklistRemoteFilePath); return inputStream; }
@Override public void connect() throws IOException { if( ftp.isConnected() ) { return; } debug( () -> "Connecting..." ); connect.accept( this ); // After connection attempt, you should check the reply code to verifysuccess. if( FTPReply.isPositiveCompletion( ftp.getReplyCode() ) ) { debug( () -> "Connected" ); } else { debug( () -> "Connection refused" ); throw new ConnectException( "Connection refused" ); } }
public String getSystemType() throws IOException { if(this.__systemName == null) { if(FTPReply.isPositiveCompletion(this.syst())) { this.__systemName = ((String)this._replyLines.get(this._replyLines.size() - 1)).substring(4); } else { String systDefault = System.getProperty("org.apache.commons.net.ftp.systemType.default"); if(systDefault == null) { throw new IOException("Unable to determine system type - response: " + this.getReplyString()); } this.__systemName = systDefault; } } return this.__systemName; }
public boolean connect(String hostname,int port,String username,String password) throws IOException{ ftpClient.setConnectTimeout(30*1000); ftpClient.connect(hostname, port); //ftpClient.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out))); if(FTPReply.isPositiveCompletion(ftpClient.getReplyCode())){ if(ftpClient.login(username, password)){ logger.info("login to [{}] with username[{}] password=[{}] success",hostname,username,password); ftpClient.enterLocalPassiveMode(); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); return true; } else{ logger.error("unable to login to ftp server[{}] with username[{}] password=[{}], abort!",hostname,username,password ); disconnect(); } } return false; }
private void connect() throws SocketException, IOException { //send the command.. ftpClient.connect(host, hostPort); //check reply code... int replyCode = ftpClient.getReplyCode(); boolean sucess = FTPReply.isPositiveCompletion(replyCode); //sucess? if(!sucess){ ftpClient.disconnect(); throw new IOException("FTP server refused connection."); } setConnected(sucess); }
public void uploadFile(String filePath, byte[] data) throws IOException { login(); OutputStream os = ftpClient.storeFileStream(filePath); int ftpUploadReplyCode = ftpClient.getReplyCode(); if(FTPReply.isNegativePermanent(ftpUploadReplyCode)) { throw new IOException("SERVER FTP:REQUEST DENIED"); } else if(FTPReply.isNegativeTransient(ftpUploadReplyCode)){ uploadFile(filePath, data); } ByteArrayInputStream bais = new ByteArrayInputStream(data); IOUtils.copy(bais, os); bais.close(); os.flush(); os.close(); if(!ftpClient.completePendingCommand()) { uploadFile(filePath, data); } logout(); }
/** * Connect to the FTP server using configuration parameters * * * @return An FTPClient instance * @throws IOException */ private FTPClient connect() throws IOException { FTPClient client = null; Configuration conf = getConf(); String host = conf.get("fs.ftp.host"); int port = conf.getInt("fs.ftp.host.port", FTP.DEFAULT_PORT); String user = conf.get("fs.ftp.user." + host); String password = conf.get("fs.ftp.password." + host); client = new FTPClient(); client.connect(host, port); int reply = client.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { throw new IOException("Server - " + host + " refused connection on port - " + port); } else if (client.login(user, password)) { client.setFileTransferMode(FTP.BLOCK_TRANSFER_MODE); client.setFileType(FTP.BINARY_FILE_TYPE); client.setBufferSize(DEFAULT_BUFFER_SIZE); } else { throw new IOException("Login failed on server - " + host + ", port - " + port); } return client; }
private void connectClientAndCheckStatus() throws SocketException, IOException, FTPException { LOGGER.debug("Connecting to {}:{}", host, port); ftpClient.connect(host, port); int replyCode = ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(replyCode)) { LOGGER.debug("Connection not made."); LOGGER.debug("Response status: {}", replyCode); LOGGER.debug("Disconnecting"); ftpClient.disconnect(); LOGGER.debug("Disconnected"); throw new ClientConnectionException(String.format("The host %s on port %d returned a bad status code.", host, port)); } }
/***************************************** * * A convenience method for connecting and logging in. */ public void connectAndLogin( String host, String username, String password ) throws IOException, UnknownHostException, FTPConnectionClosedException { this.host = host; this.userName = username; log.debug("attempting to connect to " + host ); connect( host ); if ( FTPReply.isPositiveCompletion( getReplyCode() ) ) { log.debug("connect successful, logging in as " + userName ); login( userName, password ); } else { log.warn("failed to connect to " + host + ", disconnecting..."); disconnect(); return; } log.info("connected to " + host + " as user " + userName ); }
/** * Set up an FTP connection. * * @param host the FTP host * @param user the FTP user name * @param pwd the FTP password * @param debug if true, the FTP protocol commands are printed * @throws Exception thrown if the connection could not be made */ public FTPDownloader(String host, String user, String pwd, boolean debug) throws Exception { ftp = new FTPClient(); if (debug) { ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out))); } ftp.connect(host); int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); throw new Exception("Could not connect to FTP Server."); } ftp.login(user, pwd); ftp.setFileType(FTP.BINARY_FILE_TYPE); ftp.enterLocalPassiveMode(); }
public void changeAndMakeDirs(String dir){ String ftpDir = dir;//FileUtils.replaceBackSlashToSlash(dir); File dirFile = new File(ftpDir); try { if(!ftpClient.changeWorkingDirectory(ftpDir)){ if(ftpClient.getReplyCode()==550){ changeAndMakeDirs(dirFile.getParent()); } int rcode = ftpClient.mkd(dirFile.getName()); if(!FTPReply.isPositiveCompletion(rcode)){ throw new BaseException("cmd[mkd] reply code : "+rcode); } } } catch (IOException e) { throw new BaseException("create dir error: " + dir, e); } }
private FTPClient getClient() throws SocketException, IOException { FTPClient ftp = new FTPClient(); ftp.addProtocolCommandListener(new PrintCommandListener( new PrintWriter(System.out))); ftp.setDefaultPort(getPort()); ftp.connect(getIp()); int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { log.warn("FTP server refused connection: {}", getIp()); ftp.disconnect(); return null; } if (!ftp.login(getUsername(), getPassword())) { log.warn("FTP server refused login: {}, user: {}", getIp(), getUsername()); ftp.logout(); ftp.disconnect(); return null; } ftp.setControlEncoding(getEncoding()); ftp.setFileType(FTP.BINARY_FILE_TYPE); ftp.enterLocalPassiveMode(); return ftp; }
private void _connectFtp(String user, String password, String host, int port, IMoverInterface callbackContext) throws IOException { FTPClient ftpClient = new FTPClient(); ftpClient.connect(host, port); int replyCode = ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(replyCode)) { callbackContext.error("Operation failed. Server reply code: \" + replyCode"); return; } boolean success = ftpClient.login(user, password); if (!success) { callbackContext.error("Bad username or password"); return; } ftpClient.setFileType(FTP.BINARY_FILE_TYPE); ftpClient.enterLocalPassiveMode(); String key = UUID.randomUUID().toString(); mFtpChannels.put(key, ftpClient); callbackContext.success(key); }
private void connect() throws IOException { try { this.ftp.connect(this.host); if (this.verbose) { logger.info("Connected to " + this.host + "."); } int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { throw new IOException("Could not connect properly."); } } catch (IOException e) { this.disconnect(); throw e; } }
public void open(){ if ( !ftpclient.isConnected() ){ try { ftpclient.connect( getData("server").getString(), getData("port").getInt() ); errorCode = ftpclient.getReplyCode(); if (!FTPReply.isPositiveCompletion(errorCode)) throw new Exception( ftpclient.getReplyString() ); succeeded = ftpclient.login(username, password); errorCode = ftpclient.getReplyCode(); } catch (Exception e) { succeeded = false; errorText = e.getMessage(); } setStatusData(); } }
public FTPFile[] listFiles(String directory) { if ( !ftpclient.isConnected() ){ errorText = "not connected"; succeeded = false; return null; } FTPFile[] files = null; try{ files = ftpclient.listFiles(directory); errorCode = ftpclient.getReplyCode(); succeeded = FTPReply.isPositiveCompletion(errorCode); }catch(Exception e){ errorCode = ftpclient.getReplyCode(); errorText = e.getMessage(); }finally{ setStatusData(); } return files; }