Python 2.7 UDP Port Scanner - python

Can you help me with the program now the problem is that when I enter localhost my program cannot find the open port or the closed one, if you really want to help me and you know how to solve it or fix it, please just compile my code separately just for me right now the program for some reason can’t get to receive a message from the host, I searched the entire Internet and can’t find anywhere the scanner has multiple UDP ports
import socket
import sys
# Ask for input
remoteServer = raw_input('Enter a remote host to scan: ')
remoteServerIP = socket.gethostbyname(remoteServer)
print( "-" * 60)
print ('Please wait, scanning remote host', remoteServerIP)
print( "-" * 60)
for port in range(1,1025):
try:
sock=socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM)
sock.sendto('hello',(remoteServerIP,port))
#sock.settimeout(1)
data, address = sock.recvfrom(1024)
if data != None:
print ('Port {}: Open'.format(port))
else:
print ('Port {}: Closed'.format(port))
sock.close()
except socket.error as sock_err:
if(sock_err.errno == socket.errno.ECONNREFUSED):
print sock_err('Connection refused')
except socket.gaierror:
print 'Hostname could not be resolved. Exiting'
except socket.error:
print "Couldn't connect to server"
except KeyboardInterrupt:
print 'You pressed Ctrl+C'

Need to use ICMP packet.For the program to work, you need to enter python
I publish my code because the answer to this question is practically nonexistent and the task is actually difficult.
import socket
import sys
import subprocess
def getServiceName(port, proto):
try:
name = socket.getservbyport(int(port), proto)
except:
return None
return name
UDP_IP = sys.argv[1]
for RPORT in range(int(sys.argv[2]), int(sys.argv[3])):
MESSAGE = "ping"
client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
if client == -1:
print("udp socket creation failed")
sock1 = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP)
if sock1 == -1:
print("icmp socket creation failed")
try:
client.sendto(MESSAGE.encode('utf_8'), (UDP_IP, RPORT))
sock1.settimeout(1)
data, addr = sock1.recvfrom(1024)
except socket.timeout:
serv = getServiceName(RPORT, 'udp')
if not serv:
pass
else:
print('Port {}: Open'.format(RPORT))
except socket.error as sock_err:
if (sock_err.errno == socket.errno.ECONNREFUSED):
print(sock_err('Connection refused'))
client.close()
sock1.close()

Related

Python socket getting the error “connection refused error 111”

I have a problem connecting with the socket.
I wrote a code whose purpose is to get the serial number of the hard disk from a client and send it to the server.
If I run the server and the client code on my local machine, it works fine.
When I try to run the server on the real server and the client on the real client (2 different machines) I’m getting the error:
“Connection refused error 111”
This is my client code:
#!/usr/bin/python3
import os, socket
from time import sleep
def serialNumber():
"""Find the product serial number"""
serialtest = "smartctl -a -i /dev/sda2 > /root/Desktop/serialTest.txt"
grepp = "grep 'Serial Number:' /root/Desktop/serialTest.txt > /root/Desktop/NewserialTest.txt"
sedd = "sed -i 's/Serial Number: //g' /root/Desktop/NewserialTest.txt"
os.system(serialtest)
os.system(grepp)
os.system(sedd)
try:
with open (r"/root/Desktop/NewserialTest.txt","r") as data:
global newserial
newserial = data.readline().strip()
except:
return "File not found!"
try:
os.rename(r'/root/Desktop/NewserialTest.txt',rf'/root/Desktop/{newserial}.txt')
os.remove(r"/root/Desktop/serialTest.txt")
except:
return "File not found!"
return ""
print(serialNumber())
try:
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
ip = socket.gethostname()
port = 5555
s.connect((ip,port))
except socket.error as e:
print(f"UNABLE to connect! you got error:\n{e}.")
exit(-1)
try:
with open(rf'/root/Desktop/{newserial}.txt', "rb") as fd:
toSend = fd.read()
s.send(toSend)
except socket.error as e:
print(f"you got error:\n{e}.")
This is my Server code:
#!/usr/bin/python3
import os, socket
from _thread import *
server_socket = socket.socket()
host = socket.gethostname()
port = 5555
try:
server_socket.bind((host, port))
except socket.error as e:
print(f"You have a error:\n{str(e)}")
print("\nWaiting for connection....\n")
server_socket.listen(100)
while True:
# Recive the serial number from the client
sc, address = server_socket.accept()
print(address)
f = open(r'/root/Desktop/LAB_Test/NewserialTest.txt' ,'wb') #open in binary
while (True):
l = sc.recv(1024)
f.write(l)
if not l:
break
f.close()
sc.close()
try:
with open (r'/root/Desktop/LAB_Test/NewserialTest.txt',"r") as data:
global newserial
newserial = data.readline().strip()
except:
print("File not found!")
os.rename(r'/root/Desktop/LAB_Test/NewserialTest.txt',rf'/root/Desktop/LAB_Test/{newserial}.txt')
what could be the problem?
I changed the bind to 0.0.0.0, and now it works.

Send Hex Command in python to instruct a machine to execute an order using TCP/IP Protocol

i am trying to send a Hex commmand "ABBA05B80000AF11" to a machine using TCP/ IP communication , to instruct the machine to execute an order.seems like , the Hex Command i have sent was unable to go through, Can anyone please help me . thank you
import socket
import sys
import struct
import time
import binascii
host = '192.168.1.40'
port = 800
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
inputHex = binascii.unhexlify("ABBA05B80000AF11")
try:
remote_ip = socket.gethostbyname(host)
s.connect((host, port))
except socket.gaierror:
print('Hostname could not be resolved Exiting')
sys.exit()
print('Socket connected to ' + host + ' on ip '+remote_ip)
try:
while True:
s.send(inputHex)
print('Message sent Successfully')
time.sleep(1)
print('sending')
except socket.error:
print('send fail')
` enter code here`sys.exit()
s.close()

