Build port scanner but i face some issue - python-3.x

I would like to ask for your advice if you can and guide me on how I will add this 3
in a Python script, I have:
I only have problems with this 2
If the Ports is open, it should create a file and add an entry for port number
In case of any exception for instance “host is not available”, “host name could not be resolved” or
due to any other error, you need to write that exception into the same file.

I think you need something like this.
import sys
import socket
from datetime import datetime
data = []
# Defining a target
if len(sys.argv) == 2:
# translate hostname to IPv4
target = socket.gethostbyname(sys.argv[1])
else:
print("Invalid amount of Argument")
# Add Banner
print("-" * 50)
print("Scanning Target: " + target)
print("Scanning started at:" + str(datetime.now()))
print("-" * 50)
try:
# will scan ports between 1 to 65,535
for port in range(1,65535):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket.setdefaulttimeout(1)
# returns an error indicator
result = s.connect_ex((target,port))
if result ==0:
data.append(port)
print("Port {} is open".format(port))
s.close()
with open("data.txt", "w") as e:
for port in data:
e.write("Port {} is open".format(port))
e.write("\n")
except KeyboardInterrupt:
print("\n Exiting Program !!!!")
sys.exit()
except socket.gaierror:
print("\n Hostname Could Not Be Resolved !!!!")
with open("output.txt", 'w') as e:
e.write("Hostname Could Not Be Resolved")
sys.exit()
except socket.error:
print("\ Server not responding !!!!")
with open("output.txt", 'w') as e:
e.write("Hostname Could Not Be Resolved")
sys.exit()

Related

Is something wrong in this script?. It is not showing port 53 and port 80 open?

#!/bin/python
import sys
import socket
from datetime import datetime
#Define a Target
if len(sys.argv) == 2:
target = socket.gethostbyname(sys.argv[1]) #Translate hostname to IPV4
else:
print("Invalid amount of IP address")
print("Syntax: Python3 scanner.py <IP>")
#Add a pretty 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))
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 a server.")
sys.exit()

Why isnt my python socket server receiving the messages?

so i am making a chatroom in python using sockets for practice. I have made the server code using threading so that i can have more clients. Ive also made the client code, and when i try to run two clients at once so that they message from one to another, they connect to server, but the server doesnt seem to be receiving the message sent from either of the clients.
SERVER CODE:
import select
from threading import *
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# takes the first argument from command prompt as IP address
IP_address = "127.0.0.1"
# takes second argument from command prompt as port number
Port = int("50204")
server.bind((IP_address, Port))
server.listen(1000)
list_of_clients = []
def clientthread(conn, addr):
# sends a message to the client whose user object is conn
conn.send("Welcome to this chatroom!")
while True:
try:
message = conn.recv(4096)
if message:
print("<" + addr[0] + "> " + message.decode("UTF-8"))
# Calls broadcast function to send message to all
message_to_send = "<" + addr[0] + "> " + message
broadcast(message_to_send.encode("UTF-8"), conn)
else:
remove(conn)
except:
continue
def broadcast(message, connection):
for clients in list_of_clients:
if clients != connection:
try:
clients.send(message)
except:
clients.close()
# if the link is broken, we remove the client
remove(clients)
def remove(connection):
if connection in list_of_clients:
list_of_clients.remove(connection)
while True:
conn, addr = server.accept()
list_of_clients.append(conn)
# prints the address of the user that just connected
print(addr[0] + " connected")
# creates and individual thread for every user
# that connects
Thread(target=clientthread, args=(conn, addr))
conn.close()
server.close()
CLIENT CODE:
import socket
import sys
import time
class client:
def __init__(self):
self.server_ip = "127.0.0.1"
self.port = 50204
self.s = self.connect()
def connect(self):
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error:
print("Failed to create socket.")
sys.exit()
print("Socket created")
try:
s.connect((self.server_ip, self.port))
except socket.error:
print("Failed to connect to ip " + self.server_ip)
print("Connected to: " + str(s.getsockname()))
return s
def SocketQuery(self, Sock, cmd):
try:
try:
# Send cmd string
Sock.send(cmd)
print("Sent!")
time.sleep(1)
except socket.error:
# Send failed
print("Send failed!")
sys.exit()
reply = Sock.recv(4096)
return reply
except ConnectionResetError:
print("Server is down!")
def SocketClose(self, Sock):
# close the socket
Sock.close()
time.sleep(.300)
if __name__ == "__main__":
c = client()
c.connect()
print("connected")
while True:
inp = input(">>> ")
if inp == ":q":
break
reply = c.SocketQuery(c.s, inp.encode("UTF-8"))
if reply:
print(reply.decode("UTF-8"))
c.SocketClose(c.s)
So as i have already mentioned, they do connect, but dont send/receive messages.
i have checked the value in conn.recv(), and it is the same, also everything gets encoded to UTF-8 before sent, and then decoded back. I cant seem to find any other problem except that im running them all on localhost.
If anyone knows the answer to this, please tell me.
cheers!

