Ruby Base64编码包含变量中的换行符

时间:2015-10-14 14:47:39

标签: ruby variables base64

base64编码,带有换行符

试图了解如何通过Base64 module在Base64中追加行返回,我无法使编码完成我想要的操作...

简单地说,鉴于我的错误代码:

 other = kwargs.get('object')
 if other is not None:
     self.attrx = other.attrx
     self.attry = other.attry
     # etc

返回:

require "base64"
#
enc   = Base64.encode64(%q[
    #!/bin/bash
    echo 'this is a test of nesting quotes using ruby's %q thing-a-ma-bob'
    echo 'this should return a base64 formattes version of this "file" for the purposes of cloudconfig formation'
    echo "i'm not quite certain what this script should do... so for now it does a lot of nothing ... and i don't care"
    df -h |awk '{print $1"[ ]"$2"{ }"$3" -- "$4}'
    ])
#
plain = Base64.decode64(enc)
#
#
puts "base64: "+enc
puts
puts "plain:"
puts plain
puts
puts "let's run the script now for testing:"
puts
exec({"code" => plain}, "echo ; echo bash ; echo $code")

我想尝试理解

如何让换行符进入变量I&m; m进入系统命令,不必格式如下:

base64: CiAgICAjIS9iaW4vYmFzaAogICAgZWNobyAndGhpcyBpcyBhIHRlc3Qgb2Yg
bmVzdGluZyBxdW90ZXMgdXNpbmcgcnVieSdzICVxIHRoaW5nLWEtbWEtYm9i
JwogICAgZWNobyAndGhpcyBzaG91bGQgcmV0dXJuIGEgYmFzZTY0IGZvcm1h
dHRlcyB2ZXJzaW9uIG9mIHRoaXMgImZpbGUiIGZvciB0aGUgcHVycG9zZXMg
b2YgY2xvdWRjb25maWcgZm9ybWF0aW9uJwogICAgZWNobyAiaSdtIG5vdCBx
dWl0ZSBjZXJ0YWluIHdoYXQgdGhpcyBzY3JpcHQgc2hvdWxkIGRvLi4uIHNv
IGZvciBub3cgaXQgZG9lcyBhIGxvdCBvZiBub3RoaW5nIC4uLiBhbmQgaSBk
b24ndCBjYXJlIgogICAgZGYgLWggfGF3ayAne3ByaW50ICQxIlsgXSIkMiJ7
IH0iJDMiIC0tICIkNH0nCiAgICA=

plain:

#!/bin/bash
echo 'this is a test of nesting quotes using ruby's %q thing-a-ma-bob'
echo 'this should return a base64 formattes version of this "file" for the purposes of cloudconfig formation'
echo "i'm not quite certain what this script should do... so for now it does a lot of nothing ... and i don't care"
df -h |awk '{print $1"[ ]"$2"{ }"$3" -- "$4}'


let's run the script now for testing:


bash
#!/bin/bash echo 'this is a test of nesting quotes using ruby's %q thing-a-ma-bob' echo 'this should return a base64 formattes version of this "file" for the purposes of cloudconfig formation' echo "i'm not quite certain what this script should do... so for now it does a lot of nothing ... and i don't care" df -h |awk '{print $1"[ ]"$2"{ }"$3" -- "$4}'

感谢

2 个答案:

答案 0 :(得分:1)

对有效负载进行编码时,可能需要在通过Base64进行编码之前包含换行符。请参阅以下内容:

[7] pry(main)> require "base64"
=> true
[8] pry(main)> Base64.encode64("Apple\nBacon")
=> "QXBwbGUKQmFjb24=\n"
[9] pry(main)> Base64.decode64(_)
=> "Apple\nBacon"
[10] pry(main)> Base64.encode64("Apple\nBacon")
=> "QXBwbGUKQmFjb24=\n"
[11] pry(main)> puts Base64.decode64(_)
Apple
Bacon

在编码之前在字符串中放置“\ n”,它将在解码时返回并随后打印

答案 1 :(得分:1)

问题在于echo如何处理其输入,它与base 64编码/解码无关。

您致电exececho $code。此处$code已展开,然后在空格上拆分,然后作为字符串列表传递给echoecho然后打印出每个用空格分隔的内容。

为了防止这种情况,您可以确保将整个$code变量作为单个字符串直接传递,方法是将其括在引号中。将您的exec行更改为(请注意$code周围的额外引号):

exec({"code" => plain}, "echo ; echo bash ; echo \"$code\"")

这将打印出包括换行符的块。