curl命令

我使用過的Linux命令之curl - 強大的網絡傳輸工具

本文鏈接:http://codingstandards.iteye.com/blog/807844 (轉載請註明出處)

用途說明

curl命令是一個功能強大的網絡工具,它能夠通過http、ftp等方式下載文件,也能夠上傳文件。其實curl遠不止前面所說的那些功能,大家可以通過man curl閱讀手冊頁獲取更多的信息。類似的工具還有wget。

curl命令使用了libcurl庫來實現,libcurl庫常用在C程序中用來處理HTTP請求,curlpp是libcurl的一個C++封裝,這幾個東西可以用在抓取網頁、網絡監控等方面的開發,而curl命令可以幫助來解決開發過程中遇到的問題。

常用參數

curl命令參數很多,這裏只列出我曾經用過、特別是在shell腳本中用到過的那些。

-v/--verbose 小寫的v參數,用於打印更多信息,包括髮送的請求信息,這在調試腳本是特別有用。

-m/--max-time <seconds> 指定處理的最大時長

-H/--header <header> 指定請求頭參數

-s/--slient 減少輸出的信息,比如進度

--connect-timeout <seconds> 指定嘗試連接的最大時長

-x/--proxy <proxyhost[:port]> 指定代理服務器地址和端口,端口默認爲1080

-T/--upload-file <file> 指定上傳文件路徑

-o/--output <file> 指定輸出文件名稱

-d/--data/--data-ascii <data> 指定POST的內容

--retry <num> 指定重試次數

-e/--referer <URL> 指定引用地址

-I/--head 僅返回頭部信息,使用HEAD請求

使用示例

示例一 獲取指定網頁

[root@jfht ~]# curl http://www.sunrisecorp.net/
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gbk" />
<meta name="title" content="歡迎您 - 上海騰一" />
<meta name="keyword" content="上海騰一,融合通信,電子商務,語音通信,數據通信,基站工程外包託管,物聯網,網站建設,電子商務解決方案,移動互聯網,短信,彩信,呼叫中心,多方會議,PBX,IVR,電子商務策劃方案,設備代維,網絡優化,通信工程,電信增值,3G" />
<meta name="description" content="上海騰一信息技術有限公司專注於電信增值、通信工程、電子商務等領域,擁有近十年的經驗。" />
<title>
歡迎您 - 上海騰一
</title>


插播一下廣告:上海騰一信息技術有限公司是一家致力於通信工程、電子商務和電信增值業務的公司,請訪問官方網址:http://www.sunrisecorp.net/



此處省略掉網頁內容


</body>
</html>[root@jfht ~]#

示例二 查看響應頭信息

[root@jfht ~]# curl -I http://www.sunrisecorp.net/
HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Accept-Ranges: bytes
ETag: W/"17801-1285643951000"
Last-Modified: Tue, 28 Sep 2010 03:19:11 GMT
Content-Type: text/html
Content-Length: 17801
Date: Tue, 12 Oct 2010 12:49:20 GMT

[root@jfht ~]#


示例三 檢查網頁是否可正常訪問

以下是一個tomcat監控腳本的部分內容。

Bash代碼 複製代碼收藏代碼spinner.gif
  1. # usage: check_once <port> <path>

  2. # 使用curl檢查網頁是否可以正常訪問,如果不能訪問就重啓tomcat。

  3. check_once()

  4. {

  5. echo

  6. echo "$(date) Tomcat check once"

  7. # 2008.08.21 -I/--head -s/--silent

  8. #if curl -s -I --connect-timeout 5 --max-time 10 http://localhost:$1/; then

  9. # 2010.02.16 add 200 OK test

  10. if curl -s -I --connect-timeout 5 --max-time 10 http://localhost:$1/$2 | grep -q '200 OK';



  11. then

  12. echo "$(date) Tomcat maybe OK"

  13. else

  14. echo "$(date) Tomcat maybe FAULT"

  15. restart

  16. fi

  17. }


  18. # usage: check_loop <port> <path>

  19. # 每隔一分鐘檢查一次網頁是否正常

  20. check_loop()

  21. {

  22. while true;

  23. do

  24. sleep 60

  25. check_once $1 $2 >> $CATALINA_HOME/logs/check.$(date +%Y-%m-%d).log

  26. done

  27. }


  28. # usage: monitor <path>

  29. # 對path指定的本機網頁進行監控

  30. # 2008.06.26

  31. # 2010.09.20 add path parameter

  32. monitor()

  33. {

  34. PORT=80

  35. if grep 'Connector port="80"' $CATALINA_HOME/conf/server.xml; then

  36. PORT=80

  37. elif grep 'Connector port="8080"' $CATALINA_HOME/conf/server.xml; then

  38. PORT=8080

  39. else

  40. echo "Cannot detect server port for Tomcat"

  41. return 12

  42. fi

  43. echo "Tomcat server port is $PORT"


  44. if status; then

  45. check_loop $PORT "$1" &

  46. #check_loop $PORT "$1"

  47. fi

  48. }


