I am trying to build a very simplistic port scanner in order to practice with the concept of sockets. The design I have is as following:
from socket import *
ip = input("Submit IP to scan:")
start = input("Submit starting port:")
end = input("Submit ending port:")
print("Scanning IP:", ip)
for port in range(int(start),int(end)):
print("Scanning port:" str(port) "..")
var_socket = socket(AF_INET,SOCK_STREAM)
var_socket.settimeout(3)
if var_socket.connect_ex((ip,port)) == 0:
print("port", port, "is open")
else:
print("err code:", var_socket.connect_ex((ip,port)))
var_socket.close()
print("Scanning completed!")
This all works pretty well when I run it from a file. Unfortunately I may not always have the luxury to run my scripts from a file, so I'll need to be able to create this script in a command shell. I've made some attempts myself with tips and tricks from the internet, but they all failed in some way.
from socket import * #Press enter. Note that I am in a windows terminal.
ip = input("enter ip to scan:")\ #Press enter
start = input("enter starting port:")\ #Press enter
output: Syntax error: Invalid syntax
The other solution I found actually worked, but brings some unwanted complexity along the way:
from socket import *
ip,start,end = map(int,input().split()) #Press enter
This solution allows me to enter 3 values seperated by a space, mapping them to ip, start and end respectively. Of course this will not work unless I design a function that manually transforms the entered ip value into a valid dotted decimal IP address. Does anyone know a better approach to ask for multiple inputs in a shell environment?
Thanks a lot in advance.
CodePudding user response:
When copying your script, the python interpreter reads your code line by line, which makes it fill your input with the script you are typing. One solution to avoid that is to read files from a different place (arguments, files, …). Or, you can also load your script in memory, then execute before asking for the inputs:
script = '''
from socket import *
ip = input("Submit IP to scan:")
start = input("Submit starting port:")
end = input("Submit ending port:")
print("Scanning IP:", ip)
for port in range(int(start),int(end)):
print("Scanning port:" str(port) "..")
var_socket = socket(AF_INET,SOCK_STREAM)
var_socket.settimeout(3)
if var_socket.connect_ex((ip,port)) == 0:
print("port", port, "is open")
else:
print("err code:", var_socket.connect_ex((ip,port)))
var_socket.close()
print("Scanning completed!")
'''
exec(script)