Skip to content

Instantly share code, notes, and snippets.

@kirilkirkov
Last active September 15, 2015 12:25
Show Gist options
  • Save kirilkirkov/f881d407aef2a99d084a to your computer and use it in GitHub Desktop.
Save kirilkirkov/f881d407aef2a99d084a to your computer and use it in GitHub Desktop.
Какво е cURL и как се работи с него
Какво е CURL ?
cURL е инструмент за прехвърляне на информация от и към сървър чрез използването на някой от поддържаните протоколи (DICT, FILE, FTP, FTPS, GOPHER, HTTP, HTTPS, IMAP, IMAPS, LDAP, LDAPS, POP3, POP3S, RTMP, RTSP, SCP, SFTP, SMB, SMBS, SMTP, SMTPS, TELNET and TFTP). Програмата е направена да работи без намеса на потребителия.
cURL също поддържа proxy, user authentication, FTP ъплоад, HTTP post, SLL връзки, кукита, файлов трансфер, металинк и много други функции.
Статус на операциите
cURL обикновенно показва статуса на текущата операция, количество на прехвърлената информация, бързина на прехвърляне, очаквано време за приключване и други.
cURL по подразбиране показва тази информация в терминала, така че ако curl трябва да искара информация в терминала се забранява статуса на операцията за да не се смесят output информацията и статуса.
Ако искате статус на прогреса за HTTP POST или PUT заявки, трябва да пренасочите response output-а в файл.
За URL-лите
Можете да посочите няколко URL адреси или части от URL адреси като напишете нужната част в скоби:
http://site.{one,two,three}.com
или можете да сложите range с използването на []:
ftp://ftp.numericals.com/file[1-100].txt
ftp://ftp.numericals.com/file[001-100].txt
ftp://ftp.letters.com/file[a-z].txt
Вложени последователности не се поддържат, но можете да използвате няколко такива една след друга:
http://any.org/archive[1996-1999]/vol[1-4]/part{a,b,c}.html
Можете да зададете брояч на думи или цифри в range-а които са позволени като брой например:
http://www.numericals.com/file[1-100:10].txt
http://www.letters.com/file[a-z:2].txt
Ако сложите URL без посочен протокол (protocol://), curl ще се опита да познае какъв протокол може би искате. Той автоматично ще използва HTTP, но ще опита и с други протоколи базирани на префикса на хоста. За пример, хостове започващи с "ftp." curl ще приеме, че искате да отворите FTP.
Синтакс
curl [options] [URL...]
Полезни параметри
-L, --location
Ако сървърът съобщи, че заявената страница е преместан на друго място (с хедър и 3XX отговор) тази опция ще накара curl да отиде до новата локация. Ако се ползва в комбинация с -i, --include or -I, --head, хедърите от всички страници ще се покажат.
-I, --head
Връща HTTP хедърите
-H, --header <header>
Изпращане на хедъри към сървъра. Пример: # curl -H "X-First-Name: Joe" http://192.168.0.1/
Полезни параметри за дебъг при бавен download
cURL поддържа форматирана извадка на детайли от заявка с параметъра -w. За нашата цел ще се средоточим върху изваждането на времето за което данните ще се получат.
Създаваме файл curl-format.txt и слагаме в него следният текст:
\n
time_namelookup: %{time_namelookup}\n
time_connect: %{time_connect}\n
time_appconnect: %{time_appconnect}\n
time_pretransfer: %{time_pretransfer}\n
time_redirect: %{time_redirect}\n
time_starttransfer: %{time_starttransfer}\n
----------\n
time_total: %{time_total}\n
\n
Правиме заявка към целта:
curl -w "@curl-format.txt" -o /dev/null -s http://wordpress.com/
По този начин искарваме информацията която е записана в файла curl-format.txt като cURL замества промернливите %{variable} с реални стойности и резултата се изкарва в terminal-а. Ето лист с всички променливи с които cURL работи:
The variables available are:
content_type The Content-Type of the requested document, if there was any.
filename_effective The ultimate filename that curl writes out to. This is only meaningful if curl is told to write to a file with the --remote-name or --output option. It's most useful in combination with the --remote-header-name option. (Added in 7.25.1)
ftp_entry_path The initial path curl ended up in when logging on to the remote FTP server. (Added in 7.15.4)
http_code The numerical response code that was found in the last retrieved HTTP(S) or FTP(s) transfer. In 7.18.2 the alias response_code was added to show the same info.
http_connect The numerical code that was found in the last response (from a proxy) to a curl CONNECT request. (Added in 7.12.4)
local_ip The IP address of the local end of the most recently done connection - can be either IPv4 or IPv6 (Added in 7.29.0)
local_port The local port number of the most recently done connection (Added in 7.29.0)
num_connects Number of new connects made in the recent transfer. (Added in 7.12.3)
num_redirects Number of redirects that were followed in the request. (Added in 7.12.3)
redirect_url When an HTTP request was made without -L to follow redirects, this variable will show the actual URL a redirect would take you to. (Added in 7.18.2)
remote_ip The remote IP address of the most recently done connection - can be either IPv4 or IPv6 (Added in 7.29.0)
remote_port The remote port number of the most recently done connection (Added in 7.29.0)
size_download The total amount of bytes that were downloaded.
size_header The total amount of bytes of the downloaded headers.
size_request The total amount of bytes that were sent in the HTTP request.
size_upload The total amount of bytes that were uploaded.
speed_download The average download speed that curl measured for the complete download. Bytes per second.
speed_upload The average upload speed that curl measured for the complete upload. Bytes per second.
ssl_verify_result The result of the SSL peer certificate verification that was requested. 0 means the verification was successful. (Added in 7.19.0)
time_appconnect The time, in seconds, it took from the start until the SSL/SSH/etc connect/handshake to the remote host was completed. (Added in 7.19.0)
time_connect The time, in seconds, it took from the start until the TCP connect to the remote host (or proxy) was completed.
time_namelookup The time, in seconds, it took from the start until the name resolving was completed.
time_pretransfer The time, in seconds, it took from the start until the file transfer was just about to begin. This includes all pre-transfer commands and negotiations that are specific to the particular protocol(s) involved.
time_redirect The time, in seconds, it took for all redirection steps include name lookup, connect, pretransfer and transfer before the final transaction was started. time_redirect shows the complete execution time for multiple redirections. (Added in 7.12.3)
time_starttransfer The time, in seconds, it took from the start until the first byte was just about to be transferred. This includes time_pretransfer and also the time the server needed to calculate the result.
time_total The total time, in seconds, that the full operation lasted. The time will be displayed with millisecond resolution.
url_effective The URL that was fetched last. This is most meaningful if you've told curl to follow location: headers.
Примери
curl http://www.computerhope.com/index.htm
Ще отвори index.htm от www.computerhope.com чрез HTTP протокола и ще искара информацията. Това е същото като да отворите изходния код на web страницата. Ще бъде показан суровият HTML.
curl http://www.computerhope.com/index.htm > index.htm
Ще направи същото с разликата че изходният код ще бъде записан в посоченият файл (index.htm) в директорията в която сте.
curl -O http://www.computerhope.com/index.htm
Ще вземе същият файл със същият изходен код и ще го запише в директорията в която се намирате.
curl --limit-rate 1234B -O http://www.computerhope.com/index.htm
Същото като горните но с лимит на скороста 1,234 bytes/second.
curl --limit-rate 1234B -O -# http://www.computerhope.com/index.htm
Същото като горните но с показване на прогрес бар.
curl -I google.com
Резултат:
HTTP/1.1 302 Found
Cache-Control: private
Content-Type: text/html; charset=UTF-8
Location: http://www.google.bg/?gfe_rd=cr&ei=DQf4Vd_yMqKt8wen3rHIAQ
Content-Length: 258
Date: Tue, 15 Sep 2015 11:54:53 GMT
Server: GFE/2.0
с параметъра -I взимаме само хедърите.
curl -L google.com
С този параметър ако има редиректи ги следваме
curl -IL google.com
Резултат:
HTTP/1.1 302 Found
Cache-Control: private
Content-Type: text/html; charset=UTF-8
Location: http://www.google.bg/?gfe_rd=cr&ei=hAf4Vbm3HIOu8wfbw4-wCA
Content-Length: 258
Date: Tue, 15 Sep 2015 11:56:52 GMT
Server: GFE/2.0
HTTP/1.1 200 OK
Date: Tue, 15 Sep 2015 11:56:52 GMT
Expires: -1
Cache-Control: private, max-age=0
Content-Type: text/html; charset=windows-1251
P3P: CP="This is not a P3P policy! See http://www.google.com/support/accounts/bin/answer.py?hl=en&answer=151657 for more info."
Server: gws
X-XSS-Protection: 1; mode=block
X-Frame-Options: SAMEORIGIN
Set-Cookie: PREF=ID=1111111111111111:FF=0:TM=1442318212:LM=1442318212:V=1:S=Bx6e_yi5jnr2yVBL; expires=Thu, 31-Dec-2015 16:02:17 GMT; path=/; domain=.google.bg
Set-Cookie: NID=71=VCLljZPWKLsyNa6QAIuhBpiMXKW3VTkiHn5aZVbn4RHIOgpy93HUL0rCGmeVTBBmNnUjlMGnl6lffMET0hygU7u7tmdVwxE-CBMOp1OlAmqh5lRJVu7G9kqbfgXGJBn0; expires=Wed, 16-Mar-2016 11:56:52 GMT; path=/; domain=.google.bg; HttpOnly
Set-Cookie: CONSENT=CG.24ae17; expires=Fri, 16-Oct-2015 11:56:52 GMT; path=/; domain=.google.bg
Transfer-Encoding: chunked
Accept-Ranges: none
Vary: Accept-Encoding
С тазо комбинация на параметри връщаме само хедърите от всичките локации дори да има редирект, както е в случая.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment