Search code examples
rcurlsftp

How to check if an FTP file exists


I am trying to check if a file exists on my ftp server.

I've tried using the packages httr and httr2 but haven't gotten it to work. Below are my attempts:

my_file_url <- "sftp://my_server/my_file.txt"

With httr

httr::HEAD(my_file_url, httr::authenticate(my_username, my_password))

Fails with the below message

Error in x$headers$`content-type` : 
  $ operator is invalid for atomic vectors

With httr2


request(my_file_url) %>% 
  req_method("HEAD") %>% 
  req_auth_basic( my_username, my_password) %>% 
  req_perform()

Fails with the following message (I checked my credentials):

Error:
! Authentication failure
  • What am I doing wrong in these two attempts?
  • How do I do it directly through the curl package?

P.S. I tried the following, but this downloads the file:

curl::curl_fetch_memory(my_file_url, handle = my_curl_handle)

Solution

  • I don't believe you can pass HTTP methods (HEAD) or authenticate headers to (s)ftp service, but if your permissions allow you to get a directory listing, this might work:

    library(curl)
    #> Using libcurl 8.3.0 with Schannel
    # https://test.rebex.net/ demo server
    SFTP_DEMO <- "sftp://demo:password@test.rebex.net:22/"
    
    file_list <- 
      curl(url = SFTP_DEMO, handle = new_handle(dirlistonly = TRUE)) |> 
      readLines()
    
    file_list
    #> [1] "."          ".."         "pub"        "readme.txt"
    
    "readme.txt" %in% file_list
    #> [1] TRUE
    
    "im-not-here" %in% file_list
    #> [1] FALSE
    

    Created on 2023-11-29 with reprex v2.0.2