使用curl向MongoDB插入数据报错curl: (52) Empty reply from server求助
问题:通过curl HTTP POST向MongoDB插入数据失败,返回Empty reply from server
我编写了如下bash脚本,用于从/etc/passwd文件中提取UID≥500的用户信息,并尝试通过curl以HTTP POST方式插入远程MongoDB(地址172.16.10.10:27017):
#!/bin/bash # Set the MongoDB connection information mongo_host="172.16.10.10" mongo_port="27017" mongo_db="user_info_remote" mongo_collection="user_info" # Extract user information from /etc/passwd for users with UID greater than 500 and insert it into MongoDB awk -F: '$3>=500 {print "{\"username\":\""$1"\",\"uid\":"$3",\"gid\":"$4",\"home\":\""$6"\",\"shell\":\""$7"\"}"}' /etc/passwd \ | while read user_info; do curl -vvv -i -H "Content-Type: application/json" -X POST -d "$user_info" "http://$mongo_host:$mongo_port/$mongo_db/$mongo_collection" done # Echo a message to the console echo "User information stored in MongoDB"
执行脚本后出现以下错误日志:
* Trying 172.16.10.10.. * TCP_NODELAY set * Connected to 172.16.10.10 (172.16.10.10) port 27017 (#0) \> POST /user_info_remote/user_info HTTP/1.1 \> Host: 172.16.10.10:27017 \> User-Agent: curl/7.61.1 \> Accept: */* \> Content-Type: application/json \> Content-Length: 86 \> * upload completely sent off: 86 out of 86 bytes * Empty reply from server * Connection #0 to host 172.16.10.10 left intact curl: (52) Empty reply from server
脚本最后输出"User information stored in MongoDB",但数据并未插入成功。我是MongoDB新手,已确认MongoDB配置文件绑定所有IPv4地址,且通过telnet和curl验证端口27017可正常连通:
curl -vv telnet://172.16.10.10:27017 * Rebuilt URL to: telnet://172.16.10.10:27017/ * Trying 172.16.10.10... * TCP_NODELAY set * Connected to 172.16.10.10 (172.16.10.10) port 27017 (#0)
解决方法
核心原因
MongoDB的27017端口使用的是自有二进制协议,并不支持HTTP协议。你用curl发送HTTP请求到该端口,MongoDB无法解析请求内容,因此返回空响应。
正确实现方案
1. 使用MongoDB官方mongoimport工具(推荐)
mongoimport是MongoDB自带的数据导入工具,专门适配MongoDB协议,能直接处理JSON格式数据。修改后的脚本如下:
#!/bin/bash # Set the MongoDB connection information mongo_host="172.16.10.10" mongo_port="27017" mongo_db="user_info_remote" mongo_collection="user_info" # 提取用户信息并通过mongoimport批量导入 awk -F: '$3>=500 {print "{\"username\":\""$1"\",\"uid\":"$3",\"gid\":"$4",\"home\":\""$6"\",\"shell\":\""$7"\"}"}' /etc/passwd \ | mongoimport --host "$mongo_host" --port "$mongo_port" --db "$mongo_db" --collection "$mongo_collection" --jsonArray # 检查导入结果并输出提示 if [ $? -eq 0 ]; then echo "用户信息已成功存储到MongoDB" else echo "用户信息存储到MongoDB失败" fi
--jsonArray参数用于告知mongoimport输入内容是多行JSON对象组成的集合,确保工具正确解析数据。- 如果远程MongoDB开启了认证,需要在
mongoimport命令中添加--username <用户名>和--password <密码>参数。
2. 启用MongoDB HTTP接口(不推荐)
旧版本MongoDB支持通过HTTP接口访问,但该功能已被官方废弃,存在安全和性能隐患。若需临时测试,可在启动MongoDB时添加--rest参数,但不建议用于生产环境。
额外检查项
- 确认远程MongoDB的
net.bindIp配置已允许你的客户端IP连接。 - 若开启了权限认证,确保使用的账号拥有目标数据库和集合的写入权限。
内容的提问来源于stack exchange,提问作者Tahmid Ul Muntakim
相关产品推荐
相关产品推荐

