SyntaxHighlighter

About Me

2015年12月20日 星期日

CURL 與 Shell Script 相關使用

常用語法

分享一下最近使用 curl 去 access 網站會需要用到的指令

常用語法

1. 使用 curl 直接 access 網站

curl http://xxx.xxx.xxx

2. 透過 curl post data 給網站

curl --data "Account=xxx&Password=xxx" http://xxx.xxx.xxx
// 在這個範例中傳送了 Account 跟 Password 兩個參數

3. 透過 curl 使用 user agent

curl -A "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36" http://xxx.xxx.xxx
// 此範例為使用 MAC 的 OS 然後還有使用 google chrome 的瀏覽器

4. 透過 curl 去記錄目前所使用的 cookie

1. 取得第一次驗證的 cookie

curl --cookie cookie_file.txt --cookie-jar cookie_file.txt --data "Account=xxx&Password=xxx" http://xxx.xxx.xxx/check.php

// 將驗證資料傳到 check.php 獲得 cookie ,並且將 cookie 存在同層目錄下面的 cookie_file.txt 中

2. 使用已經取得的 cookie file 進行其他的使用

curl --cookie cookie_file.txt http://xxx.xxx.xxx/something.php

shell script 額外使用

1. 使用額外的 config file

  • vim env.conf

      test1="test1"
      test2 = "test2"
      # 宣告會使用到的參數
    
  • vim sourcecode.sh

      source env.conf
    
      # 只要在 source code 中引入這個檔案就可以使用了
    
      echo $test1 # test1
      echo $test2 # test2
    

2. 取得當前執行的目錄

WORKDIR=$(cd "$(dirname "$0")"; pwd)

3. 在 mac 中可以直接雙擊 sh 檔

直接將檔名從 .sh 改成 .command

目前遇到的問題

1. 要傳送兩次 post data 給 check.php 後的 cookie_file 才可以使用

curl --cookie cookie_file.txt --cookie-jar cookie_file.txt --data "Account=xxx&Password=xxx" http://xxx.xxx.xxx/check.php
curl --cookie cookie_file.txt http://xxx.xxx.xxx/something.php

// 這樣會無法在 something.php 中取得到資料

curl --cookie cookie_file.txt --cookie-jar cookie_file.txt --data "Account=xxx&Password=xxx" http://xxx.xxx.xxx/check.php
curl --cookie cookie_file.txt --cookie-jar cookie_file.txt --data "Account=xxx&Password=xxx" http://xxx.xxx.xxx/check.php
curl --cookie cookie_file.txt http://xxx.xxx.xxx/something.php

// 這樣就可以在 something.php 中取得資料

Reference

  1. Linux - shell script 取得當前路徑
  2. 如何雙擊 shell script file
  3. 如何使用 applescript 去呼叫 shell script
  4. 如何使用 curl 進行 session 驗證

沒有留言:

張貼留言