尝试在Python 3.6中执行与此Powershell脚本类似的操作:
$apiKey = "key-example"
$HostPA = "https://ip-address"
$file = "addressObjects.csv"
$addressObject = Import-Csv $file
foreach($line in $addressObject)
{
$name = $line.name
$ip = $line.ip_netmask
Invoke-WebRequest "$HostPA/api/?type=config&action=set&xpath=/config/devices/entry[@name='localhost.localdomain']/vsys/entry[@name='vsys1']/address/entry[@name='$name']&element=$ip&key=$apikey"
}
这将采用列(Excel样式)CSV文件并将每一行传递给API请求。
我已经将API请求部分关闭了(在PowerShell中无法工作的部分),但不是foreach语句。我尝试了一些东西,却无处可去。
到目前为止这是有效的:
apiKey = 'key-example'
HostPA = 'ip-address'
import csv
File = open('addressObjects.csv')
File_Reader = csv.reader(File, delimiter=',')
import requests
r = requests.get(HostPA + "/api/?type=config&action=set&xpath=/config/devices/entry[@name='localhost.localdomain']/vsys/entry[@name='vsys1']/address/entry[@name='" + name + "']&element=" + ip + "&key=" + apiKey, verify=False)
with open("results.xml", "wb") as f: f.write(r.text.encode("utf-8"))
例如,如果我有这样的CSV文件:
name, ip
test, 8.8.8.8
test2, 8.8.4.4
我想把每一行都分配给一个变量,该变量将转到" requests.get"中的相应位置。 URL
第一行将翻译"
HostPA + "/api/?type=config&action=set&xpath=/config/devices/entry[@name='localhost.localdomain']/vsys/entry[@name='vsys1']/address/entry[@name='" + name + "']&element=" + ip + "&key=" + apiKey
进入这个:
https://HostIP/api/?type=config&action=set&xpath=/config/devices/entry[@name='localhost.localdomain']/vsys/entry[@name='vsys1']/address/entry[@name='test']&element=8.8.8.8&key=Somekey
然后遍历其他行
我的问题与提议的副本不同:loop through rows of one csv file to find corresponding data in another
此问题要求匹配两个CSV文件之间的数据。 CSV格式与我的相同。我的问题是要求采用圆柱形CSV数据并循环遍历每一行,从每个行创建一个变量,因此我可以将其推送到单独的API调用中。
任何帮助,将不胜感激。 :)
编辑:
这是我的解决方案:
apiKey = 'MyKey'
HostPA = 'https://IP'
import requests
import csv
filereader = csv.reader(open('C:/addressObjects.csv'), delimiter=',') #import csv
header = filereader.__next__()
#Header names
for name, ip in filereader:
(print(name, ip))
r = requests.get(HostPA + "/api/?type=config&action=set&xpath=/config/devices/entry[@name='localhost.localdomain']/vsys/entry[@name='vsys1']/address/entry[@name='" + name + "']&element=<ip-netmask>" + ip + "</ip-netmask>&key=" + apiKey, verify=False) #API call
print(r.text) #Check API results