# usage: check_once <port> <path>
# 使用curl檢查網頁是否可以正常訪問,如果不能訪問就重啓tomcat。
check_once()
{
        echo
        echo "$(date)  Tomcat check once"
        # 2008.08.21 -I/--head -s/--silent
        #if curl -s -I --connect-timeout 5 --max-time 10 http://localhost:$1/; then
        # 2010.02.16 add 200 OK test
        if curl -s -I --connect-timeout 5 --max-time 10 http://localhost:$1/$2 | grep -q '200 OK';


 then
                echo "$(date)  Tomcat maybe OK"
        else
                echo "$(date)  Tomcat maybe FAULT"
                restart
        fi
}

# usage: check_loop <port> <path>
# 每隔一分鐘檢查一次網頁是否正常
check_loop()
{
        while true;
        do
                sleep 60
                check_once $1 $2 >> $CATALINA_HOME/logs/check.$(date +%Y-%m-%d).log
        done
}

# usage: monitor <path>
# 對path指定的本機網頁進行監控
# 2008.06.26
# 2010.09.20 add path parameter
monitor()
{
        PORT=80
        if grep 'Connector port="80"' $CATALINA_HOME/conf/server.xml; then
                PORT=80
        elif grep 'Connector port="8080"' $CATALINA_HOME/conf/server.xml; then
                PORT=8080
        else
                echo "Cannot detect server port for Tomcat"
                return 12
        fi
        echo "Tomcat server port is $PORT"

        if status; then
                check_loop $PORT "$1" &
                #check_loop $PORT "$1"
        fi
}
 


這個腳本的執行方式是 monitor <path>,比如monitor main/index.html。下面是執行時輸出的日誌信息片段。


2010年 10月 09日 星期六 15:20:38 CST Tomcat check once
2010年 10月 09日 星期六 15:20:46 CST Tomcat maybe OK

2010年 10月 09日 星期六 15:21:46 CST Tomcat check once
2010年 10月 09日 星期六 15:21:57 CST Tomcat maybe FAULT
Tomcat is now running, not stopped: 0
Tomcat is now running, not stopped: 1
Tomcat is now running, not stopped: 2
Tomcat is now running, not stopped: 3
Tomcat is now running, not stopped: 4
Tomcat is now running, not stopped: 5
Tomcat is now running, not stopped: 6
Tomcat is now running, not stopped: 7
Tomcat is now running, not stopped: 8
Tomcat is now running, not stopped: 9
Tomcat killed use SIGKILL
Tomcat stopped
Starting tomcat

2010年 10月 09日 星期六 15:23:09 CST Tomcat check once
2010年 10月 09日 星期六 15:23:09 CST Tomcat maybe OK

2010年 10月 09日 星期六 15:24:09 CST Tomcat check once
2010年 10月 09日 星期六 15:24:09 CST Tomcat maybe OK


示例四 另一個檢查網頁是否正常的腳本


Bash代碼 複製代碼收藏代碼spinner.gif
  1. # 要檢查的網頁地址

  2. URL="http://www.sunrisecorp.net/"


  3. # usage:

  4. curlit()

  5. {

  6. curl --connect-timeout 15 --max-time 30 --head --silent "$URL" | grep 'HTTP/1.1 200 OK'

  7. }


  8. # 只有MIN_ALARM次訪問失敗時才告警

  9. MIN_ALARM=10


  10. #

  11. doit()

  12. {

  13. echo "===== $(now) ====="

  14. if ! curlit; then

  15. echo "$(now) bbdx nss access failed"

  16. N=1

  17. if [ -e curlit_error ]; then

  18. N="$(cat curlit_error)"

  19. N=$[N+1]

  20. fi

  21. echo "$(now) N=$N"

  22. echo $N >curlit_error

  23. if [ "$N" == "$MIN_ALARM" ]; then

  24. echo "$(now) do notify"

  25. touch curlit_error

  26. notify_curlit_error

  27. fi

  28. else

  29. if [ -e curlit_error ]; then

  30. echo "$(now) recovered"

  31. N=$(cat curlit_error)

  32. echo "$(now) N=$N"

  33. rm -f curlit_error

  34. if [ "$N" -ge "$MIN_ALARM" ]; then

  35. notify_curlit_recovered

  36. fi

  37. fi

  38. fi

  39. }


  40. doit >>log/curlit.log 2>&1


