Asram
Asram

Reputation: 3

How to assign a string value to each element in a list when the function iterates through the list of elements

I am a beginner, hence i want to know how to assign either a 'PASS' or a 'FAIL' value to each element in the list. The function I have below just pings the echo servers. for example if 10.10.10.5 is reachable then for example: 10.10.10.5 should be 'PASS'and 'FAIL' when it is not reachable, if 192.168.11.10 is not reachable the same process repeats.

I have seperate columns in a MariaDB database for each of the ip addresses and they need to get logged if it is 'PASS' or 'FAIL'.

This means i need to assign pass or fail to each IP address right? Could someone please show me an example of how this could be done please.

Here is what I have:

def echo_ping(self, echo_ip):
        
        self.echo_ping_reply = subprocess.run(["ping","-n","2", echo_ip],stderr=subprocess.PIPE, stdout=subprocess.PIPE) # windows
        self.echo_result =""
        print (".", end='')
        
        if self.echo_ping_reply.returncode == 0:
            
            if ("unreachable" in str(self.echo_ping_reply.stdout)):
                self.echo_result = ("\n* No response from device %s" % echo_ip)
            else:
                self.echo_result= ("\n* OK response from device %s" % echo_ip)
        elif self.echo_ping_reply.returncode == 1:
            self.echo_result= ("\n* No response from device %s" % echo_ip)
        return self.echo_result

def ping_all_va(self):
        self.ips = ["10.10.10.2",'192.168.11.1', '192.168.12.2', '192.168.13.3', '192.168.14.4']
        for echo_ip in self.ips:
            print(self.echo_ping(echo_ip))
Ping().ping_all_va()



        insert_query = f"""INSERT INTO db_ServerEcho(,
        Ethernet_Port_1,Ethernet_Port_2,E_port_3,Ethernet_Port_4,Ethernet_Port_5,)VALUES ( '{10.10.10.2 pass or fail variable comes here}', '{192.168.11.1 pass or fail variable comes here and so on...}', '-', '-', '-', '-')"""
        cur.execute(insert_query)
    
        print(f"{cur.rowcount} row of data inserted to the Database")
        conn.commit()

Upvotes: 0

Views: 44

Answers (1)

Aditya Tripathi
Aditya Tripathi

Reputation: 36

There are two ways out of this problem. The best one of them is use a dictionary. Why I'm saying this to be best us you can access the connection results using the ip addresses. Example- conn_results = {"ip1":"pass", "ip2":"fail}

To print the results of ip1 it's quite easy print(conn_results["ip1"])

Else you can use a nested list(list in a list) and use indices to access ip and result. Example- Conn_results = [["ip1", "ip2"], ["pass", "fail"]] Now to print the results of ip1 you need to use indexing

print(f"{Conn_results[1][0]}")

1st method is quite clean and easy for use, but nested list is a bad idea as it's quite messy for handling as well as accessing. Hope this helps you.

Upvotes: 1

Related Questions