Discover network hosts

0

When trying to create a script about the subject I had some doubts about the script below! The question is, how am I going to do the "for i in 100" so that it pings the ips, like so 192.168.0.1/192.168.0.2/.../.../192.168.0.100.

Code:

import os

os.system('clear')
ip = int(input('IP INICIAL (192.168.0.1); '))
print ('Testing...')
for i in 100:
    rs = os.system('ping -c1', ip, +i)
    if rs == 0:
        print ('O', ip, 'ta on')

Error:

> IP INICIAL (192.168.0.1); 192.168.2.0

Traceback (most recent call last):
  File "/root/redes/redes.py", line 4, in <module>
    ip = int(input('IP INICIAL (192.168.0.1); '))
  File "<string>", line 1
    192.168.2.0
            ^
SyntaxError: invalid syntax
    
asked by anonymous 24.02.2018 / 06:21

1 answer

2

You can not read ip as integer because it has several . in the middle, which is actually the error that appears in the image you placed.

The easiest thing is to treat ip as a list of integers. And for this you can use the split function of string that separates into multiple values using a separator. In your case it is important to use . as a separator.

ip = input('IP INICIAL (192.168.0.1); ').split('.')

See how it's interpreted

>>> ip = input('IP INICIAL (192.168.0.1); ').split('.')
IP INICIAL (192.168.0.1); 192.168.1.1
>>> ip
['192', '168', '1', '1']

Each part of ip is not actually a number but a string , however, it has no relevance to what you are doing that is to replace the last block dynamically. Now we are at the point of building the for you want:

import os

os.system('clear')
ip = input('IP INICIAL (192.168.0.1); ').split('.')
print ('Testing...')
for i in range(1,101): # faltou range aqui
    ip[3] = str(i) # mudar a ultima parte do ip para o numero como string
    ip_formatado = '.'.join(ip) # criar o texto que representa o ip
    rs = os.system('ping -c 1 {}'.format(ip_formatado)) # executar o comando com o ip certo
    if rs == 0:
        print ('O {} ta on'.format(ip_formatado))

Note that you had the command with -c1 together when it was supposed to be separated by space.

I built the ip text back using the join function with ip_formatado = '.'.join(ip) , which greatly simplifies. Here's an example of this part just working:

>>> ip = ['192', '168', '1', '1']
>>> ip
['192', '168', '1', '1']
>>> '.'.join(ip)
'192.168.1.1'
    
24.02.2018 / 11:04