# 要檢查的網頁地址
URL="http://www.sunrisecorp.net/"

# usage: 
curlit()
{
        curl --connect-timeout 15 --max-time 30 --head --silent "$URL" | grep 'HTTP/1.1 200 OK'
}

# 只有MIN_ALARM次訪問失敗時才告警
MIN_ALARM=10

# 
doit()
{
	echo "===== $(now) ====="
	if ! curlit; then
			echo "$(now)  bbdx nss access failed"
			N=1
			if [ -e curlit_error ]; then
					N="$(cat curlit_error)"
					N=$[N+1]
			fi
			echo "$(now)  N=$N"
			echo $N >curlit_error
			if [ "$N" == "$MIN_ALARM" ]; then
					echo "$(now)  do notify"
					touch curlit_error
					notify_curlit_error
			fi
	else
			if [ -e curlit_error ]; then
					echo "$(now)  recovered"
					N=$(cat curlit_error)
					echo "$(now)  N=$N"
					rm -f curlit_error
					if [ "$N" -ge "$MIN_ALARM" ]; then
							notify_curlit_recovered
					fi
			fi
	fi
}

doit >>log/curlit.log 2>&1
 


示例五 使用HttpPost上傳數據

一個用於http post的腳本。

Bash代碼 複製代碼收藏代碼spinner.gif
  1. #!/bin/sh


  2. MS=1350514xxxx


  3. TM=$(date +"%Y%m%d%H%M%S")

  4. DT=$(date +"%Y%m%d")


  5. cat <<EOF >reqtmp.xml

  6. <?xml version="1.0" encoding="GBK" ?>

  7. <OwnPlatForm>

  8. <OrigDomain>QZT</OrigDomain>

  9. <HomeDomain>BOSS</HomeDomain>

  10. <ActivityCode>T5100001</ActivityCode>

  11. <ActionCode>0</ActionCode>

  12. <TransIDO>$TM</TransIDO>

  13. <TransIDH></TransIDH>

  14. <ProcessTime>$TM</ProcessTime>

  15. <CutOffDay>$DT</CutOffDay>

  16. <TestFlag>0</TestFlag>

  17. <Content>

  18. <![CDATA[

  19. <BizProcReq>

  20. <IDType>01</IDType>

  21. <IDValue>$MS</IDValue>

  22. <UserCity>14</UserCity>

  23. <UserCounty>1419</UserCounty>

  24. <OprCode>01</OprCode>

  25. <BizType>51</BizType>

  26. <OprTime>$TM</OprTime>

  27. <OprSrc>27</OprSrc>

  28. <ProductInfo>

  29. <PrdCode>510001</PrdCode>

  30. </ProductInfo>

  31. </BizProcReq>

  32. ]]>

  33. </Content>

  34. </OwnPlatForm>

  35. EOF


  36. cat reqtmp.xml



  37. URL="http://10.32.140.230:7092/fcgi-bin/UIG_NEWINT"


  38. curl --verbose --upload-file reqtmp.xml --header "Content-Type: text/xml""$URL" --output rsptmp.xml


  39. cat rsptmp.xml

#!/bin/sh

MS=1350514xxxx

TM=$(date +"%Y%m%d%H%M%S")
DT=$(date +"%Y%m%d")

