Linux-curl指令

388 阅读6分钟

Linux-curl指令

curl是一个用于从命令行或脚本中传输数据的工具,特别适用于在互连网或局域网环境中发送或接收数据。它的强大之处在于支持多种协议和多种复杂操作。以下将介绍curl的基本用法、常见示例以及一些高级用法。

一、基本概念

什么是curl?

curl是一个命令行工具,名称来自"Client URL",主要用于请求和传输数据。curl支持许多协议,包括HTTP、HTTPS、FTP、FTPS、SCP、SFTP、TFTP、TELNET、LDAP、LDAPS、DICT、FILE和GOPHER。由于其强大的功能和灵活性,curl被广泛应用于开发、调试和系统管理任务中。

安装curl

在大多数Linux发行版上,curl已经预装。如果没有,可以使用以下命令进行安装:

# Debian/Ubuntu
sudo apt-get install curl
​
# RedHat/CentOS
sudo yum install curl
​
# macOS(通过Homebrew)
brew install curl

二、基本用法

获取网页内容

最常见的用法是从一个URL获取内容。例如,获取Google首页的HTML内容:

curl http://www.google.com

这会将Google首页的HTML源代码输出到终端。

将内容保存到文件

使用-o或-O选项可以将内容保存到文件:

# 使用-o指定文件名
curl -o google.html http://www.google.com
​
# 使用-O保持远程文件名
curl -O http://google.com/index.html

跟踪重定向

有时,URL会重定向到另一个地址。默认情况下,curl不会跟踪重定向。使用-L选项可以开启重定向跟踪:

curl -L http://bit.ly/2JkzWjG

显示响应头信息

使用-I或--head选项可以只获取响应头信息:

curl -I http://www.google.com

发送GET请求

默认情况下,curl发送GET请求。也可以显示指定:

curl -X GET http://www.google.com

发送POST请求

使用-d选项可以发送POST请求:

curl -X POST -d "param1=value1&param2=value2" http://httpbin.org/post

也可以从文件读取POST数据:

curl -X POST -d @data.txt http://httpbin.org/post

发送JSON数据

使用-H选项指定内容类型,发送JSON数据:

curl -X POST -H "Content-Type: application/json" -d '{"key1":"value1","key2":"value2"}' http://httpbin.org/post

三、高级应用

设置HTTP请求头

使用-H选项可以设置HTTP请求头:

curl -H "Accept: application/json" -H "Content-Type: application/json" http://httpbin.org/get

处理Cookies

curl可以处理Cookies。保存Cookies到文件:

curl -c cookies.txt http://httpbin.org/cookies/set?name=value

从文件读取Cookies并发送:

curl -b cookies.txt http://httpbin.org/cookies

认证

curl支持多种认证方式:

基本认证

使用-u选项进行基本认证:

curl -u username:password http://httpbin.org/basic-auth/username/password
Bearer Token认证

使用-H选项添加Authorization头:

curl -H "Authorization: Bearer <token>" http://httpbin.org/bearer

上传文件

使用-F选项上传文件:

curl -F "file=@/path/to/file" http://httpbin.org/post

限制带宽

使用--limit-rate选项限制带宽:

curl --limit-rate 100K http://example.com

设置超时

使用--connect-timeout和--max-time设置连接和总超时:

curl --connect-timeout 10 --max-time 20 http://www.example.com

使用代理

使用-x选项通过代理发送请求:

curl -x http://proxy.example.com:8080 http://www.example.com

断点续传

使用-C选项从断点续传:

curl -C - -o file.zip http://www.example.com/file.zip

静默模式

使用-s选项启用静默模式,不显示进度和错误信息:

curl -s http://www.example.com

打印调试信息

使用-v选项打印详细的调试信息:

curl -v http://www.example.com

使用多个URL

可以同时请求多个URL:

curl -O http://www.example.com/file1 -O http://www.example.com/file2

使用元数据

使用--write-out选项打印元数据,例如响应时间:

curl -w "Time: %{time_total}\n" -o /dev/null/ -s http://www.example.com

发送自定义方法

使用-X选项发送自定义HTTP方法:

curl -X DELETE http://www.example.com/resource

发送多部分表单数据

使用-F选项发送多部分表单数据:

