Search code examples
rsftpgeturl

R: change port to connect with SFTP server


I have a connection with an ftp server with the following code:

url       <- "ftp://MyServer"
userpwd   <- "MyUser:MyPass"
filenames <- getURL(url, userpwd = userpwd, ftp.use.epsv = FALSE, dirlistonly = TRUE, port = 22) 
filen     <- "MyFile.csv"      
rawdata   <- getURL(paste(url, filen, sep = ""), userpwd = userpwd, crlf =  TRUE)

The file will be moved to an SFTP server, so I need to change the input. This new SFTP server is accessed via port 22 instead of the standard port 21. At the moment the connection fails with the following error

Error in function (type, msg, asError = TRUE)  : 
  Failed to connect to MyServer port 21: Connection refused

It takes the wrong port, but how do I tell R to choose port 22?


Solution

  • You need to specify the SFTP protocol in the URL, so the line

    url       <- "ftp://MyServer"
    

    should become

    url       <- "sftp://MyServer"
    

    getUrl will then use the SSH port (22).