cat <<EOF >reqtmp.xml
<?xml version="1.0" encoding="GBK" ?>
<OwnPlatForm>
        <OrigDomain>QZT</OrigDomain>
        <HomeDomain>BOSS</HomeDomain>
        <ActivityCode>T5100001</ActivityCode>
        <ActionCode>0</ActionCode>
        <TransIDO>$TM</TransIDO>
        <TransIDH></TransIDH>
        <ProcessTime>$TM</ProcessTime>
        <CutOffDay>$DT</CutOffDay>
        <TestFlag>0</TestFlag>
        <Content>
                <![CDATA[
                        <BizProcReq>
                                <IDType>01</IDType>
                                <IDValue>$MS</IDValue>
                                <UserCity>14</UserCity>
                                <UserCounty>1419</UserCounty>
                                <OprCode>01</OprCode>
                                <BizType>51</BizType>
                                <OprTime>$TM</OprTime>
                                <OprSrc>27</OprSrc>
                                <ProductInfo>
                                        <PrdCode>510001</PrdCode>
                                </ProductInfo>
                        </BizProcReq>
                ]]>
        </Content>
</OwnPlatForm>
EOF

cat reqtmp.xml


URL="http://10.32.140.230:7092/fcgi-bin/UIG_NEWINT"

curl --verbose --upload-file reqtmp.xml  --header "Content-Type: text/xml" "$URL" --output rsptmp.xml

cat rsptmp.xml


示例六 使用proxy的腳本

Bash代碼 複製代碼收藏代碼spinner.gif
  1. # usage: do_sync_once <mobile> <codes> <area_id> <opening>

  2. do_sync_once()

  3. {

  4. mobile=$1

  5. codes=$2

  6. area_id=$3

  7. opening=$4




  8. curl --silent --max-time 60 --proxy http://10.32.187.170:8080"http://host/boss/sync.jsp?seq=1251747862492&mobile=$mobile&serviceCodes=$codes&areaId=$area_id&opening=$opening"


  9. }

# usage: do_sync_once <mobile> <codes> <area_id> <opening>
do_sync_once()
{
        mobile=$1
        codes=$2
        area_id=$3
        opening=$4  
        


curl --silent --max-time 60 --proxy http://10.32.187.170:8080 "http://host/boss/sync.jsp?seq=1251747862492&mobile=$mobile&serviceCodes=$codes&areaId=$area_id&opening=$opening"

}


示例七 使用Google AJAX Search API進行搜索

Bash代碼 複製代碼收藏代碼spinner.gif
  1. # usage: google_search <STR>

  2. # Google搜索

  3. google_search()

  4. {

  5. REF="http://codingstandards.iteye.com/"

  6. KEY="ABQIAAAAHg_ENG5Yq9pOZd19v64gyxTMcdcN4KfyGCBxustvF1FXdNe4WBQOej_ZiBgIK6-a4M3hTxcVfSkt2g"

  7. STR="$1"

  8. # 採用網頁搜索

  9. curl --retry 5 -e "$REF""http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=$STR&hl=zh-CN&key=$KEY"2>/dev/null

  10. # 採用博客搜索

  11. #curl -e $REF "http://ajax.googleapis.com/ajax/services/search/blogs?v=1.0&q=$STR&hl=zh-CN"2>/dev/null

  12. #curl --retry 5 -e $REF "http://ajax.googleapis.com/ajax/services/search/blogs?v=1.0&q=$STR&hl=zh-CN"2>/dev/null

  13. #curl --retry 5 -e "$REF""http://ajax.googleapis.com/ajax/services/search/blogs?v=1.0&q=$STR&hl=zh-CN&key=$KEY"2>/dev/null

  14. }

# usage: google_search <STR>
# Google搜索
google_search()
{
        REF="http://codingstandards.iteye.com/"
        KEY="ABQIAAAAHg_ENG5Yq9pOZd19v64gyxTMcdcN4KfyGCBxustvF1FXdNe4WBQOej_ZiBgIK6-a4M3hTxcVfSkt2g"
        STR="$1"
        # 採用網頁搜索
        curl --retry 5 -e "$REF" "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=$STR&hl=zh-CN&key=$KEY" 2>/dev/null
        # 採用博客搜索
        #curl -e $REF "http://ajax.googleapis.com/ajax/services/search/blogs?v=1.0&q=$STR&hl=zh-CN" 2>/dev/null
        #curl --retry 5 -e $REF "http://ajax.googleapis.com/ajax/services/search/blogs?v=1.0&q=$STR&hl=zh-CN" 2>/dev/null
        #curl --retry 5 -e "$REF" "http://ajax.googleapis.com/ajax/services/search/blogs?v=1.0&q=$STR&hl=zh-CN&key=$KEY" 2>/dev/null
}

問題思考

相關資料

【1】Linux公社 Linux curl使用簡單介紹


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章