curl -F "name=John" -F "file=@/path/to/file" http://httpbin.org/post

使用配置文件

将常用选项保存到配置文件:

# .curlrc 或 _curlrc
user = "username:password"
proxy = "http://proxy.example.com:8080"

使用配置文件:

curl -K config.txt http://www.example.com

执行脚本

curl可以与其他命令结合使用。例如,从GitHub API获取信息并处理:

curl -s https://api.github.com/repos/curl/curl | jq '.description'

四、实践案例

1. 检查网站状态

定期检查网站状态,并将结果写入日志文件:

#/bin/bash
URL="http://www.example.com"
LOGFILE="/var/log/website_status.log"
STATUS=$(curl -o /dev/null -s -w "%{http_code}\n" $URL)
echo "$(date): $STATUS" >> $LOGFILE

2. 监控网页内容变化,并发送邮件通知:

#/bin/bash
URL="http://www.example.com"
CHECKSUM_FILE="/var/tmp/webpage_checksum"
CURRENT_CHECKSUM=$(curl -s $URL | md5sum)
if [ -f $CHECKSUM_FILE ];then
	PREVIOUS_CHECKSUM=$(cat $CHECKSUM_FILE)
	if [ "$CURRENT_CHECKSUM" != "$PREVIOUS_CHECKSUM" ];then
		echo "Webpage has changed" | mail -s "Webpage Change Alert" user@eaxmple.com
	fi
fi
echo $CURRENT_CHECKSUM > $CHECKSUM_FILE

3. 自动下载文件

定期从FTP服务器下载文件:

#!/bin/bash
FTP_URL="ftp://user:password@ftp.example.com/file.txt"
LOCAL_DIR="/var/tmp"
curl -o $LOCAL_DIR/file.txt $FTP_URL

4. API调用脚本

从API获取数据并存储到数据库:

#!/bin/bash
API_URL="http://api.example.com/data"
DB_HOST="localhost"
DB_USER="user"
DB_PASS="password"
DB_NAME="database"
DATA=$(curl -s $API_URL)
mysql -h $DB_HOST -u $DB_USER -p$DB_PASS $DB_NAME -e "INSERT INTO table (date) VALUES ('$DATA')";

5. 批量处理和并行下载

利用curl的并行处理功能和xargs命令,可以同时下载多个文件,从而提高下载效率:

# urls.txt 中包含要下载的URL列表
cat urls.txt | xargs -n 1 -P 10 curl -O

6. RSET API自动化

编写一个脚本,自动从RSET API获取数据,并根据结果进行进一步处理,例如发送通知或存储到数据库:

#!/bin/bash

API_URL="https://api.example.com/data"
NOTIFICATION_EMAIL="user@example.com"
DB_HOST="localhost"
DB_USER="dbuser"
DB_PASS="dbpass"
DB_NAME="dbname"

# 获取数据
response=$(curl -s $API_URL)
status_code=$(echo $response | jq -r '.status_code')

if [ "$status_code" -eq 200 ];then
	# 处理数据
	data=$(echo $response | jq -r '.data')
	
	# 存储到数据库
	mysql -h $DB_HOST -u $DB_USER -p$DB_PASS $DB_NAME << EOF
	INSERT INTO data_table (data_column) VALUES ('$data');
EOF

	# 发送通知
	echo "Data fetched and sorted successfully" | mail -s "API Data Notification" $NOTIFICATION_EMAIL
else
	echo "Failed to fetch data. Status code: $status_code" | mail -s "API Data Notification" $NOTIFICATION_EMAIL
fi

7. 使用OAuth2进行认证的API调用

有些API需要OAuth2认证,这里是一个获取Access Token并使用它进行API调用的示例。

获取Access Token

curl -X POST "https://auth.example.com/oauth/token" \
		 -H "Content-Type: application/x-www-form-urlencoded" \
		 -d "grant_type=client_credentials&client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET"

使用Access Token调用API

ACCESS_TOKEN = "YOUR_ACCESS_TOKEN"

curl -H "Authorization: Bearer $ACCESS_TOKEN" \
		 -H "Accept: application/json" \
		 "https://api.example.com/protected/resource"

8. 使用GraphQL API

与REST API不同,GraphQL需要发送一个查询请求,这里是一个使用curl调用GraphQL API的示例:

