Python Client is unable to receive data sent from Python Server - python-2.7

I am trying to send some data from my python client to python server
I have followed this link
My python client code is as follows
#Socket client example in python
import socket #for sockets
import sys #for exit
#create an INET, STREAMing socket
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error:
print 'Failed to create socket'
sys.exit()
print 'Socket Created'
host = '10.4.1.25';
port = 80;
try:
remote_ip = socket.gethostbyname( host )
except socket.gaierror:
#could not resolve
print 'Hostname could not be resolved. Exiting'
sys.exit()
#Connect to remote server
s.connect((host , port))
print 'Socket Connected to ' + host + ' on ip ' + remote_ip
message = "16973"
try :
#Set the whole string
s.sendall(message)
except socket.error:
#Send failed
print 'Send failed'
sys.exit()
print 'Message send successfully'
#Now receive data
reply = s.recv(4096)
print reply
the python server code is
import socket
import sys
HOST = '' # Symbolic name meaning all available interfaces
PORT = 80 # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created'
try:
s.bind((HOST, PORT))
except socket.error , msg:
print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
sys.exit()
print 'Socket bind complete'
s.listen(10)
print 'Socket now listening'
#wait to accept a connection - blocking call
conn, addr = s.accept()
print 'Connected with ' + addr[0] + ':' + str(addr[1])
#now keep talking with the client
data = conn.recv(1024)
conn.sendall(data)
conn.close()
s.close()
The Function sendall is used to send data to client , means when I enter the text in terminal on server I should see it on client as well. But this does not happen
The output which I get is
Server Output
$ python server.py
Socket created
Socket bind complete
Socket now listening
Connected with 10.4.1.255:44656
Client Output
$ telnet localhost 8888
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
I am unable to know what's going wrong here?
Also how can I send data (message) from Python Client to Python server??
Any help would be great !
Thanks!

Related

How do I loop ports to scan?

I have this problem with a portscanner which keeps hanging at scanning port 1. How can I solve this problem?
#! /usr/bin/env python
import socket
import subprocess
from datetime import datetime
#Clear the screen
subprocess.call('clear', shell=True)
def portscan():
server = raw_input("Enter the server to scan: ")
serverIP = socket.gethostbyname(server)
# Printing banner with information about host
print "[+] Host: {} [+]\nIP Address: {}\n".format(server, serverIP)
print "[!] Please wait, scanning for open services...\n"
#Time when scan started.
t1 = datetime.now()
try:
for port in range(1, 1024):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = sock.connect_ex((serverIP, port))
if result == 0:
print "[+] Port {}: Status:OPEN\n".format(result)
sock.close()
except socket.gaierror:
print "Hostname could not be resolved, Exiting...\n"
sys.exit()
except socket.error:
print "Couldn\'t connect to server, Exiting\n"
sys.exit()
#Checking time again
t2 = datetime.now()
#Calculate duration of scan
totaltime = t2 - t1
print "Scan completed, duration: {}\n".format(totaltime)
What happens when i run it i give it a hostname and resolve it to a IP
Address but whenever the scan starts it keeps scanning port 1 as i saw
in Wireshark
I think that you maybe need a timeout.
Eventually, your sock.connect_ex( ), will to raise an exception socket.error: [Errno 110] Connection timed out, as you can read more about it, in this answer.
But the default timeout could be 120 seconds, and maybe you don't want to wait so much. So, you can set your own timeout, like that:
try:
for port in range(1, 1024):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(10) #timeout set for wait up 10 seconds.
result = sock.connect_ex((serverIP, port))
sock.settimeout(None)
To know why to use sock.settimeout(None), and see another ways of setting timeout, you can read this discussion.
I'm not sure if it was what you're looking for, but I hope it may help.

How to send a captured packet saved as text with Python

