我已经建立了一个curl命令
cmd = %Q(curl --tlsv1.2 -b #{config['cookies']} -c #{config['cookies']} --
connect-timeout 60 -X POST
-H 'Content-Type: application/xml'
-H 'Accept: application/xml'
-d '#{xml_content}'
--location #{uri})
puts cmd
打印字符串时输出如下
curl --tlsv1.2 -b /tmp/cookie.txt -c /tmp/cookie.txt --connect-timeout 60 -X POST
-H 'Content-Type: application/xml'
-H 'Accept: application/xml'
-d '<?xml version="1.0" encoding="UTF-8" ?>
<ns:login xmlns:ns="http://www.actility.com/smp/ws/admin">
<login>hello</login><password>wPa4GwYbRTCw0Uy!</password></ns:login>'
--location https://myapi.application.com
如何在ruby中执行它而不将cmd字符串修改为单个cmd?
答案 0 :(得分:1)
我认为您应该在“\ n”de“\”之前添加到您的cmd,它应该按如下方式添加:
[1] pry(main)> cmd = %Q(curl -i
[1] pry(main)* -H 'Authorization: Basic dXNlcjpwYXNzd29yZA=='
[1] pry(main)* -XGET 'http://httpbin.org/basic-auth/user/password')
=> "curl -i\n" + "-H 'Authorization: Basic dXNlcjpwYXNzd29yZA=='\n" + "-XGET 'http://httpbin.org/basic-auth/user/password'"
[2] pry(main)> exec(cmd)
curl: no URL specified!
curl: try 'curl --help' or 'curl --manual' for more information
sh: line 1: -H: command not found
sh: line 2: -XGET: command not found
你应该这样写:
[1] pry(main)> cmd = %Q(curl -i \\
[1] pry(main)* -H 'Authorization: Basic dXNlcjpwYXNzd29yZA==' \\
[1] pry(main)* -XGET 'http://httpbin.org/basic-auth/user/password')
=> "curl -i \\\n" + "-H 'Authorization: Basic dXNlcjpwYXNzd29yZA==' \\\n" + "-XGET 'http://httpbin.org/basic-auth/user/password'"
[2] pry(main)> exec(cmd)
HTTP/1.1 200 OK
Connection: keep-alive
Server: meinheld/0.6.1
Date: Mon, 05 Jun 2017 09:46:24 GMT
Content-Type: application/json
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true
X-Powered-By: Flask
X-Processed-Time: 0.000503063201904
Content-Length: 47
Via: 1.1 vegur
{
"authenticated": true,
"user": "user"
}
答案 1 :(得分:0)
您已经构建了一个包含该命令的字符串,因此您需要将其传递给Ruby的一个shell执行方法。 我建议
result = %x(#{cmd})
以下是您可能会发现有用的更详细的答案:https://stackoverflow.com/a/2400/2029766