Doubt with IF and LISTS python3

2

I am new to the python language, but I started developing a script to manage linux servers etc ... I have a problem with a snippet of code:

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 mounted this snippet of code, but I wanted to figure out how to get the list of network interfaces, and make a true or false condition to proceed with the code

ex:

  

I've listed the interface with ifconfig | 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. ")

I'm just having a problem, if I put the value: eth2 for example, it makes two loops, saying that the value is invalid until it hits ... How do I resolve this now?

    
asked by anonymous 21.06.2017 / 05:36

3 answers

2

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

pip install plumbum

Plubum:

( tl; dr )
With this package you can execute most shell commands, to answer your question, I executed a ifconfig | grep simple, only to get the lines in which the string Eth appears, but you can compose the command you want. The result of the command is placed in a list and then ... Well ... I will not be bla bla bla much, so I explained no own code.

# 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  ']

Search functions in the list:

# 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'

List Searches:

# 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 to 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 search1(var) function can be considered unnecessary if we were to consider only the restrictive search, since it would suffice to do:

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

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

View the code running on this jupyter notebook.

    
21.06.2017 / 18:03
3

To list all network interfaces, you can use python-nmap . Take a search to find the right command for this.
After grabbing all the interfaces, put them in a list and then use for to test conditions on 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 . Then he checks if device is equal to interface_internet , and there he makes the decisions.

    
21.06.2017 / 12:23
1

He enters the loop twice and the error until he finds out why he is testing value by list value to see if he is equal to 'eth2' . First test with eth0 after eth1 and only then with eth2 .

To check if the value is within the ethers list 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. ")
    
21.06.2017 / 17:16