Subprocess results in "Broken Pipe" error

I'm playing around with socket programming. In the following code snippet I'm trying to connect to client and if his input contains "hack" it will remove it and run shell command and sends back the output.
server side:
import socket
class SP:
def server(self):
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('127.0.0.1', 9999))
s.listen(1)
while True:
try:
c, addr = s.accept()
print('Got connection from ', addr)
while True:
data = c.recv(1024)
if data:
if 'hack' in data.decode('utf-8'):
import subprocess
data = data.decode('utf-8')
data = data.strip('hack').lstrip().rstrip()
output = subprocess.call(data, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
s.send(str(output).encode('utf-8'))
else:
d = data.decode('utf-8')
print('Got data: '+str(d))
c.send(str('ACK: '+str(d)+' ...').encode('utf-8'))
else:
print('No more data from client: '+str(addr))
break
finally:
s.close()
except Exception as e:
print('Caught Exception: '+str(e))
s.close()
obj = SP()
obj.server()
client-side:
import socket
class CS:
def client(self):
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('127.0.0.1', 9999))
while True:
data = input('Enter data to be sent to server: \n')
if not data:
break
else:
s.send(data.encode('utf-8'))
reply = s.recv(1024).decode('utf-8')
print(str(reply))
else:
s.close()
except Exception as e:
print('Caught Exception: '+ str(e))
s.close()
obj = CS()
obj.client()
How can I resolve this the error ? Caught Exception: [Errno 32] Broken pipe doesn't tell me much.
update:
import socket
class SP:
def server(self):
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('127.0.0.1', 9999))
s.listen(1)
while True:
try:
c, addr = s.accept()
print('Got connection from ', addr)
while True:
data = c.recv(1024)
if data:
if 'hack' in data.decode('utf-8'):
import subprocess
data = data.decode('utf-8')
data = data.strip('hack').lstrip().rstrip()
print(data)
#output = subprocess.call(data, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
s.send(data.encode('utf-8'))
else:
d = data.decode('utf-8')
print('Got data: '+str(d))
c.send(str('ACK: '+str(d)+' ...').encode('utf-8'))
else:
print('No more data from client: '+str(addr))
break
finally:
s.close()
except Exception as e:
print('Caught Exception: '+str(e))
s.close()
obj = SP()
obj.server()
Even when I comment out the line where I call subprocess.call I still get "Broken Pipe" so the error isn't originating from the subprocess call.
You're using server's socket s instead of client's socket c to send the data to the client:
s.send(data.encode('utf-8'))
how about changing it to:
c.send(data.encode('utf-8'))

Port scanner shows module error, what is this relating to?

