Im making a port scanner it through's this message here is my code but it checks one port 21 i have pasted output below
import socket
import os
host = input("Enter the host name or ip : ")
s = socket.socket()
s.settimeout(5)
p = 0;
s.close
port = [21,22,23,25,53,80,110,115,135,139,143,194,443,445,1433,3306,3389,5632,5900,6112]
while(p<=19):
try:
s.connect(('host', port[p]))
except ConnectionRefusedError:
print("Port %d is close" %(port[p]))
except socket.timeout:
print("Port %d is close" %(port[p]))
else:
print("Port %d is open" %(port[p]))
p=p+1;
s.close
On command line :
PS E:\Codes by me\Selenium py> python .\practice.py
Enter the host name or ip : 89.86.98.76
Port 21 is close # it checks one port
Traceback (most recent call last):
File ".\practice.py", line 11, in <module>
s.connect((host, port[p]))
OSError: [WinError 10022] An invalid argument was supplied
You are passing the literal string 'host' as the host. You should be passing the variable host:
s.connect((host, port[p]))
You are also not actually closing the socket each time, since you left off the parentheses in s.close(). But if you did close the socket each time, you would have to create a new socket each time, instead of trying to reuse the same socket. You can't reuse a closed socket.
Related
I have written a client-server python program where the client can send the data to the server. But when the client is trying to connect with the server I am getting the following error.
[Errno 110] Connection timed out
Sending Key to Server
Traceback (most recent call last):
File "client.py", line 43, in <module>
s.send(str(id))
socket.error: [Errno 32] Broken pipe
I tried the following solutions
Broken Pipe error and How to prevent Broken pipe error but none of them solved the issue.
Here are my client and server code
client.py
import socket
import os
import subprocess
from optparse import OptionParser
from random import randint
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print "Socket has been successfully created"
except socket.error as err:
print "socket creation failed with error %s" %(err)
# The Manager Address and port
host_ip='192.168.43.123'
port =10106
# Generates a random number say xxxx then its client id becomes 'clxxxx' and home directory made at the server as '/home/clxxxx' with permissions 700
def random_with_N_digits(n):
range_start = 10**(n-1)
range_end = (10**n)-1
return randint(range_start, range_end)
id=random_with_N_digits(4)
id="cl"+ str(id)
# Looks for a public key in .ssh folder if temp.pub not present. If not found generates a ssh public private key and sends it to manager which then copies it to the server
subprocess.call(["bash","keygen.sh"])
#s = socket.socket()
try:
s.connect((host_ip,port))
print "the socket has successfully connected to Backup Server IP == %s" %(host_ip)
except socket.error as err:
print err
f = open('temp.pub','r')
print "Sending Key to Server"
j = "-"
s.send(str(id))
l=f.read(8192)
while(l):
print 'Sending...'
s.send(l)
l = f.read(8192)
try:
client_id=s.recv(1024)
data=s.recv(12)
ip=s.recv(24)
print client_id,
print data, ip
except:
print "An Unknown Error Occurred!"
f.close()
# Writes the parameters of client in the file 'backup_dir.txt'
with open('backup_dir.txt','w') as the_file:
the_file.write(client_id)
the_file.write('\n')
the_file.write(data)
the_file.write('\n')
the_file.write(ip)
the_file.write('\n')
f.close()
s.close()
server.py
import socket
import subprocess
import os
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print "Socket has been successfully created"
except socket.error as err:
print "socket creation failed with error %s" %(err)
port = 10106
s.bind(('', port))
print("socket binded to %s port" %port)
s.listen(10)
print("socket is listening")
while(True):
print("waiting for a connection")
c, addr = s.accept()
print("Got a connection from", addr,c)
clientID =(c.recv(8192))
key =(c.recv(8192))
print clientID
print key
with open("temp.pub", 'w') as fp:
fp.write(key)
note=subprocess.check_output("./test_user.sh "+ clientID, shell=True)
note = str(note)
print(len(note))
flag, path, serverIP = note.split(":")
print(flag)
print(path)
print(serverIP)
if flag:
c.send(clientID)
c.send(path)
c.send(serverIP)
os.remove("temp.pub")
else:
c.send("Unable to add Client.")
How do I fix this problem so that the client can send the data to the server without any error?
Thank You in advance.
The error resolved.
It was due to the firewall issue as #RaymondNijland was mentioning, Thanks.
I added the rule in the firewall to allow the following port for Socket Connection and it worked.
sudo ufw allow 10106
It's my client:
#CLIENT
import socket
conne = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
conne.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
i=0
while True:
conne.connect ( ('127.0.0.1', 3001) )
if i==0:
conne.send(b"test")
i+=1
data = conne.recv(1024)
#print(data)
if data.decode("utf-8")=="0":
name = input("Write your name:\n")
conne.send(bytes(name, "utf-8"))
else:
text = input("Write text:\n")
conne.send(bytes(text, "utf-8"))
conne.close()
It's my server:
#SERVER
import socket
counter=0
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(('', 3001))
sock.listen(10)
while True:
conn, addr = sock.accept()
data = conn.recv(1024)
if len(data.decode("utf-8"))>0:
if counter==0:
conn.send(b"0")
counter+=1
else:
conn.send(b"1")
counter+=1
else:
break
print("Zero")
conn.send("Slava")
conn.close()
))
After starting Client.py i get this error:
Traceback (most recent call last): File "client.py", line 10, in
conne.connect ( ('127.0.0.1', 3001) ) OSError: [Errno 9] Bad file descriptor
Problem will be created just after first input.
This program - chat. Server is waiting for messages. Client is sending.
There are a number of problems with the code, however, to address the one related to the traceback, a socket can not be reused once the connection is closed, i.e. you can not call socket.connect() on a closed socket. Instead you need to create a new socket each time, so move the socket creation code into the loop:
import socket
i=0
while True:
conne = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
conne.connect(('127.0.0.1', 3001))
...
Setting socket option SO_BROADCAST on a stream socket has no affect so, unless you actually intended to use datagrams (UDP connection), you should remove the call to setsockopt().
At least one other problem is that the server closes the connection before the client sends the user's name to it. Probably there are other problems that you will find while debugging your code.
Check if 3001 port is still open.
You have given 'while True:' in the client script. Are you trying to connect to the server many times in an infinite loop?
I have to create a web server in Python. Below is the code I am working on. When i execute it, I initially get no error and it prints "Ready to serve.." , but after opening a browser and running http://10.1.10.187:50997/HelloWorld.html (HelloWorld is an html file in the same folder as my python code, while 10.1.10.187 is my IP address and 50997) is the server port), I get a TypeError saying 'a bytes like object is required and not str". please help me in resolving this and kindly let me know if any other modifications are required.
#Import socket module
from socket import *
#Create a TCP server socket
#(AF_INET is used for IPv4 protocols)
#(SOCK_STREAM is used for TCP)
# Assign a port number
serverPort = 50997
serverSocket = socket(AF_INET, SOCK_STREAM)
#serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#print ("hostname is: "), gethostname()
#print ("hostname is: "), socket.gethostname()
# Bind the socket to server address and server port
serverSocket.bind(("", serverPort))
# Listen to at most 1 connection at a time
serverSocket.listen(1)
# Server should be up and running and listening to the incoming connections
while True:
print ("Ready to serve...")
# Set up a new connection from the client
connectionSocket, addr = serverSocket.accept()
try:
# Receives the request message from the client
message = connectionSocket.recv(1024)
print ("Message is: "), message
filename = message.split()[1]
print ("File name is: "), filename
f = open(filename[1:])
outputdata = f.read()
connectionSocket.send("HTTP/1.1 200 OK\r\n\r\n")
for i in range(0, len(outputdata)):
connectionSocket.send(outputdata[i])
connectionSocket.send("\r\n")
# Close the client connection socket
connectionSocket.close()
except IOError:
# Send HTTP response message for file not found
connectionSocket.send("HTTP/1.1 404 Not Found\r\n\r\n")
connectionSocket.send("<html><head></head><body><h1>404 Not Found</h1></body></html>\r\n")
# Close the client connection socket
connectionSocket.close()
serverSocket.close()
The error I am exacly getting-
Ready to serve...
Message is:
File name is:
Traceback (most recent call last):
File "intro.py", line 56, in <module>
connectionSocket.send("HTTP/1.1 200 OK\r\n\r\n")
TypeError: a bytes-like object is required, not 'str'
You need to convert the string you are sending into bytes, using a text format. A good text format to use is UTF-8. You can implement this conversion like so:
bytes(string_to_convert, 'UTF-8')
or, in the context of your code:
connectionSocket.send(bytes("HTTP/1.1 404 Not Found\r\n\r\n","UTF-8"))
connectionSocket.send(bytes("<html><head></head><body><h1>404 Not Found</h1></body></html>\r\n","UTF-8"))`
I have a very simple Socket Server code running on port 9999. When I fire up my server and client, with netstat I can see that the server is running and the client is on the ephemeral port of 7180.
TCP 192.168.1.117:9999 0.0.0.0:0 LISTENING 7180
However, the output of client shows this error:
Traceback (most recent call last):
File "client.py", line 6, in <module>
clisock.connect((host, 9999))
File "C:\Python27\lib\socket.py", line 222, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 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
My server code:
import socket
import sys
import time
srvsock = socket.socket (socket.AF_INET, socket.SOCK_STREAM)
print 'Server Socket is Created'
host = socket.gethostname()
try:
srvsock.bind( (host, 9999) )
except socket.error , msg:
print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
sys.exit()
srvsock.listen(5)
print 'Socket is now listening'
while True:
clisock, (remhost, remport) = srvsock.accept()
print 'Connected with ' + remhost + ':' + str(remport)
currentTime = time.ctime(time.time()) + "\r\n"
print currentTime
clisock.send(currentTime)
clisock.close()
srvsock.close()
And my Socket client program is as follow:
import socket
clisock = socket.socket (socket.AF_INET, socket.SOCK_STREAM)
host = socket.gethostname()
print host
clisock.connect((host, 9999))
tm = clisock.recv(1024)
clisock.close()
print tm
What is the issue? Could it be a Firewall or something which cause the connection to drop?
There is no guarantee that socket.gethostname() will return a FQDN. Try to bind the server to '' (empty string is a symbolic name meaning all available interfaces), then connect your client to localhost or 127.0.0.1.
Python documentation includes a very useful example for creating a simple TCP server-client application using low-level socket API [1].
[1] https://docs.python.org/2/library/socket.html#example
I am trying to implement a simple ftp with sockets using C (server side) and Python (client side). When the server code is compiled and run, the user enters a port number. The client then enters "localhost " when compiling. For some reason I am getting [Errno 111] on the client side when I run the code. It is saying that the issue is with my client.connect statement. I have tried using multiple different port numbers and it throws this same error:
flip1 ~/FTPClient 54% python ftpclientNew.py localhost 2500
Traceback (most recent call last):
File "ftpclientNew.py", line 86, in <module>
main()
File "ftpclientNew.py", line 27, in main
if client.connect((serverName, portNumber)) == None:
File "<string>", line 1, in connect
socket.error: [Errno 111] Connection refused
Another weird thing is that this connection error was not happening when I ran this same code a few days ago. Has anyone experienced a problem like this? Any idea what might be causing this? Thanks!
Here is the client code:
import sys, posix, string
from socket import *
def main():
if len(sys.argv) < 3:
print "\nFormat: 'localhost' <port number>!\n"
return 0
buffer = ""
bufferSize = 500
serverName = "localhost"
fileBuffer = [10000]
if sys.argv[1] != serverName:
print "Incorrect Server Name! \n"
return 0
portNumber = int(sys.argv[2])
client = socket(AF_INET, SOCK_STREAM)
if client < 0:
print "Error Creating Socket!! \n"
return 0
if client.connect((serverName, portNumber)) == None:
print "Client Socket Created...\n"
print "Connecting to the server...\n"
print "Connected!\n"
##clientName = raw_input("Enter a file name: ")
Sometimes localhost isn't working on host
Change this
serverName = 127.0.0.1
Try to change the serverName variable to 127.0.0.1.