Python3 Portscanner can't solve the socket pr0blem

When I run this code I am getting this socket error:
[WinError 10038] An operation was attempted on something that is not a socket
but even if I delete the s.close() it gives me wrong results.
It is a port scanner that are going to try connecting to all ports on the server I want to scan. And the ones that i'm getting connection from is stored in a list. But for some reason it is giving me wrong results. can someone please help me.
import socket
import threading
def scan_for_open_ports():
#Creating variables
OpenPorts = []
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = input('Host to scan: ')
global port
global OpenPorts
port = 1
#Scanning
for i in range(65534):
try:
s.connect((host, port))
s.shutdown(2)
OpenPorts.append(port)
print(str(port) + 'is open.')
s.close()
port += 1
except socket.error as msg:
print(msg)
s.close()
show_user()
def show_user():
#Giving the user results
print('------Open porst-----\n')
print(OpenPorts)
That's because you're closing your socket inside the loop with s.close() and you're not opening it again and you try to connect with a socket that's closed already. you should close the socket when you're done with it at the end of the loop, i also amended your code to make OpenPorts global and remove the unnecessary port variable you define and increment inside your for loop
import socket
OpenPorts = []
def scan_for_open_ports():
# Creating variables
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = input('Host to scan: ')
# Scanning
for port in range(1, 65534):
try:
s.connect((host, port))
OpenPorts.append(port)
print(str(port) + 'is open.')
except socket.error as msg:
print(msg)
s.close()
show_user()
def show_user():
# Giving the user results
print('------Open ports-----\n')
print(OpenPorts)
scan_for_open_ports()

What is wrong with the statement socket.sendall(message) in python 3.3?

Hi I am trying to learn sockets in python 3.3 but have an issue sending data to the remote server. Has the command be changed in python 3.3 or am I just doing it wrong. Please find the code below so you can see the problem. Would prefer a simple splution like change s.sendall to s.send or something. If not possible no worries
import socket
import sys
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error:
print("Failed to create a socket")
print("Socket created")
host = ("www.google.com")
port = 80
try:
remote_ip = socket.gethostbyname(host)
except socket.gaierror:
print("Hostname could not be found, exiting finding socket")
sys.exit()
print("Ip adress of",host,"is",remote_ip)
s.connect((remote_ip, port))
print("Socket connected to",host,"on ip", remote_ip)
message = "GET / HTTP/1.1/r/n/r/n"
try:
s.send(message)
except socket.error:
print("Failed")
sys.exit
print("Message send successful")
reply = s.recv(4096)
print(reply)
s.close()
First, you used slash where you meant to use backslash. Try this instead:
message = "GET / HTTP/1.1\r\n\r\n"
Second, yes, the send() call did change a little. Try this:
s.send(message.encode('utf-8'))

Python Server send data not working

I am currently working on a server in Python, the problem I am facing is the client could not retrieve the sent data from server.
The code of the server is:
import sys
import socket
from threading import Thread
allClients=[]
class Client(Thread):
def __init__(self,clientSocket):
Thread.__init__(self)
self.sockfd = clientSocket #socket client
self.name = ""
self.nickName = ""
def newClientConnect(self):
allClients.append(self.sockfd)
while True:
while True:
try:
rm= self.sockfd.recv(1024)
print rm
try:
self.sockfd.sendall("\n Test text to check send.")
print "Data send successfull"
break
except socket.error, e:
print "Could not send data"
break
except ValueError:
self.sockfd.send("\n Could not connect properly")
def run(self):
self.newClientConnect()
self.sockfd.close()
while True:
buff = self.sockfd.recv(1024)
if buff.strip() == 'quit':
self.sockfd.close()
break # Exit when break
else:
self.sendAll(buff)
#Main
if __name__ == "__main__":
#Server Connection to socket:
IP = '127.0.0.1'
PORT = 80
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serversocket.setsockopt( socket.SOL_SOCKET, socket.SO_REUSEADDR,1)
print ("Server Started")
try:
serversocket.bind(('',5000))
except ValueError,e:
print e
serversocket.listen(5)
while True:
(clientSocket, address) = serversocket.accept()
print 'New connection from ', address
ct = Client(clientSocket)
ct.start()
__all__ = ['allClients','Client']
#--
And the client connecting is:
import socket
HOST = '192.168.1.4' # The remote host
PORT = 5000 # The same port as used by the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
data = s.recv(1024)
s.close()
print 'Received', data#repr(data)
In need of a quick solution....
Thanks,
I tested out your code, and when I commented out
rm= self.sockfd.recv(1024)
print rm
it worked fine. Basically the server stopped there to wait for a message that never came. If it still does not work for you, there might be two problems. Either you have a firewall that blocks the connection somehow, or you have old servers running in the background from previous tries that actually wasn't killed. Check your processes if pythonw.exe or equivalent is running when it shouldn't be, and kill it.
To wait for response:
with s.makefile('rb') as f:
data = f.read() # block until the whole response is read
s.close()
There are multiple issues in your code:
nested while True without break
finally: ..close() is executed before except ValueError: ..send
multiple self.sockfd.close()
etc
Also you should probably use .sendall() instead of .send().
your server code is excepting client send something first,
rm= self.sockfd.recv(1024)
but I don't see any in your code
please try send something in your client code
s.connect((HOST, PORT))
s.send("hello")
Short solution
Add a short sleep after connect.
import time
time.sleep(3)

Categories

Resources