Port Scanner written in python does not display output normally - python

So I tried to write a port scanner in python3
Here is my code:
import sys #allows us to enter command line arguments, among other things
import socket
from datetime import datetime
if len(sys.argv) == 2:
target = socket.gethostbyname(sys.argv[1]) #Translate a hostname to IPv4
else:
print("Invalid amount of arguments.")
print("Syntax: python3 scanner.py <ip>")
sys.exit()
#Add a banner
print("-" * 50)
print("Scanning target "+target)
print("Time started: "+str(datetime.now()))
print("-" * 50)
try:
for port in range(50,85):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket.setdefaulttimeout(1)
result = s.connect_ex((target,port)) #returns error indicator
print("Checking port {}".format(port))
if result == 0:
print("Port {} is open".format(port))
s.close()
except KeyboardInterrupt:
print("\nExiting program.")
sys.exit()
except socket.gaierror:
print("Hostname could not be resolved.")
sys.exit()
except socket.error:
print("Couldn't connect to server.")
sys.exit()
using Kali Linux 2020.2, with the newest version of python,
I executes python3 scanner.py google.com
It is expected that the scanner will display "Checking port 50", "Checking port 51" one by one during the scanning process.
And if it find any one of the ports is open, it shows "Port xx is open" after the "Checking port xx"
However, my scanner was stuck as the initial banner.
And eventually when it has completed the scanning, it displays all the output in one go.
Can anyone please tell me how can I solve this problem?

Just switch the following lines in your code:
result = s.connect_ex((target,port)) #returns error indicator
print("Checking port {}".format(port))
becomes:
print("Checking port {}".format(port))
result = s.connect_ex((target,port)) #returns error indicator

Related

Python script to broadcast relay on all adapters lan networking gaming

can anybody make something like this for pythons script, nothing big very small programme , source code which is free.
kindly read throught and check what it does. i will paste the text from the github below.
https://github.com/dechamps/WinIPBroadcast
WinIPBroadcast is a small program that allows Windows applications to send global IP broadcast packets (destination address 255.255.255.255) to all interfaces instead of just the preferred one.
This application is most useful for users of server browsers or other network monitoring software. Specifically, those playing multiplayer games locally on multiple interfaces (for example, a LAN network and a Hamachi VPN) will be able to see games from all networks at once.
ok and now here is a python script i found on stackoverflow post.
this sends broadcast but not relaying or something maybe you can help tweak this
import socket
from time import sleep
def main():
interfaces = socket.getaddrinfo(host=socket.gethostname(), port=None, family=socket.AF_INET)
allips = [ip[-1][0] for ip in interfaces]
msg = b'hello world'
while True:
for ip in allips:
print(f'sending on {ip}')
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) # UDP
sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
sock.bind((ip,0))
sock.sendto(msg, ("255.255.255.255", 3074))
sock.close()
sleep(2)
main()
i found this
import socket
import threading
import sys
import getopt
import os
from relay import udp
from relay import tcp
from relay import status
relayport = 0
remoteport = 0
remoteaddress = ""
protocol = "UDP"
help = "Invalid arguments, usage:\nboxy.py -i <input port> -p <remote port> -a <remote address> [-t]"
def quit():
print "Quitting..."
if (protocol == "UDP"):
udp.stop()
else:
tcp.stop()
os._exit(0)
#process args
try:
options, args = getopt.getopt(sys.argv[1:], "i:p:a:t")
except getopt.GetoptError:
print help
sys.exit(2)
try:
for option, arg in options:
if (option == "-i"):
relayport = int(arg)
elif (option == "-p"):
remoteport = int(arg)
elif (option == "-a"):
remoteaddress = arg
elif (option == "-t"):
protocol = "TCP"
except ValueError:
print help
sys.exit(2)
if ((0 < relayport <= 65535 and 0 < remoteport <= 65535 and remoteaddress != "") == False):
print help
sys.exit(2)
print "Relay starting on port {0}, relaying {1} to {2}:{3}".format(relayport, protocol, remoteaddress, remoteport)
if (protocol == "UDP"):
udp.start(relayport, remoteaddress, remoteport)
else:
tcp.start(relayport, remoteaddress, remoteport)
status.start(relayport, remoteaddress, remoteport)
try:
while raw_input() != "quit":
continue
quit()
except KeyboardInterrupt:
quit()
except EOFError:
#this exception is raised when ctrl-c is used to close the application on Windows, appears to be thrown twice?
try:
quit()
except KeyboardInterrupt:
os._exit(0)
how do i fix it ? gives error missing perenthisis.
boxy.py -i 3074 -a 192.168.0.0.1 -p 3074 -t`
https://github.com/OliverF/boxy
how do i send it to all adapters

Can connect to a socket on my local network but not on separate ones (python sockets)

I've been trying to make a program that would allow me to remote into my computer. It works perfectly when both computers are connected to the same network, and I am able to access a sort of command line that I have coded.
I am very inexperienced with networks and I'm not entirely sure what sort of information is needed.
This is the code I used:
Server:
import sys
import socket
def create_socket():
try:
global host
global port
global s
host = ""
port = 9999
s = socket.socket()
except socket.error as msg:
print("SocketCreationError: " +str(msg))
def bind_socket():
try:
global host
global port
global s
print("binding the port " + str(port)+"...")
s.bind((host,port))
s.listen(5)
except socket.error as msg:
print("SocketBindingError: " + str(msg))
print("retrying...")
bind_socket()
def socket_accept():
conn,address = s.accept()
print("Connection established. \nIP:"+address[0]+"\nPort:"+str(address[1]))
print(str(conn.recv(1024), "utf-8"), end="")
send_command(conn)
conn.close()
#allows user to send command to client computer
def send_command(conn):
while True:
try:
cmd = input(">")
if cmd == 'exit':
conn.close()
s.close()
sys.exit()
if len(str.encode(cmd)) > 0:
conn.send(str.encode(cmd))
clientResponse = str(conn.recv(1024),"utf-8")
print(clientResponse, end="")
except Exception:
print("Something went wrong...")
def main():
create_socket()
bind_socket()
socket_accept()
main()
Client:
import socket
import os
import subprocess
#connect to socket and send cwd
s = socket.socket()
host = 'myIP'
port = 9999
s.connect((host, port))
s.send(str.encode(os.getcwd()))
#allows form of command line on host pc
while True:
try:
data = s.recv(1024)
outputStr = ""
if data.decode("utf-8") == 'dir':
dirList = os.listdir(os.getcwd())
for i in dirList:
print(i)
outputStr = outputStr + i + "\n"
elif data[:2].decode("utf-8") == 'cd':
dirTo = data[3:].decode("utf-8")
print(data[3:].decode("utf-8"))
os.chdir(os.getcwd() + "\\" + dirTo)
elif len(data) > 0:
cmd = subprocess.Popen(data.decode("utf-8"), shell=True,stdout=subprocess.PIPE,stdin=subprocess.PIPE, stderr=subprocess.PIPE)
outputByte = cmd.stdout.read() + cmd.stderr.read()
outputStr = str(outputByte, "utf-8")
print(outputStr)
cwd = os.getcwd()
s.send(str.encode(outputStr +"\n"+cwd))
#handle something going wrong and just allows to continue
except Exception:
cwd = os.getcwd()
s.send(str.encode("Something went wrong...\n"+ cwd))
I am using ipv4 addresses. I think it may have something to do with port forwarding on the server side, but again I am not sure?
Thank you for any answers in advance :)
You can't connect to your computer using a remote network because of port forwarding. If you dont know what that is, I recommend taking a look at the Wikipedia article on it: https://en.wikipedia.org/wiki/Port_forwarding
There are many different methods to perform Port Forwarding, the simplest of which is the UPnP/IGD (look it up), but if you're just interested in being able to Access your computer remotely, you could just use an SSH (Secure Shell Connection) to do just this (I think it Works on remote networks as well). If you're using Linux this should be pretty easy to set up, just look up how to do it. Good luck!

Why doesn't my python socket connect to another computer?

So i've recently started testing out sockets and i have managed to create a server and client, which are both working together when i run them on the same pc. However, when i put in the server on a diffrent computer it gives me the following error: ""TimeoutError: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond""
Here is my server:
import socket
import pyautogui
import os
computerIP = socket.gethostbyname(socket.gethostname())
def Main():
host = computerIP
port = 5000
value = 0
mySocket = socket.socket()
mySocket.bind((host,port))
mySocket.listen(1)
conn, addr = mySocket.accept()
print ("Connection from: " + str(addr))
while True:
data = conn.recv(1024).decode()
if not data:
break
elif data == "shift":
pyautogui.keyDown("shift")
elif data == "relshift":
pyautogui.keyUp("shift")
elif data == "logout":
os.popen("shutdown -l")
elif data == "click":
pyautogui.click()
pyautogui.click()
print ("from connected user: " + str(data))
data = str(data).upper()
print ("sending: " + str(data))
conn.send(data.encode())
conn.close()
if __name__ == '__main__':
Main()
My client:
import socket
def Main():
host = #same ip as server
port = 5000
mySocket = socket.socket()
mySocket.connect((host,port))
message = input(" -> ")
while message != 'q':
mySocket.send(message.encode())
data = mySocket.recv(1024).decode()
print ('Received from server: ' + data)
message = input(" -> ")
mySocket.close()
if __name__ == '__main__':
Main()
OS: Windows 8.1
Python verion: 3.4
I tried looking this up on the internet but since i'm pretty new to python i didn't understand much.
Tell me if there is anything i need to clearify.
Looks like the port is blocked due to some firewall.
Use socket.connect_ex() instead of socket.connect(). If the connection succeeds it would return 0, otherwise the value of the errno variable will help you debug why the connection failed.
Prior to the connection also use socket.settimeout() so that the connection times out in the given no. of seconds.

Python Port Scanner Stuck In Loop

I've been following a guide on how to make a simple port scanner, I am trying to scan my own IP but it gets stuck in a loop and prints no ports. It's hard to figure out at it gives no errors and gets stuck in a loop.
Any help would be greatly appreciated.
import socket
import subprocess
import sys
from datetime import datetime
#clears the shell screen
subprocess.call('clear', shell=True)
#ask for input
remoteServer = raw_input("Please enter a host to scan:")
remoteServerIP = socket.gethostbyname(remoteServer)
#print a banner saying we are scanning
print "-" * 60
print "now scanning your host...", remoteServerIP
print "-" * 60
#Check what time the scan started
t1 = datetime.now()
# Using the range function to specify which ports (1 - 1025)
#Errors.
try:
for port in range(1, 1025):
sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
result = sock.connect_ex((remoteServerIP, port))
if result == 0:
#if the socket is listening it will print out the port
print("Port{}:\t Open".format(port))
sock.close()
except KeyboardInterrupt:
print "You pressed ctrl+c"
sys.exit()
except socket.gaierror:
print 'Hostname could not be resolved to IP. Exiting'
sys.exit()
except socket.error:
print "couldn't connect to server"
sys.exit()
# checking the time again
t2 = datetime.now()
#calculates the differnce of time, to see how long it took to run the script
total = t2 - t1
#printing the info to screen
print "scanning compelte in :", total
You can use sock.timeout(0.1) so it will no wait for connection.
I put print port to see which port is scanned.
You can try with 8.8.8.8 - without sock.timeout(0.1) it hang on first port.
Maybe you have good secured computer and it blocks connections to close ports.
import sys
from datetime import datetime
import socket
#ask for input
remoteServer = raw_input("Please enter a host to scan: ")
remoteServerIP = socket.gethostbyname(remoteServer)
#print a banner saying we are scanning
print "-" * 60
print "now scanning host ...", remoteServerIP
print "-" * 60
#Check what time the scan started
t1 = datetime.now()
# Using the range function to specify which ports (1 - 1025)
#Errors.
try:
for port in range(1, 1025):
print port
sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
sock.settimeout(0.1)
result = sock.connect_ex((remoteServerIP, port))
if result == 0:
#if the socket is listening it will print out the port
print("Port {:4d}: Open".format(port))
sock.close()
except KeyboardInterrupt:
print "You pressed ctrl+c"
sys.exit()
except socket.gaierror:
print 'Hostname could not be resolved to IP. Exiting'
sys.exit()
except socket.error:
print "couldn't connect to server"
sys.exit()
# checking the time again
t2 = datetime.now()
#calculates the differnce of time, to see how long it took to run the script
total = t2 - t1
#printing the info to screen
print "scanning compelte in:", total
BTW:
You can compare your results with results from tools like nmap
See scapy - python module to work with network packages. (book: Black Hat Python)
At least on my machine (Ubuntu 16.something) it does work. Output:
Please enter a host to scan:localhost
------------------------------------------------------------
now scanning your host... 127.0.0.1
------------------------------------------------------------
Port21: Open
Port22: Open
Port25: Open
Port80: Open
Port139: Open
Port443: Open
Port445: Open
Port631: Open
scanning compelte in : 0:00:00.047478
However, it only scans ports 1-1024, while ports go up to 65535.
To make it scan all the ports, change for port in range(1, 1025): to for port in range(1, 65536):

Port Scanner 3.5 Python Print Issue After Going Through set range

import socket
import sys
from datetime import datetime
#Ask the user for input, the form of a remote host entire in the IP address of the target machine
remoteServer =input ("Enter a remote host to scan:")
remoteServerIP =socket.gethostbyname(remoteServer)
#Print a block of text with information on which host we are about to scan.
#While scanning display a message so the user knows the program is working and isn't frozen
print ("_"*60)
print ("Please wait, currently scanning remote host", remoteServerIP)
print ("_"*60)
#Show/check the time scan started
t1 = datetime.now()
#range function to specify ports, this case I have set the pogram to go through ports 1 to 150
# port in range works like so
try:
for port in range (1, 150):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = sock.connect_ex((remoteServerIP, port))
if result == 0:
print ("Port {}: Open".format(port))
sock.close()
# Press Ctrl C to leave the application
except KeyboardInterrupt:
print ("You pressed Ctrl+C")
sys.exit()
except socket.gaierror:
print ('Hostname could not be resolved. Exiting')
sys.exit()
except socket.error:
print ("Couldn't connect to server")
sys.exit()
# Checking the time again
t2 = datetime.now()
# Calculates the difference of time, to see how long it took to run the script
total = t2 - t1
# Printing the information to screen
print ('Scanning Completed in: ', total)
My boss has told me to start learning about Metasploitable2 and Kali Linux as such I have attempted to create a port scanner it seems to work fine for most of the part however. after if has finished scanning the ports within it's set range it close completely rather then print ('Scanning Completed in: ', total) with listed findings. What have I done wrong here? And I 'm well aware this is script slow I'm going to attempt to make it multithreaded later on.

Categories