Python While loop stops when I have IOError - python-3.x

the below while loop stops when runs the except IOError
SO i get as output:
IP: 192.168.1.1 ,PORT: 80 ,Connection established
IP: 192.168.1.1 ,PORT: 22 ,Connection established
IP: 192.168.1.1 ,PORT: 22 ,Connection established
IP: 192.168.1.1 ,PORT: 22 ,Connection established
IP: 192.168.1.97 ,PORT: 22 ,Cannot Connect (stops here)
Any help would be great. I can't understand why it runs the except IOError: and then stops
Thank you
while True:
f = input('Type the File Name/Path:')
if f == '': break
try:
with open(f, 'r', encoding='utf-8') as f:
for check in f:
check = check.split("\t")
HOSTNAME = check[0]
IP = check[1]
PORT = int(check[2])
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(TIMEOUT)
s.connect((IP, PORT))
f = open("output.txt", "a")
print('IP:', IP, ',' 'PORT:', PORT, ',' "Connection established", file=f)
time.sleep(1)
f.close()
s.close()
except IOError:
f = open("output.txt", "a")
print('IP:', IP,',' 'PORT:', PORT,',' "Cannot Connect", file=f)
f.close()
except FileNotFoundError:
print("\n")
print('The file {} does not exist'.format(f))
input('Press ENTER to continue...')
print("\n")
break

if the IO Error is caused by the socket call, I think your try/except statement has to be changed a bit. You could try:
while True:
file = input('Type the File Name/Path:')
if file == '':
break
try:
with open(file, 'r', encoding='utf-8') as f:
for check in f:
check = check.split("\t")
HOSTNAME = check[0]
IP = check[1]
PORT = int(check[2])
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(TIMEOUT)
s.connect((IP, PORT))
s.close()
except IOError:
log = open("output.txt", "a")
print('IP:', IP,',' 'PORT:', PORT,',' "Cannot Connect", file=log)
log.close()
continue # will go back to the beginning of the while loop
log = open("output.txt", "a")
print('IP:', IP, ',' 'PORT:', PORT, ',' "Connection established", file=log)
log.close()
time.sleep(1)
except FileNotFoundError:
print('\nThe file {} does not exist'.format(file))
input('Press any key to continue...\n')
break

Related

Build port scanner but i face some issue

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()

How to tell a client that a file doesn't exist in the server in Python

I'm writing a simple client-server simple application, in which the client requests a certain file to the server. If the file exists, the server sends the file and its size; if it doesn't exists, then the server sends a message to the client saying the file couldn't be found. I included the exception in the server, but I don't know how to include the if clause in the client: if the file exists, the receive the file; else, receive the message saying it doesn't exist. I think I managed to do this on the server side, but I'm not really sure of how may I write this code to only print the message "file not found" in the client if the file wasn't found in the server
Here's the server side code
import socket
import os
import sys
import pickle
def Main():
host = '127.0.0.1'
port = 8881
s = socket.socket()
s.bind((host,port))
print("Server", host, "waiting on port", port)
s.listen(1)
while True:
c, addr = s.accept()
print("Connected to: " + str(addr))
filename = ''
while True:
data = c.recv(1024).decode('utf-8')
if not data:
break
filename += data
print("File requested: " + filename)
if os.path.isfile(filename):
lista = []
myfile = os.path.getsize(filename)
size = ('File size: ',myfile,' bytes')
texto = ''
for i in size:
texto = texto + '{:>4}'.format(i)
print(texto)
lista.append(texto)
file_size = pickle.dumps(lista)
c.send(file_size)
file2send = open(filename, "rb")
c.send(file2send.read())
c.close()
else:
print("File not found")
msg = ('File not found')
s.send(msg.encode('utf-8'))
if __name__ == '__main__':
Main()
And the client side:
import socket, os.path, datetime, sys, pickle
def Main():
host = '127.0.0.1'
port = 8881
s = socket.socket()
s.connect((host, port))
Filename = input("File name and extension: ")
s.send(Filename.encode('utf-8'))
s.shutdown(socket.SHUT_WR)
file_size = s.recv(1024)
lista = pickle.loads(file_size)
print(lista)
data = s.recv(1024).decode('utf-8')
print(data)
msg = s.recv(1024).decode('utf-8')
print(msg)
s.close()
if __name__ == '__main__':
Main()
In server, you are sending "file not found" message to server socket s, instead you should send that to client c and as per your logic you should send message length first and then message before closing the connection.
Please refer below server code.
Server:
import socket
import os
import sys
import pickle
def Main():
host = '127.0.0.1'
port = 8881
s = socket.socket()
s.bind((host,port))
print("Server", host, "waiting on port", port)
s.listen(1)
while True:
c, addr = s.accept()
print("Connected to: " + str(addr))
filename = ''
while True:
data = c.recv(1024).decode('utf-8')
if not data:
break
filename += data
print("File requested: " + filename)
if os.path.isfile(filename):
lista = []
myfile = os.path.getsize(filename)
size = ('File size: ',myfile,' bytes')
texto = ''
for i in size:
texto = texto + '{:>4}'.format(i)
print(texto)
lista.append(texto)
file_size = pickle.dumps(lista)
c.send(file_size)
file2send = open(filename, "rb")
c.send(file2send.read())
c.close()
else:
print("File not found")
msg = ('File not found')
c.send(str(len(msg)).encode('utf-8'))
c.send(msg.encode('utf-8'))
c.close()
if __name__ == '__main__':
Main()

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'))

