安装
centos下安装pycurl,如果直接使用pip install pycurl
的话,可能会有ERROR: Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-install-hb0k0rkr/pycurl/
的错误,那么需要先安装一下yum install python-devel curl-devel
就解决问题了。
如果是windows下安装pycurl就比较麻烦一点,需要先pip install wheel
安装wheel,然后去http://www.lfd.uci.edu/~gohlke/pythonlibs/ 下载对应python版本的编译包到本地,然后在cmd命令行里pip install 对应的.whl
就好了。但是注意http://www.lfd.uci.edu/~gohlke/pythonlibs/ 是需要翻墙登录的。
python3脚本
pycurl的常用的常量列表可以看一下https://izsk.me/2017/12/27/%E4%BD%BF%E7%94%A8python%E5%BA%93pycurl%E6%9D%A5%E6%A3%80%E6%B5%8Bweb%E6%9C%8D%E5%8A%A1%E8%B4%A8%E9%87%8F/ 这个文章,我这里就直接写一下我的脚本:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21import pycurl
import sys
c = pycurl.Curl()
url = 'http://X.X.X.X:对应端口号'
c.setopt(c.URL, url)
c.setopt(c.HEADER, True)
c.setopt(pycurl.CONNECTTIMEOUT, 5) # 连接的等待时间,设置为0则不等待
c.setopt(pycurl.TIMEOUT, 5) # 请求超时时间
c.getinfo(pycurl.HTTP_CODE) # 返回的HTTP状态码
#c.setopt(c.POST,1) #是否是post,默认是get
try:
c.perform() #提交请求
except Exception as e:
print("连接异常!" + str(e))
c.close()
sys.exit()
HTTP_CODE = c.getinfo(c.HTTP_CODE) #获取 HTTP 状态码
print('HTTP状态码: %s' %(HTTP_CODE))
c.close()
不过pycurl有两个缺点,第一,整个请求头都会输出;第二,无法摘取到http协议版本号。
GO脚本
如果是想用go语言来实现curl效果,脚本如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54package main
import (
"fmt"
"github.com/mikemintang/go-curl"
)
func main() {
url := "http://目标路径:目标端口"
headers := map[string]string{
"User-Agent": "Sublime",
"Authorization": "Bearer access_token",
"Content-Type": "application/json",
}
cookies := map[string]string{
"userId": "12",
"loginTime": "15045682199",
}
queries := map[string]string{
"page": "2",
"act": "update",
}
postData := map[string]interface{}{
"name": "mike",
"age": 24,
"interests": []string{"basketball", "reading", "coding"},
"isAdmin": true,
}
// 链式操作
req := curl.NewRequest()
resp, err := req.
SetUrl(url).
SetHeaders(headers).
SetCookies(cookies).
SetQueries(queries).
SetPostData(postData).
Post()
if err != nil {
fmt.Println(err)
} else {
if resp.IsOk() {
fmt.Println(resp.Body)
} else {
fmt.Println(resp.Raw)
}
}
}
上述脚本执行效果:
参考资料
http://pycurl.io/docs/latest/index.html (官方文档)
https://www.twilio.com/blog/2016/12/http-requests-in-python-3.html
https://stackoverflow.com/questions/472179/how-to-read-the-header-with-pycurl