简体   繁体   English

如何使用 Python 读取列和行并遍历条目?

[英]How to read column and rows with Python and iterate through the entries?

I have a CSV file with the host addresses in the column, and the ports for them in the rows, I would like to go through the columns and then scan for the corresponding ports in the row.我有一个 CSV 文件,列中有主机地址,行中有它们的端口,我想通过列 go 然后扫描行中的相应端口。

I've come up with this code, this works if I manually use the cell with host IP and port.我想出了这段代码,如果我手动使用带有主机 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)

Sample CSV样品 CSV

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

Thank you!谢谢!

First skip over you header using next() .首先使用next()跳过你 header 。 Then you can read each row by first taking the ip address and then reading all other entries as ports using Python's * operator.然后,您可以通过首先获取ip地址然后使用 Python 的*运算符将所有其他条目作为ports读取来读取每一行。 For example:例如:

For example:例如:

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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM