Doubt with IF and LISTS python3

Asked

Viewed 760 times

3

I’m new to the python language, but I started to develop a script to manage linux servers etc... I have a little problem in a code snippet:

def rotear():

    print(" \n Disponível: \n"), os.system("ifconfig|grep eth|cut -c 1-4")
    interface_internet = input(" \n Digite a Interface de Internet: ")
    if interface_internet != ethers[0]:
            print("Nao deu certo!")

Next, I listed the network interfaces, I put together this snippet of code, but I wanted to figure out a way to get the list of network interfaces, and make a condition true or false to proceed with the code

ex:

listed the interface with the ifconfig command | grep Eth | cut -c 1-4

eth0

eth1

if interface_internet is different from one of the above listings, do this otherwise, do that

I wanted a solution on this...

So I put the code:

def rotear():
    ethers = ['eth0','eth1','eth2','wlan0','wlan1','ath0','ath1']
    print(" \n Listando Interfaces de Rede(s)..."),time.sleep(1)
    print(" \n Disponível: \n"), os.system("ifconfig|grep eth|cut -c 1-4")
    interface_internet = input(" \n Digite a Interface de Internet: ")
    for device in ethers:
        if interface_internet == device:
            header(" \n 1 - Habilitar Roteamento")
            header(" 2 - Desabilitar Roteamento\n")
            encaminhar = input(" Escolha uma Opção de Roteamento:")
            if encaminhar == "1":
                os.system("echo 1 > /proc/sys/net/ipv4/ip_forward")
                os.system("iptables -t nat -A POSTROUTING -o %s -j MASQUERADE" % (interface_internet))
                sucess(" \n Roteamento Habilitado Com Sucesso..."),tcl()
            elif encaminhar == "2":
                os.system("echo 0 > /proc/sys/net/ipv4/ip_forward")
                sucess(" \n Roteamento Desabilitado Com Sucesso..."),tcl()
        else:
            fail(" \n Atenção: Valor Inválido. ")

only I’m in trouble, if I put the value: eth2 for example, he makes two loops, saying that the value ta invalido until right... how do I fix it now?

  • Please correct the code indentation

  • To use python for this purpose, consider using the package I suggest in my answer.

3 answers

3

To list all network interfaces, you can use the python-nmap. Take a look to find the correct command for this.
After grabbing all interfaces, put them in a list and then use a for to test conditions in each of the interfaces, something like this:

for device in ethers:
    if interface_internet == device:
        fazer X
    else:
        fazer Y

ethers will be your list with all network interfaces.
The for will loop to each interface in the list, calling it device. So he checks if the device is equal to interface_internet, and then makes the decisions.

  • Good morning Denis! Thank you very much for the Return. but I had another problem, I edited the code on top. !

1

It enters 2 times in the loop and error until finding because it is testing value by list value to see if it is equal to 'eth2'. First forehead with eth0 afterward eth1 and only then with eth2.

To check if the value is inside the list ethers you must use the reserved word in as I did in the code below, if variavel in lista:....

def rotear():
    ethers = ['eth0','eth1','eth2','wlan0','wlan1','ath0','ath1']
    print(" \n Listando Interfaces de Rede(s)..."),time.sleep(1)
    print(" \n Disponível: \n"), os.system("ifconfig|grep eth|cut -c 1-4")
    interface_internet = input(" \n Digite a Interface de Internet: ")
    if interface_internet in ethers:
        header(" \n 1 - Habilitar Roteamento")
        header(" 2 - Desabilitar Roteamento\n")
        encaminhar = input(" Escolha uma Opção de Roteamento:")
        if encaminhar == "1":
            os.system("echo 1 > /proc/sys/net/ipv4/ip_forward")
            os.system("iptables -t nat -A POSTROUTING -o %s -j MASQUERADE" % (interface_internet))
            sucess(" \n Roteamento Habilitado Com Sucesso..."),tcl()
        elif encaminhar == "2":
            os.system("echo 0 > /proc/sys/net/ipv4/ip_forward")
            sucess(" \n Roteamento Desabilitado Com Sucesso..."),tcl()
    else:
        fail(" \n Atenção: Valor Inválido. ")
  • 1

    Corrected the name. .rs... pardon Thanks Gabriel, Now it worked!! Thank you very much, then I will see a way to try to put the ifconfig command listing inside the list or lake like this. Very Grateful!

  • is Opened my name hahaha.

  • I’m glad you made it, man!

  • 1

    Correcting the Name: Thanks "Gabriel"... rsrs... sorry for the gaffe.... THANK YOU VERY MUCH.

  • @Andersonuser777, to put the result of the command ifconfig within a python list, see my answer.

  • @Sidon I’m looking at the code you just passed! Thanks so much for the help..

Show 1 more comment

1


If Voce is going to use python for infrastructure management tasks in the linux environment, my suggestion is that you do, first of all; this:

pip install plumbum

Plubum:

(tl;dr)
With this package you can run most shell commands, to answer your question, I ran a ifconfig | grep simple, just to grab the lines in which the string appears Eth, but you can compose the command you want. The result of the command is placed in a list and then... Well... I’m not gonna get too blah blah, because I explained in the code itself.

# Para execução de comandos shell
from plumbum.cmd import grep, ifconfig
from plumbum import FG, BG
# Firula
import pprint  

# Monta o comando ifconfig (ifconfig | grep Eth)
ifc = ifconfig | grep["Eth"]

# Executa o comando
f = ifc & BG
output = f.stdout

# Atribui a saida do comando a um objeto tipo lista do pyton
lst = output.splitlines()

pprint.pprint(lst)

Result of pprint:

['docker0   Link encap:Ethernet  Endereço de HW 02:42:bb:5c:52:96  ',
 'enp3s0    Link encap:Ethernet  Endereço de HW 10:c3:7b:c4:21:e4  ']

Functions for list searches:

# Pesquisa restritiva, o conteudo da variável tem que "casar" com uma linha inteira na lista
def search1(var):
    return var if var in lst else 'Não encontrado'

# Pesquisa não restritiva, basta uma substring dentro de um dos elementos da lista
def search2(var):
    result = [s for s in lst if var in s]
    return var if len(result)>0 else 'Não encontrado'

Searches on the list:

# Variável a ser pesquisada na lista
str1 = 'docker0'
str2 = 'docker0   Link encap:Ethernet  Endereço de HW 02:42:bb:5c:52:96  '

print ("REALIZANDO BUSCAS\n")
print ('Busca restritiva')
print ("str1 : ", search1(str1))
print ("str2 : ", search1(str2))
print ('\nBusca não restritiva')
print ("str1 : ", search2(str1))
print ("str2 : ", search2(str2))

Search results:

Busca restritiva
str1 :  Não encontrado
str2 :  docker0   Link encap:Ethernet  Endereço de HW 02:42:bb:5c:52:96  

Busca não restritiva
str1 :  ['docker0   Link encap:Ethernet  Endereço de HW 02:42:bb:5c:52:96  ']
str2 :  ['docker0   Link encap:Ethernet  Endereço de HW 02:42:bb:5c:52:96  ']

Using the command if:

if str1 in search1(str1):
    print ('str1 foi encontrada na busca restritiva')
else:
    print ('str1 não foi encontrada na busca restritiva')

if str2 in search1(str2):
    print ('str2 foi encontrada na busca restritiva')
else:
    print ('str2 não foi encontrada na busca restritiva')

if str1 in search2(str1):
    print ('str1 foi encontrada na busca não restritiva')
else:
    print ('str1 não foi encontrada na busca não restritiva')

if str2 in search2(str2):
    print ('str2 foi encontrada na busca não restritiva')
else:
    print ('str2 não foi encontrada na busca não restritiva')    

Output for the commands if's:

str1 não foi encontrada na busca restritiva
str2 foi encontrada na busca restritiva
str1 não foi encontrada na busca não restritiva
str2 foi encontrada na busca não restritiva  

Final consideration:
Of course the function search1(var) can be considered unnecessary if we were to consider only the restrictive search, because it would be enough to do:

if var not in lst:
   print ('Não encontrada')

But depending on the context, one can join the two functions (restrictive and non-restrictive search) in one, for flexibility and practicality gain.

See the code running on that notebook jupyter.

  • Sidon, Thank you very much man, I will study your code and try to apply it to my code. !!!!!

  • @Andersonuser777, I noticed some mistakes and I made corrections in the code, if to use the code for tests, download the notebook straight from the anaconda here.

  • Sidon, I installed the plubum with the Pip install Plum command, so far so good. but when I ran the script from plumbum.cmd import grep, ifconfig Import: No module named 'plumbum' !

  • Which version of python?

  • Blz Sidon, I’ll be downloading, Baraços...

  • Dude I’m putting my code together in python3.

  • Legal, run on command line: python -c "import plumbum; print (plumbum.__version__)" and paste the result here.

  • If the plumbum version does not appear, the installation was unsuccessful.

  • result (1, 6, 3)

  • a doubt saw that the extension of it is . ipynb as executing? Obg...

  • Install the Jupyter, and Turbine your python world. :-) pip3 install jupyter

  • 1

    There is yes Sidon, I did not know it was the extension of jupyter, never used, but I’ve seen several videos explaining about, OBG once again... hugs

Show 7 more comments

Browser other questions tagged

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