I captured packets on individual text files with tcpdump, I want to send back the captured packets, first I extracted the IP and Port, but I have not been able to send the packet.
This is my code:
def client():
packet = open("packet3.txt", "r")
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(10)
sock.connect(("192.168.128.1", 80))
while True:
try:
sock.send("packet")
sleep(1)
reply = sock.recv(131072)
if not reply:
break
print "recvd: ", reply
except KeyboardInterrupt:
print "bye"
break
sock.close()
return
client()
I get this error:
reply = sock.recv(131072)
error: [Errno 10054] An existing connection was forcibly closed by the remote host

python2.7 netcat program running with subprocesses

I am trying to make a script to mimic netcat and it kinda runs but i don't get the result i'm meant to, when trying to debug it i managed to do a bit but after days of searching and trial and errors i am at a loss at how to fix the issue. This is my whole code:
import sys
import socket
import getopt
import threading
import subprocess
import os
# define the global variables
listen = False
command = False
upload = False
execute = ""
target = ""
upload_destination = ""
port = 0
def usage():
print "BHP Net Tool"
print "Usage: netcat2.py -t target_host -p port"
print "-l --listen - listen on [host]:[port] for incoming
connections"
print "-e --execute=file_to_run - execute the given file upon receiving
a connection"
print "-c --command - initialize a command shell"
print "-u --upload=destination - upon receiving connection upload a
file and wrtie to [destination]"
print "Examples: "
print "netcat2.py -t 192.168.0.1 -p 5555 -l -c"
print "netcat2.py -t 192.168.0.1 -p 5555 -l -u=C:\\target.exe"
print "netcat2.py -t 192.168.0.1 -p 5555 -l -e=\"cat /etc/passwd\""
print "echo 'ABCDEFGHI' | ./netcat2.py -t 192.168.0.1 -p 135"
sys.exit(0)
def main():
global listen
global port
global execute
global command
global upload_destination
global target
if not len(sys.argv[1:]):
usage()
# read the commandline option
try:
opts, args = getopt.getopt(sys.argv[1:], "hle:t:p:cu", ["help",
"listen", "execute", "target", "port", "command", "upload"])
except getopt.GetoptError as err:
print str(err)
usage()
for o, a in opts:
if o in ("-h", "--help"):
usage()
elif o in ("-l", "--listen"):
listen = True
elif o in ("-e", "--execute"):
execute = a
elif o in ("-c", "--commandshell"):
command = True
elif o in ("-u", "--upload"):
upload_destination = a
elif o in ("-t", "--target"):
target = a
elif o in ("-p", "--port"):
port = int(a)
else:
assert False, "Unhandled Option"
# are we going to listen or just send data from stdin?
if not listen and len(target) and port > 0:
# read in the line from the commandline
# this will block, so send CTRL-D if not sending input
# to stdin
line = sys.stdin.readline()
print (line)
# send data off
client_sender(line)
# we are going to listen and potentially
# upload things, execute commands, and drop a shell back
# depending on our command line options above
if listen:
server_loop()
def client_sender(line):
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
# connect to our target host
client.connect((target, port))
if len(line):
client.send(line)
while True:
# now wait for data back
recv_len = 1
response = ""
while recv_len:
data = client.recv(4096)
recv_len = len(data)
response += data
if recv_len < 4096:
break
print "response"
# wait for more input
line = raw_input("")
line += "\n"
# send it off
client.sendline()
except:
print "[*] Exception! Exiting."
# tear down the connection
client.close()
def server_loop():
global target
# if no target is defined, we listen on all interfaces
if not len(target):
target = "0.0.0.0"
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((target, port))
server.listen(5)
while True:
client_socket, addr = server.accept()
# spin off a thread to handle out new client
client_thread = threading.Thread(target=client_handler, args=
(client_socket,))
client_thread.start()
def run_command(command):
# trim the newline
command = command.rstrip()
# run the command and get the output back
try:
with open(os.devnull, 'w') as devnull:
output = subprocess.check_output(command,
stderr=subprocess.STDOUT, shell=True)
except:
output = "Failed to execite command. \r\n"
# send the output back to the client
return output
def client_handler(client_socket):
global upload
global execute
global command
# check for upload
if len(upload_destination):
# read in all of the bytes and write to out destination
file_line = ""
# keep reading data until none is available
while True:
data = client_socket.recv(1024)
if not data:
break
else:
file_line += data
# now we take these bytes and try to write them out
try:
file_descriptor = open(upload_destination, "wb")
file_descriptor.write(file_line)
file_descriptor.close()
# acknowledge that we wrote the file out
client_socket.send("Succesfully saved file to %s\r\n" %
upload_destination)
except:
client_socket.send("Failed to save file to %s\r\n" %
upload_destination)
# check for command execution
if len(execute):
# run the command
output = run_command(execute)
client_socket.send(output)
# now we go into another loop if a command shell was requested
if command:
while True:
# show a simple prompt
client_socket.send("<BHP:#> ")
# now we receive until we see a linefeed (enter key)
cmd_line = ""
while "\n" not in cmd_line:
cmd_line += client_socket.recv(1024)
# send back the command output
response = run_command(cmd_line)
# send back the response
client_socket.send(response)
main()
when i run it, and close it with CTRL+D it exits and when i close the terminal i get this message in localhost:
<BHP:#> Failed to execite command.
<BHP:#>
if anyone can help me fix this or even point me in the right direction i'd really appreciate it :), i'm trying to run this in python 2.7

