2017-06-05 71 views
-1

我不得不建立一個捲曲命令紅寶石執行多行CMD串

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 

如何在紅寶石執行它的w/o修改將cmd字符串轉換爲單個cmd?

回答

1

德「\」它應該是scaped如下:

[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" 
} 
0

您已經構建了一個包含該命令的字符串,因此您需要將它傳遞給Ruby的某個shell執行方法。 我建議

result = %x(#{cmd}) 

這裏是你可能會發現有用的更詳細的回答:我認爲你應該前作「\ n」添加到您的CMD https://stackoverflow.com/a/2400/2029766

+0

我得到這個錯誤 'curl:沒有指定URL! curl:嘗試'curl --help'或'curl --manual'以獲取更多信息 sh:2:-H:找不到 sh:3:-H:找不到 sh:4:-d:找不到 sh:7: - location:not found# –

+0

我看到了問題。傳遞給'%x()'的字符串換行就像在終端中打到一樣。爲了防止發送命令,你需要通過預置一個'\'(如建議的anquegi)來轉義換行符,或者你只需​​刪除換行符以執行; '%×(#{cmd.tr( 「\ n」 個, '')})'。 –