I'm going through the book violent python and using some examples from github to write the code in python 3. All has been going well for the most port but on the port scanner program I'm running into this repeated error module 'socket' has no attribute 'SOCKET_STREAM'. I have tried searching for this but most of the examples I've seen don't relate.
I've tried coding this on windows and Linux although I don't believe it's an OS issue.
#!/bin/bash/python 3.7
import argparse
import binascii
import socket
import threading
screen_lock = threading.Semaphore(value=1)
def conn_scan(target_host, target_port):
conn_skt = socket.socket(socket.AF_INET, socket.SOCKET_STREAM)
error = conn_skt.connect_ex(target_host, target_port)
screen_lock.aquire()
if not error:
print("[*] %d tcp open, " % target_port)
else:
print("[*] %d tcp closed." % target_port)
screen_lock.release()
conn_skt.close()
def ban_scan(target_host, target_port):
try:
conn_skt = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
conn_skt.connect(target_host, target_port)
conn_skt.send(b'ViolentPython3\r\n')
conn_skt.recv(100)
screen_lock.aquire()
print("[+] %d/tcp open " % target_port)
except Exception:
print("[-] %d/tcp closed " % target_port)
finally:
screen_lock.release()
conn_skt.close()
def initiate_scan(target_host, target_ports):
try:
target_IP = socket.gethostbyname(target_host)
except Exception:
print("[-] Cannot resolve '%s': Unknown host" % target_host)
return
try:
target_name = socket.gethostbyaddr(target_IP)
print("\n[+] Scan results for: " + target_name[0])
except Exception:
print("\n[+] Scan results for : " + target_IP)
socket.setdefaulttimeout(1)
for target_port in target_ports:
print("Scanning port " + target_port)
t = threading.Thread(target=conn_scan, args=(target_host, int(target_port)))
t.start()
def main():
parser = argparse.ArgumentParser()
parser.add_argument('-H', '--host', help='specify target host')
parser.add_argument('-P', '--port', help='specify target ports separated by comma')
args = parser.parse_args()
target_host = args.host
target_ports = str(args.port).split(',')
if(target_host is None) | (target_ports[0] is None):
parser.print_help()
exit(0)
initiate_scan(target_host, target_ports)
if __name__ == '__main__':
main()
Should show output of the port scan

Stop server from client's thread / Modify server's variable from client's thread

I would like to write an application that could stop the server based on client's input. The server is multi-threaded and I do not understand how can I do this.
Basically, I described my problem here: Modify server's variable from client's thread (threading, python).
However, this is the Python solution, not the general solution I could implement in Java, C, C++, etc.
I need to close other clients, when one of them guesses the number, but the server should be still alive, ready for the new game.
Can I ask for some advices, explanations?
I tried this (still do not know how to port it to C or Java), but it lets the clients send the numbers even if one of them just guesses it. It seems to me that kill_em_all does not do it's job, it does not close all the connections and does not disconnect the other clients as it should. How to improve this?
#!/usr/bin/env python
from random import randint
import socket, select
from time import gmtime, strftime
import threading
import sys
class Handler(threading.Thread):
def __init__(self, connection, randomnumber, server):
threading.Thread.__init__(self)
self.connection = connection
self.randomnumber = randomnumber
self.server = server
def run(self):
while True:
try:
data = self.connection.recv(1024)
if data:
print(data)
try:
num = int(data)
if self.server.guess(num) :
print 'someone guessed!'
self.server.kill_em_all()
break
else :
msg = "Try again!"
self.connection.sendall(msg.encode())
except ValueError as e:
msg = "%s" % e
self.connection.sendall(msg.encode())
else:
msg = "error"
self.connection.send(msg.encode())
except socket.error:
break
self.connection.close()
def send(self, msg):
self.connection.sendall(msg)
def close(self):
self.connection.close()
class Server:
randnum = randint(1,100)
def __init__(self, ip, port):
self.ip = ip
self.port = port
self.address = (self.ip, self.port)
self.server_socket = None
def guess(self, no):
if self.randnum == no:
self.randnum = randint(1, 100)
print("New number is ", self.randnum )
result = True
else:
result = False
return result
def kill_em_all(self):
for c in self.clients:
c.send("BYE!")
c.close()
def run(self):
try:
self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.server_socket.bind((self.ip, self.port))
self.server_socket.listen(10)
self.clients = []
print('Num is %s' % self.randnum)
while True:
connection, (ip, port) = self.server_socket.accept()
c = Handler(connection, self.randnum, self)
c.start()
self.clients.append(c)
except socket.error as e:
if self.server_socket:
self.server_socket.close()
sys.exit(1)
if __name__ == '__main__':
s = Server('127.0.0.1', 7777)
s.run()
Client code:
import socket
import sys
port = 7777
s = None
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = socket.gethostname()
s.connect(('127.0.0.1', port))
except socket.error, (value, message):
if s:
s.close()
print "Could not open socket: " + message
sys.exit(1)
while True:
data = raw_input('> ')
s.sendall(data)
data = s.recv(1024)
if data:
if data == "BYE!":
break
else:
print "Server sent: %s " % data
s.close()
Log in. Using whatever protocol you have, send the server a message telliing it to shut down. In the server, terminate your app when you get the shutdown message. That's it. It's not a problem with any OS I have used - any thread of a process can terminate that process.

Resources