How to find port number

i am trying to find which port is available for pc but i am unable would you tell me the process how to find port
import socket
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = socket.gethostname()
ip = socket.gethostbyname(host)
def portFinder(port):
try:
client_socket.connect((ip, port))
return True
except:
return False
for x in range(1, 200000):
if portFinder(x):
print("port {} is open for host {}".format(ip, x))
else:
print("No")

Python UDP client-server with different matching incoming-outgoing ports

Based on the example at http://www.binarytides.com/programming-udp-sockets-in-python/ I modified it to run on python 3 and used two opposed ports on client and server, so replies from each one go to these ports. Here are my examples
Server:
'''
Simple udp socket server
'''
import socket
import sys
HOST = 'localhost'
PORT_IN = 8889 # Arbitrary non-privileged port
PORT_OUT = 8888
# Datagram (udp) socket
try :
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
print('Socket created')
except socket.error as e:
print(e)
sys.exit()
# Bind socket to local host and port
try:
s.bind((HOST, PORT_IN))
except socket.error as e:
print(e)
sys.exit()
print('Socket bind complete')
#now keep talking with the client
while 1:
# receive data from client (data, addr)
d = s.recvfrom(1024)
data = d[0]
addr = d[1]
if not data:
break
reply = 'OK...' + str(data)
s.sendto(reply.encode('UTF-8'), ('localhost', PORT_OUT))
print('Message[' + addr[0] + ':' + str(addr[1]) + '] - ' + str(data).strip())
s.close()
Client:
'''
udp socket client
Silver Moon
'''
import socket #for sockets
import sys #for exit
# create dgram udp socket
try:
s1 = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s2 = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
except socket.error:
print('Failed to create socket')
sys.exit()
host = 'localhost'
port_out = 8889
port_in = 8888
counter = 0
while(1) :
# msg = b'aoua'
msg = 'aoua' + str(counter)
try :
#Set the whole string
s1.sendto(msg.encode('UTF-8'), (host, port_out))
# receive data from client (data, addr)
s2.bind(('localhost', port_in))
d = s2.recvfrom(1472)
reply = d[0]
addr = d[1]
print('Server reply : ' + str(reply))
except socket.error as e:
print(e)
# sys.exit()
counter += 1
Problem is with the client which cannot receive any response from server and d = s2.recvfrom(1472) hangs with error [WinError 10022] An invalid argument was supplied.
I've noticed a slightly different behaviour with sock.settimeout(seconds), but I really can't figure why. Isn't d = s2.recvfrom(buffer) supposed to wait for incoming data?
What am I missing here?
Damn... Just saw it. Silly mistake. Calling s2.bind(('localhost', port_in)) in Client inside the loop.

Resources