2013-03-11 298 views
-1

我想遍歷一個導入的.csv文件並將列中的每個值賦給變量。想法是使用該變量來搜索Shodan API,將搜索結果打印到屏幕上,然後轉到列中下一行的值,將其分配給變量,執行搜索等操作上。迭代字典值,分配給變量

下面是我從我迄今發現拼湊起來....

import csv 

# Initialize the API 
from shodan import WebAPI 
api = WebAPI("My Shodan Key") 

# Open csv file 

with open('C:\pythonfiles\sccm.csv', 'rb') as reader: 
    sccmtable = csv.reader(reader, delimiter=';') 
    #for row in sccmtable: 
    #print ', '.join(row) 

for row in sccmtable: 
    for value in row: 
     edbresults = api.exploitdb.search(value) 
     print (edbresults) 

看來,如果這是正確的開始,因爲我可以打印新導入的內容CSV到屏幕上,但我不知道如何採取下一步。任何幫助是極大的讚賞。

此致敬禮。

+0

您是否收到錯誤?它是什麼?你想搜索每一行中的每個值,還是每行搜索所有的值? 'row'是一個值列表,我只是猜測'api.exploitdb.search'需要一個字符串,而不是一個字符串列表。 – shx2 2013-03-12 06:17:55

+0

@ shx2感謝您的回覆。你是正確的,'api.exploitdb.search'需要一個字符串,我不知道'row'是一個值列表。我想單獨搜索每一行中的每個值。謝謝你的幫助。 – user2145207 2013-03-12 13:47:28

回答

1

爲了單獨搜索每個行中的每個值,這樣做:

for row in reader: 
    for value in row: 
     edbresults = api.exploitdb.search(value) 
     print (edbresults) 
+0

再次感謝!我插入你提供的內容,並且出現以下錯誤:''ValueError:關閉文件上的I/O操作'我的大腦現在正處於工作狀態很長時間,所以我明天可以做更多的研究就我自己而言,這是什麼原因造成的。有任何想法嗎? – user2145207 2013-03-12 20:18:14

+0

我在Google-fu之後發現了這一點:「在這裏注意類似文件的行爲是很重要的,請注意,寫入操作返回到開頭並讀取之後,需要執行seek。嘗試兩次運行相同的迭代器結果在第二次通過時沒有值 '''StringIO.getvalue()''返回一個新創建的字符串對象,其中包含StringIO緩衝區的全部內容。「你認爲這種方法會有幫助嗎? – user2145207 2013-03-12 20:25:48

+0

請修正您的原始問題中的縮進,幷包含您收到錯誤的完整追溯。這可以幫助您更輕鬆地找到解決方案。 – shx2 2013-03-12 20:35:09

0

關於你提到的第二個問題,當你with聲明超出範圍,你的文件被關閉。您仍然需要在範圍內閱讀其內容。簡單地縮進。

with open('C:\pythonfiles\sccm.csv', 'rb') as reader: 
    sccmtable = csv.reader(reader, delimiter=';') 
    #for row in sccmtable: 
    #print ', '.join(row) 

    for row in sccmtable: 
     for value in row: 
      edbresults = api.exploitdb.search(value) 
      print (edbresults) 
+0

謝謝!它現在似乎在工作。我的CSV有375行,每行都包含一個應用程序的名稱。當我運行腳本時,前四個將不返回結果。第五是一個好的命中,並返回良好的搜索結果,然後下兩個沒有結果。然後有東西爆炸。 – user2145207 2013-03-12 21:26:30

+0

Traceback(最近一次調用最後一次): 文件「build:」文件「build:文件」C:\ Users \ wilsond \ workspace \ Desktop Patching Lookup \ ModuleOne.py「,第22行,在 edbresults = api.exploitdb.search \ bdist.win32 \ egg \ shodan \ api.py「,第105行,搜索 文件」build \ bdist.win32 \ egg \ shodan \ api.py「,第159行,在_request中 文件」C:\ Python27 \ lib \ urllib2.py「,第126行,在urlopen 返回_opener。打開(url,data,timeout) 文件「C:\ Python27 \ lib \ urllib2.py」,第406行,打開 response = meth(req,response) – user2145207 2013-03-12 21:27:28

+0

文件「C:\ Python27 \ lib \ urllib2.py 「,第519行,http_response 'http',請求,響應,代碼,msg,hdrs) 文件」C:\ Python27 \ lib \ urllib2.py「,第444行,錯誤 返回self._call_chain(* args ) 在_call_chain中的文件「C:\ Python27 \ lib \ urllib2.py」,第378行 result = func(* args) http_error_default中的文件「C:\ Python27 \ lib \ urllib2.py」,第527行 引發HTTPError(req.get_full_url(),code,msg,hdrs,fp) urllib2.HTTPError:HTTP錯誤503:服務暫時不可用 – user2145207 2013-03-12 21:28:16