Increment in Python list

Asked

Viewed 507 times

3

Hello,

I am creating a script to do automatic logins on equipment. I have created a list with several Ips that are the equipment I want to access. I want to create a loop, I tried with while and for, but I couldn’t.

Each loop in the loop it must execute the commands to access them, but I am not able to increase the position of the list, so that in the next round, the IP of the next position is called.

lista = ['11.111.111.111','22.222.222.222','3.333.333.333']
ip = lista[0]
while lista != 44.444.444.44:
    username = raw_input("Username:")
    password = getpass.getpass("Password: ")
    remote_conn_pre = paramiko.SSHClient()
    remote_conn_pre.set_missing_host_key_policy(paramiko.AutoAddPolicy()) 
    remote_conn_pre.connect(ip, username=username, password=password)
    remote_conn = remote_conn_pre.invoke_shell()
    output = remote_conn.recv(5000)

Can you help me? Thank you!

2 answers

4


If you just want to increment (my Chará) is very simple. Use the famous for:

lista = ['11.111.111.111','22.222.222.222','3.333.333.333']
for ip in lista:
    # faz suas operações com a variável ip
    remote_conn_pre.connect(ip, username=username, password=password)
    # ... demais operações

The variable ip will update its value by iterating the list elements.

  • 1

    Thank you very much Thank you, both for the reply and for the editing suggestions. I am new on the site and was of great help, thank you!

  • Come on, buddy, you’re welcome! :)

0

There are several problems with this code. I consider that maybe you are imagining a way Python works that does not exist.

The solution involves iterating your IP list as follows:

lista = ['11.111.111.111','22.222.222.222','3.333.333.333']

# ip = lista[0] # Isto não precisa

for ip in lista:
    username = raw_input("Username:")   
    password = getpass.getpass("Password: ")
    remote_conn_pre = paramiko.SSHClient()     
    remote_conn_pre.set_missing_host_key_policy(paramiko.AutoAddPolicy())   
    remote_conn_pre.connect(ip, username=username, password=password)
    remote_conn = remote_conn_pre.invoke_shell()    
    output = remote_conn.recv(5000)
  • 1

    That’s right Morrison, thank you for the answer! As I said above, the for - in Felipe’s reply - helped me in relation to the problem.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.