如何在R中从密码保护的SFTP服务器下载加密ZIP文件?
从带密码保护的SFTP下载加密ZIP文件的R语言解决方案
问题背景
尝试从带密码保护的SFTP服务器下载加密的.zip文件到R环境,下载后的加密ZIP无法打开;但相同代码可正常下载并打开未加密文件,问题出在加密ZIP的密码验证环节。
已尝试操作及错误
- 读取服务器文件名:
url <- "<url>" userpwd <- "<username:password>" filenames <- getURL(url, userpwd)
- 获取目标ZIP文件URL并尝试文本模式下载,触发错误:
filename1 <- paste0(url, strsplit(filenames, "\n")[[1]][2]) ftp_data1 <- getURL(filename1, userpwd)
Error in curlPerform(curl = curl, .opts = opts, .encoding = .encoding) :
embedded nul in string: 'PK\003\004\024'
- 改用二进制模式下载,可生成ZIP文件但无法打开:
bin <- getBinaryURL(filename1, userpwd=userpwd) con <- file("<output.zip>", open = "wb") writeBin(bin, con) close(con)
解决方案
R基础工具不支持直接处理密码保护的ZIP,需借助第三方工具或包完成解压,以下是三种可行方法:
方法1:调用系统unzip命令(推荐)
利用系统自带的unzip命令(Linux/macOS默认自带,Windows需通过Git Bash/Chocolatey安装),下载完成后直接传入密码解压:
# 保持原有的二进制下载代码 bin <- getBinaryURL(filename1, userpwd=userpwd) con <- file("encrypted_file.zip", open = "wb") writeBin(bin, con) close(con) # 替换为你的ZIP文件密码 zip_pwd <- "your_zip_password" # 执行解压命令,将文件提取到指定目录 system(paste0('unzip -P "', zip_pwd, '" encrypted_file.zip -d ./extracted_files'))
方法2:使用zip包
zip包原生支持带密码的ZIP解压,先安装再调用:
install.packages("zip") library(zip) # 下载完成后直接解压 unzip( zipfile = "encrypted_file.zip", exdir = "./extracted_files", password = "your_zip_password" )
方法3:调用7zip命令行(兼容AES加密)
如果ZIP采用AES加密(unzip可能不支持),可使用7zip工具:
zip_pwd <- "your_zip_password" # 需先安装7zip并确保其在系统PATH中 system(paste0('7z x encrypted_file.zip -o./extracted_files -p"', zip_pwd, '"'))
关键说明
- 你之前的SFTP下载代码是正确的,问题并非出在文件下载环节,而是解压时未提供ZIP文件的专属密码。
- 未加密文件能正常打开,是因为无需密码验证;加密ZIP必须输入对应密码才能解析内部内容。
内容的提问来源于stack exchange,提问作者Mathilde Verdam
相关产品推荐
相关产品推荐

