使用openssl运行Rscript系统命令

时间:2020-06-18 01:21:58

标签: r rscript

让R为我执行系统命令有点麻烦。系统命令是openssl,非常基本。

我在Windows系统上。

如果我在cmd.exe提示符或powershell上执行以下代码,则它将按预期工作:

## echo "the name of the dog is bruce" | openssl enc -base64
dGhlIG5hbWUgb2YgdGhlIGRvZyBpcyBicnVjZQo=

但是,当我尝试将其转换回我的R脚本中的原始字符串时,它不起作用:

mydata <- "dGhlIG5hbWUgb2YgdGhlIGRvZyBpcyBicnVjZQo="
system(sprintf("echo '%s' | openssl enc -base64 -d", mydata))

它抱怨找不到echo

Warning message:
'echo' not found

我知道有些软件包可以下载,但是,我想使用R附带的基本软件包来解决此问题。由于openssl似乎不是基本软件包的一部分,因此我采用上述方法(我知道这样做效率不高,所以请对我放轻松)。

我尝试过:

system2(sprintf("echo '%s' | openssl enc -base64 -d", mydata))

shell(sprintf("echo '%s' | openssl enc -base64 -d", mydata))

没有一个有效。

1 个答案:

答案 0 :(得分:0)

使用shell(),提供openssl的完整文件路径,它应该可以工作。请注意,您需要使用参数intern = TRUE,以便它返回可以分配的R对象。

mydata <- "dGhlIG5hbWUgb2YgdGhlIGRvZyBpcyBicnVjZQo="
shell(sprintf("echo %s | \"C:/Tools/openssl-1.1.1/openssl.exe\" enc -base64 -d", mydata), intern = TRUE)

[1] "the name of the dog is bruce"

为完整起见,请使用openssl库:

library(openssl)

str_enc <- base64_encode("the name of the dog is bruce")
rawToChar(base64_decode(str_enc))

[1] "the name of the dog is bruce"
相关问题