Discover hosts from the network

Asked

Viewed 939 times

0

When trying to create a script on the subject I got some questions about the script below! The question is, how am I going to do the "for i in 100" so that it will ping the ips, like 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
  • For those who voted to close, this question in its last incarnation is a question of how to use the [tag:Python] to do an action, so it is in the scope

1 answer

2


You cannot read the ip as whole because it has several . by the means, which is actually the error that appears in the image you placed.

The easiest is to even treat ip as an integer list. And for that you can use the function split of string which separates into several values by means of a separator. In your case it is important to use the . 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 the ip is not actually a number but a string, however, it has no relevance to what it is doing which is to replace the last block dynamically. Now we’re at the point of building whatever:

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 function join with ip_formatado = '.'.join(ip), which greatly simplifies. See an example of this part only working:

>>> ip = ['192', '168', '1', '1']
>>> ip
['192', '168', '1', '1']
>>> '.'.join(ip)
'192.168.1.1'
  • MT THANKS MANO, NAMORAL I LOVE YOU <3

Browser other questions tagged

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