简体   繁体   中英

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.

I've come up with this code, this works if I manually use the cell with host IP and port.


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

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() . Then you can read each row by first taking the ip address and then reading all other entries as ports using Python's * operator. 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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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