【发布时间】:2021-10-11 21:06:01
【问题描述】:
我正在尝试将从RestApi URL 返回的响应写入csv 文件,用于提供port number(交互模式)和选定用户users_list.txt(脚本模式)。我有下面的代码来完成这项工作。
import json
import csv
import urllib.request
import subprocess
portvalue = input("Please enter an Port Number:\n")
portvalue = int(portvalue)
print(f'You entered {portvalue}')
tooluser='admin'
toolpassword='password'
user = open('users-list.txt')
for line in user:
bash_com = 'curl --user {tooluser}:{toolpassword} http://198.98.99.12:46567/{portvalue}/protects/{user} \
| jq --arg a_port {portvalue} --arg a_userid {user} 'map(.+{"userid":{user}}+{"port":{portvalue}})'' as url:
subprocess.Popen(bash_com)
output = subprocess.check_output(['bash','-c', bash_com])
print(line)
myfile.close()
# with urllib.request.urlopen("curl --user admin:password http://198.98.99.12:46567/{port}/protects/{user} | jq") as url:
data = json.loads(url.read().decode())
fname = "output.csv"
with open(fname, "w") as file:
csv_file = csv.writer(file,lineterminator='\n')
csv_file.writerow(["depotFile","host","isgroup","line","perm","user","port","userid"])
for item in data["raw_data"]:
csv_file.writerow([item['depotFile'],item['host'],item['isgroup'],item['line'],item['perm'],item['user'],item['port'],item['userid']])
使用 URL 获取单个用户的数据 - curl --user admin:password http://198.98.99.12:46567/2324/protects/sanchez.ricardo | jq
users_list.txt 由以下格式的用户组成。
sanchez.ricardo
varun.sharma
daniel.vel
json输出格式之一如下,
[
{
"depotFile": "//LIB/Include/...",
"host": "*",
"isgroup": "",
"line": "19",
"perm": "open",
"user": "5G",
"port": "2324",
"userid": "sanchez.ricardo"
},
....
......
.........
]
预期的输出 csv 文件:-
Sno depotFile host isgroup line perm user port userid
1 //LIB/Include/... * 19 open 5G 2324 sanchez.ricardo
2 //LIB/... * 19 write 6G 2324 varun.sharma
3 //AND/RIO/... * 20 write AND 2324 daniel.vel
我无法处理上述代码中的RestApi URl。请帮助我在 python 中实现这一点。提前感谢您的帮助。
【问题讨论】:
-
如果您仍然需要这方面的帮助,您能否添加一个包含两个用户的用户列表示例文件,以及您为获取两个用户的 csv 所点击的实际 url?
-
@ Brian Z,是的,我仍在寻求帮助。我在问题中添加了
userlist文件和实际url信息。请看看并帮助我。
标签: python json python-3.x csv rest