curl -X POST "https://api.example.com/graphql" \
		 -H "Content-Type: application/json" \
		 -d '{
		 				"query": "{user(id:"1") {name email}}"
		 }'

9. 自动化日志转换

使用curl和Cron作业定期上传日志文件并归档:

脚本:upload_logs.sh

#!/bin/bash

LOG_FILE="/var/log/myapp.log"
ARCHIVE_DIR="/var/log/achive"
REMOTE_SERVER="user@backup.example.com:/backups/logs"

# 归档日志文件
timestamp=$(date +"%Y%m%d%H%M%S")
cp $LOG_FILE $ARCHIVE_DIR/myapp.log.$timestamp

# 清空当前日志文件
> $LOG_FILE

# 上传归档文件
curl -T $ACHIVE_DIR/myapp.log.$timestamp sftp://$REMOTE_SERVER

# 删除旧的归档文件(超过30天)
find $ACHIVE_DIR -type f -mtime +30 -exec rm {} ;

添加到Cron作业

0 0 * * * /path/to/upload_logs.sh

10. 与Slack集成

使用curl向Slack发送消息。此例子展示了如何通过Webhook向Slack频道发送通知:

WEBHOOK_URL="https://hooks.slack.com/service/T00000000/B00000000/XXXXXXXXXXXXXXXX"
MESSAGE="Hello, this is a test message from curl!"

curl -X POST -H 'Content-Type: application/json' --data '{"text":"'"$MESSAGE"'"}' $WEBHOOK_URL

11. 多阶段API调用与数据处理

从多个API获取数据,合并处理后保存到文件系统:

脚本:multi_stage_api_call.sh

#!/bin/bash

API_URL1="https://api.example.com/data1"
API_URL2="https://api.example.com/data2"
OUTPUT_FILE="/path/to/output.json"

# 获取数据
response1=$(curl -s $API_URL1)
response2=$(curl -s $API_URL2)

# 合并数据
combined_data=$(jq -s '.[0] * .[1]' <(echo $response1) <(echo $response2))

# 保存到文件
echo $combined_data > $OUTPUT_FILE

# 打印结果
echo "Data saved to $OUTPUT_FILE"

12. 下载并解压缩文件

下载压缩文件并自动解压缩到指定目录。

脚本:download_and_unzip.sh

#!/bin/bash

FILE_URL="https://example.com/file.zip"
DEST_DIR="/path/to/destination"

# 下载文件
curl -O /tmp/file.zip $FILE_URL

# 解压缩文件
unzip /tmp/file.zip -d $DEST_DIR

# 删除文件
rm /tmp/file.zip

# 打印结果
echo "File downloaded and extracted to $DEST_DIR"

13. 自动备份和恢复数据

使用curl从远程服务器下载备份文件并恢复数据。

脚本:backup_and_restore_db.sh

#!/bin/bash

BACKUP_URL="https://backup.example.com.cn/db_backup.sql"
DB_HOST="localhost"
DB_USER="dbuser"
DB_PASS="dbpass"
DB_NAME="dbname"

# 下载备份文件
curl -o /tmp/db_backup.sql $BACKUP_URL

# 恢复数据库
mysql -h $DB_HOST -u $DB_USER -p$DB_PASS $DB_NAME < /tmp/db_backup.sql

# 删除临时文件
rm /tmp/db_backup.sql

# 打印结果
echo "Database restored from backup"

14. 监控网站性能

定期监测网站响应时间,并记录到日志文件中。

脚本:monitor_website_performance.sh

#!/bin/bash

URL="http://www.example.com"
LOGFILE="/var/log/website_performance.log"

# 获取响应时间
response_time=$(curl -o /dev/null -s -w "%{time_total}\n" $URL)

# 记录到日志文件
echo "$(date): $response_time" >> $LOGFILE

添加到Cron工作

*/5 * * * * /path/to/monitor_website_performance.sh

五、总结

curl是一个功能强大的命令行工具,适用于多种数据传输任务、无论是简单的网页抓取,还是复杂的API交互,curl都能轻松应对。通过掌握curl的基本用法和高级技巧,可以在多种场景中灵活应用这一工具,提高工作效率。

更多技术分享,关注公众号:halugin