Skip to content

Instantly share code, notes, and snippets.

@briarfox
Last active Aug 29, 2015
Embed
What would you like to do?
Wifi Transfer
'''Usage:
args:
server - Opens in server mode
ip | path - uploads file to device
example:
192.168.1.50 Projects/example project
192.168.1.50:8090 testProject.py
no args: console prompts
'''
##Server Port##
port = 8080
###############
import requests
import os
import io
import socket
import SocketServer,threading
import sys
import re
import tarfile
import StringIO
##Socket Server
class EchoRequestHandler(SocketServer.BaseRequestHandler):
def setup(self):
#self.request.send('Client: Recieving Data...')
print 'Server: Recieving Request'
def handle(self):
data = ''
while True:
res = self.request.recv(4096)
if res.strip() == 'EXIT':
#self.request.send('Server: Shutting down')
print 'Server: Shutting down****'
self.server.shutdown()
#self.server.server_close()
#self.finish()
break
if not res:
tar = tarfile.open(fileobj=StringIO.StringIO(data),mode ='r:gz')
tar.extractall(path='./WifiTransfer/')
print 'Server: Files saved.'
data = ''
break
data = data + res
def finish(self):
self.request.send('Client: complete')
print 'Server: Request complete'
#print 'Press any key to exit:'
#Create the tar file
def make_tarfile(source_dir):
#zf = tempfile.TemporaryFile(prefix='wifitransfer', suffix='.tar.gz')
bytes = io.BytesIO()
path = os.path.abspath(os.path.join(os.getcwd(),source_dir))
with tarfile.open(fileobj = bytes, mode="w:gz") as tar:
tar.add(path,arcname=os.path.basename(source_dir))
tar.close()
#with open('wifitransfer.tar.gz', 'w') as open_file:
# open_file.write(bytes.getvalue())
return bytes.getvalue()
#Client
def consolePrint(ip = None,path=None):
if not ip:
ip = raw_input('server ip: ')
if not path:
print "Use 'quit' to exit."
path = raw_input('File Path: ')
ipsplit = ip.split(':',2)
ipa = ipsplit[0]
ipp = ipsplit[1] if len(ipsplit)==2 else port
print ipa
print ipp
if path == 'quit':
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((ipa,ipp))
len_sent = s.sendall('EXIT')
#s.shutdown(1)
#rec = s.recv(len_sent)
#print rec
print 'Client: shutting down'
s.close
sys.exit(0)
try:
source_dir = os.path.join(os.path.dirname(__file__),path)
print source_dir
#print os.path.abspath(source_dir)
print 'Client: Preparing file.'
file = make_tarfile(source_dir)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ipport = ip.split()
s.connect((ipa,ipp))
len_sent = s.send(file)
s.shutdown(1)
rec = s.recv(len_sent)
print rec
s.close()
except:
print 'Invalid Dir/File'
consolePrint(ip=ip)
#r = requests.post('http://{server}:8080/upload'.format(server=ip), data = {"mysubmit":"Go"}, files={"archive": ("test.zip", file)})
#s.close()
#sys.exit(0)
#Get lan/wan ip
def getIp():
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(('8.8.8.8', 9))
address = address=s.getsockname()[0]
print '''
###########################################
To send a file connect to: {address}:{port}
###########################################
'''.format(address=address,port=port)
s.close()
#Server
def createServer():
print 'Starting Server...'
SocketServer.ThreadingTCPServer.allow_reuse_address = True
server = SocketServer.ThreadingTCPServer(('0.0.0.0',port),EchoRequestHandler)
#server.allow_reuse_address = True
#server.serve_forever()
t = threading.Thread(target=server.serve_forever)
t.setDaemon(True) # don't hang on exit
t.start()
# Connect to the server
#server.handle_request()
print('Server listening')
#run server
def server():
address = getIp()
createServer()
#raw_input('waiting')
#Run
if __name__ == '__main__':
if len(sys.argv) == 1:
print 'Mode: server|client.'
mode = raw_input('Mode: ')
if mode == 'client':
consolePrint()
elif mode == 'server':
server()
else:
print '*Test Mode*'
server()
consolePrint()
else:
if sys.argv[1] == 'server':
server()
elif sys.argv[1]=='test':
server()
consolePrint(ip=sys.argv[2],path=sys.argv[3])
else:
print sys.argv[1],sys.argv[2]
consolePrint(ip=sys.argv[1],path=sys.argv[2])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment