T.Bender T.Bender - 1 month ago 8
Linux Question

Issue with Python ping sweep script

import subprocess

nrange = "192.168.229."

for i in range(0, 254):
address = nrange + str(i)
res = subprocess.call(['ping', '-c', '3', address])
if res == 0:
print "ping to", address, "OK"
elif res == 2:
print "no response from", address
else:
print "ping to", address, "failed!"


root@kali:~/Desktop# ./pypsweep.py
^C./pysweep.py: line 3: nrange: command not found
./pysweep.py: line 5: syntax error unexpected toke `('
./pysweep.py: line 5: `for i in range (0, 254):'
root@kali:~/Desktop#


I am having an issue the above code. I am attempting to write a ping sweep script through Python to run in bash. I have tried several examples posted by other people around the interwebs but non seem to be functioning for me. This code is one that I wrote based off the simplest example I could find. I'm not sure if I am just simply overlooking an obvious error or what the issue could be. Any assistance with this issue would be greatly appreciated.

This is being ran on VMware Workstation Pro on Kali Linux distro if that matters at all.

Answer

Your code does not have a shebang line. As a consequence, when this command is run:

root@kali:~/Desktop# ./pypsweep.py

the shell attempts to interpret ./pypsweep.py as the default type: a shell script. That is why you see the errors that you see.

There are two solutions.

  1. Call python explicitly:

    root@kali:~/Desktop# python ./pypsweep.py

  2. Add this line to the beginning of your script:

    #!/usr/bin/python
    

    If you python is not in /usr/bin, adjust the path appropriately.