【问题标题】:How to read column and rows with Python and iterate through the entries?如何使用 Python 读取列和行并遍历条目?
【发布时间】:2021-05-26 20:39:11
【问题描述】:

我有一个 CSV 文件,列中包含主机地址,行中包含它们的端口,我想遍历列,然后扫描行中的相应端口。

我想出了这段代码,如果我手动使用带有主机 IP 和端口的单元,这将有效。


import socket
import csv

lst = [1,2,3,4,5,6,7,8,9]
 
line_number = 0

while line_number  < len(lst):
    line_number  = int(line_number +1)
    
with open('temp.csv', 'rt') as f:
    mycsv = csv.reader(f)
    mycsv = list(mycsv)
    h = mycsv[line_number][0] 
    line_number  = int(line_number +1)
while line_number  < len(lst): 
    line_number  = int(line_number +1)
with open('temp.csv', 'rt') as f:
    mycsv = csv.reader(f)
    mycsv = list(mycsv)
    p = mycsv[line_number][2] 


s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

host = h
port = int(p)

def portScanner(port):
    if s.connect_ex((host, port)):
        print("Closed")
    else:
        print("Open")

portScanner(port)

CSV 示例

ip,port 
1.1.1.1,80,443,22
2.2.2.2,80,21,22
3.3.3.3,111,22,21
.
.
.
.

谢谢!

【问题讨论】:

    标签: python python-3.x list csv for-loop


    【解决方案1】:

    首先使用next() 跳过您的标题。然后,您可以通过首先获取ip 地址然后使用Python 的* 运算符将所有其他条目读取为ports 来读取每一行。例如:

    例如:

    import csv
    import socket
    
    def portScanner(ip, port):
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        
        if s.connect_ex((ip, port)):
            print(f"  Port {port}: Closed")
        else:
            print(f"  Port {port}: Open")
    
    
    with open('temp.csv') as f_input:
        csv_input = csv.reader(f_input)
        header = next(csv_input)
        
        for ip, *ports in csv_input:
            print(f"IP: {ip}")
        
            for port in ports:
                portScanner(ip, int(port))
    

    【讨论】:

    • 感谢您的及时回复,也很抱歉在这里不清楚,我是python新手。我现在收到一个错误:ValueError: invalid literal for int() with base 10: '1.1.1.1' 我在网上看了,都建议让它浮动,但它也没有帮助。我也尝试导入 ipaddress 模块但没有成功。再次感谢您的帮助!
    • 我已经更新了解决方案,现在我可以看到您的 CSV 文件的实际格式是什么
    猜你喜欢
    • 2021-02-25
    • 1970-01-01
    • 2011-09-11
    • 2011-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-22
    • 2022-06-28
    相关资源
    最近更新 更多