Python UDP networking socket.error: [Errno 10049]

I am trying to establish a simple UDP connection using Python code, between 2 PCs through internet.
Code run on PC_1:
import socket
import time
HOST = "ip_address_of_PC2"
PORT = 5555
data = "Hello World!!"
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
while True:
s.sendto(data, (HOST, PORT))
print "sent: ",data
time.sleep(1)
code run on the 2nd PC:
import socket
HOST = "ip_address_of_PC1"
PORT = 5555
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind((HOST,PORT))
while True:
print s.recv(30)
While running the code on 2nd PC am getting following error message:
return getattr(self._sock,name)(*args)
socket.error: [Errno 10049] The requested address is not valid in its context
change print s.recv(30) to:
data, addr = s.recvfrom(30)
print data
and in the 2nd PC code, the HOST variable needs the value of the 2nd PC ip, not the first one:
HOST = "ip_address_of_PC2"
Code run on PC1:
import socket
import time
HOST = "public ip_address_of_PC2"
PORT = 5555
data = "Hello World!!"
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
while True:
s.sendto(data, (HOST, PORT))
print "sent: ",data
time.sleep(1)
Code run on PC2:
import socket
HOST = "private ip_address_of_PC2"
PORT = 5555
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind((HOST,PORT))
while True:
print s.recv(30)

Web Server: socket programming for TCP connections in Python

I'm trying to run a python web server. The server says is running so I assume it is all working, except that I can only see the html text. The jpeg/image and the pdf files won't dispaly. Here is what i have so far.
#import socket module
from socket import *
serverSocket = socket(AF_INET, SOCK_STREAM)
serverSocket.bind(('', 12000))
serverSocket.listen(1)
while True:
print 'Ready to serve...'
connectionSocket, addr = serverSocket.accept()
print 'Required connection', addr
try:
message = connectionSocket.recv(1024)
filename = message.split()[1]
f = open(filename[1:])
outputdata = f.read()
#Fill in start
connectionSocket.send('HTTP/1.0 200 OK\r\n\r\n')
#Fill in end
#Send the content of the requested file to the client
for i in range(0, len(outputdata)):
connectionSocket.send(outputdata[i])
connectionSocket.close()
except IOError:
#Send response message for file not found
#Fill in start
connectionSocket.send('404 Not Found')
#Fill in end
#Close client socket
#Fill in start
connectionSocket.close()
#Fill in end
serverSocket.close()
I'm working on the same thing. I added the line:
connectionSocket.send('Content-Type: image/jpeg')
right after this:
connectionSocket.send('HTTP/1.0 200 OK')
I assume I'm/we're just missing some line in the header.