def live_stream_start(): lan = flask.request.get_json(force=True) channel_name = lan['channel_name'] user = lan['user'] os.system('./start ' + channel_name) today = str(date.today()) print(today) s = '' for c in today: if c != '-': s += c s = s[:len(s) - 2] s += '12' for files in os.listdir(s): print(files) fil = files print(fil) var = str(int(time.time() * 1000)) + '.mp4' for files in os.listdir(s[:] + '/' + fil): if 'mp4' in files: #uu.encode(s+'/'+fil+'/'+files,'video.txt') uu.encode(s + '/' + fil + '/' + files, var + '.txt') break #res = client.add('video.txt') res = upload_file(var + '.txt') hash_file = res fil = open(user + '.txt', 'a+') #fil.write('\n'+hash_file+'.'+str(int(time.time()*1000))+'.mp4') fil.write('\n' + hash_file + '.' + var) fil.close() os.system('rm -rf ' + s) return 'True'
def test_encode(self): fin = fout = None try: support.unlink(self.tmpin) fin = open(self.tmpin, 'wb') fin.write(plaintext) fin.close() fin = open(self.tmpin, 'rb') fout = open(self.tmpout, 'wb') uu.encode(fin, fout, self.tmpin, mode=0o644) fin.close() fout.close() fout = open(self.tmpout, 'rb') s = fout.read() fout.close() self.assertEqual(s, encodedtextwrapped(0o644, self.tmpin)) # in_file and out_file as filenames uu.encode(self.tmpin, self.tmpout, self.tmpin, mode=0o644) fout = open(self.tmpout, 'rb') s = fout.read() fout.close() self.assertEqual(s, encodedtextwrapped(0o644, self.tmpin)) finally: self._kill(fin) self._kill(fout)
def get_payload(self, i=None): # taken from http://hg.python.org/cpython/file/0926adcc335c/Lib/email/message.py # Copyright (C) 2001-2006 Python Software Foundation # See PY-LIC for licence if i is None: payload = self._payload elif not isinstance(self._payload, list): raise TypeError('Expected list, got %s' % type(self._payload)) else: payload = self._payload[i] if self.is_multipart(): return payload cte = self.get('content-transfer-encoding', '').lower() if cte == 'quoted-printable': return encoders._qencode(payload) elif cte == 'base64': try: return encoders._bencode(payload) except binascii.Error: # Incorrect padding return payload elif cte in ('x-uuencode', 'uuencode', 'uue', 'x-uue'): sfp = StringIO() try: uu.encode(StringIO(payload + '\n'), sfp, quiet=True) payload = sfp.getvalue() except uu.Error: # Some decoding problem return payload # Everything else, including encodings with 8bit or 7bit are returned # unchanged. return payload
def encode_sample(file_path): enc_file_path = file_path + '.uu' uu.encode(file_path, enc_file_path) if os.path.exists(enc_file_path): return True return False
def test_encode(self): try: fin = open(self.tmpin, "wb") fin.write(plaintext) fin.close() fin = open(self.tmpin, "rb") fout = open(self.tmpout, "w") uu.encode(fin, fout, self.tmpin, mode=0644) fin.close() fout.close() fout = open(self.tmpout, "r") s = fout.read() fout.close() self.assertEqual(s, encodedtextwrapped % (0644, self.tmpin)) # in_file and out_file as filenames uu.encode(self.tmpin, self.tmpout, mode=0644) fout = open(self.tmpout, "r") s = fout.read() fout.close() self.assertEqual(s, encodedtextwrapped % (0644, self.tmpin)) finally: self._kill(fin) self._kill(fout)
def createAttachment(workdir, srcdir, filename, accountid, description): zip = "att.zip" now = datetime.datetime.now() dn = "%04d%02d%02d%02d%02d%02d"%(now.year, now.month, now.day, now.hour, now.minute, now.second) sdir = os.path.join(workdir, dn) os.mkdir(sdir) fullpath = os.path.join(srcdir, filename) cmd = "cp "+fullpath+" "+sdir logger.debug(cmd) (r,c) = commands.getstatusoutput(cmd) if r: msg = "Copy source %s to workdir failed "%(fullpath)+" "+str(c) logger.error(msg) mailError(msg) raise PRException(msg) csvname = os.path.join(sdir, "request.txt") open(csvname, "w").write("Name,ParentId,Body,Description\n%s,%s,#%s,%s\n"%(filename, accountid, filename, description)) zipname = os.path.join(sdir, zip) cmd = "(cd %s;zip %s request.txt %s)"%(sdir, zipname, filename) (r,c) = commands.getstatusoutput(cmd) if r: msg = "Creating zip %s failed: %s"%(zipname, c) raise PRException(msg) uuname = os.path.join(sdir, "att.uue") uu.encode(zipname, uuname, zip) return sdir,zipname,uuname
def get_payload(self, i=None): # taken from http://hg.python.org/cpython/file/0926adcc335c/Lib/email/message.py # Copyright (C) 2001-2006 Python Software Foundation # See PY-LIC for licence if i is None: payload = self._payload elif not isinstance(self._payload, list): raise TypeError('Expected list, got %s' % type(self._payload)) else: payload = self._payload[i] if self.is_multipart(): return payload cte = self.get('content-transfer-encoding', '').lower() if cte == 'quoted-printable': return encoders._qencode(payload) elif cte == 'base64': try: return encoders._bencode(payload) except binascii.Error: # Incorrect padding return payload elif cte in ('x-uuencode', 'uuencode', 'uue', 'x-uue'): sfp = StringIO() try: uu.encode(StringIO(payload+'\n'), sfp, quiet=True) payload = sfp.getvalue() except uu.Error: # Some decoding problem return payload # Everything else, including encodings with 8bit or 7bit are returned # unchanged. return payload
def test_encode(self): fin = fout = None try: test_support.unlink(self.tmpin) fin = open(self.tmpin, 'org.eclipse.wb') fin.write(plaintext) fin.close() fin = open(self.tmpin, 'rb') fout = open(self.tmpout, 'w') uu.encode(fin, fout, self.tmpin, mode=0644) fin.close() fout.close() fout = open(self.tmpout, 'r') s = fout.read() fout.close() self.assertEqual(s, encodedtextwrapped % (0644, self.tmpin)) # in_file and out_file as filenames uu.encode(self.tmpin, self.tmpout, self.tmpin, mode=0644) fout = open(self.tmpout, 'r') s = fout.read() fout.close() self.assertEqual(s, encodedtextwrapped % (0644, self.tmpin)) finally: self._kill(fin) self._kill(fout)
def uu_encoded(self): logging.debug('EncodedFiles.uu_encoded()') buf = io.BytesIO(self._make_tgz()) out_buf = io.BytesIO() uu.encode(buf, out_buf) out_buf.seek(0) return out_buf.read().decode('ascii').splitlines()
def test_newlines_escaped(self): # Test newlines are escaped with uu.encode inp = io.BytesIO(plaintext) out = io.BytesIO() filename = "test.txt\n\roverflow.txt" safefilename = b"test.txt\\n\\roverflow.txt" uu.encode(inp, out, filename) self.assertIn(safefilename, out.getvalue())
def reverse(self, data): meta = metavars(data) path = meta.get('path', None) name = path and pathlib.Path(path).name with MemoryFile(data) as stream: with MemoryFile() as output: uu.encode(stream, output, name, backtick=True) return output.getvalue()
def test_encode(self): sys.stdin = cStringIO.StringIO(plaintext) sys.stdout = cStringIO.StringIO() uu.encode("-", "-", "t1", 0666) self.assertEqual( sys.stdout.getvalue(), encodedtextwrapped % (0666, "t1") )
def test_encode(self): inp = io.BytesIO(plaintext) out = io.BytesIO() uu.encode(inp, out, "t1") self.assertEqual(out.getvalue(), encodedtextwrapped(0o666, "t1")) inp = io.BytesIO(plaintext) out = io.BytesIO() uu.encode(inp, out, "t1", 0o644) self.assertEqual(out.getvalue(), encodedtextwrapped(0o644, "t1"))
def upgrade_fw(self, local_path: str) -> None: # No sftp in dropbear # with self.open_sftp() as sftp: # sftp.put(local_path, '/tmp/fwupdate.bin') stdin, _stdout, _stderr = self.exec_command('uudecode -o /tmp/fwupdate.bin', timeout=240) uu.encode(local_path, stdin, backtick=True) stdin.flush() stdin.close() self.exec_command('/sbin/fwupdate -m', timeout=20)
def leer_archivo(self, nom_arch): arch_texto = self.msj_dir + 'temp.txt' uu.encode(nom_arch, arch_texto) arch = open(arch_texto, 'rb') cont = arch.read() arch.close() self.sha1 = self.codificar(cont) self.sha1 += " " return cont
def test_encode(self): inp = cStringIO.StringIO(plaintext) out = cStringIO.StringIO() uu.encode(inp, out, "t1") self.assertEqual(out.getvalue(), encodedtextwrapped % (0666, "t1")) inp = cStringIO.StringIO(plaintext) out = cStringIO.StringIO() uu.encode(inp, out, "t1", 0644) self.assertEqual(out.getvalue(), encodedtextwrapped % (0644, "t1"))
def test_uu_encode_decode(self, payload, name, quiet): input_file = io.BytesIO(payload) encoded_file = io.BytesIO() decoded_file = io.BytesIO() uu.encode(input_file, encoded_file, name=name) encoded_file.seek(0) uu.decode(encoded_file, out_file=decoded_file, quiet=quiet) decoded_payload = decoded_file.getvalue() assert payload == decoded_payload
def test_encode(self): inp = io.BytesIO(plaintext) out = io.BytesIO() uu.encode(inp, out, 't1') self.assertEqual(out.getvalue(), encodedtextwrapped(438, 't1')) inp = io.BytesIO(plaintext) out = io.BytesIO() uu.encode(inp, out, 't1', 420) self.assertEqual(out.getvalue(), encodedtextwrapped(420, 't1'))
def comptest(s): print 'original length:', len(s),' ', s print 'zlib compressed length:', len(zlib.compress(s)),' ', zlib.compress(s) print 'bz2 compressed length:', len(bz2.compress(s)),' ', bz2.compress(s) out = StringIO.StringIO() infile = StringIO.StringIO(s) uu.encode(infile, out) print 'uu:', len(out.getvalue()), out.getvalue()
def videoIntoString(videoNumber): print("Inside Video into String function!") uu.encode('./videoBuffer/video' + str(videoNumber) + '.mp4', './videoBuffer/videoTemp.txt') f = open('./videoBuffer/videoTemp.txt', 'r') #Log the step into the logFile #logFile.write("Converted the videoNumber : " + str(videoNumber) + " into txtfile.") return f.read()
def convert_refs(ref_file_orig): content = open(ref_file_orig).read() buf_out = StringIO() zipped = gzip.GzipFile(filename=ref_file_orig, mode="w", fileobj=buf_out) zipped.write(content) zipped.close() val = buf_out.getvalue() out = open(ref_file_orig + ".gz.uu", "w") uu.encode(out_file=out, in_file=StringIO(val)) out.close()
def convert_refs(ref_file_orig): content = open(ref_file_orig).read() #buf=StringIO(content) buf_out = StringIO() # zipped = gzip.GzipFile(filename=ref_file_orig, mode="w", fileobj=buf_out) zipped.write(content) zipped.close() val = buf_out.getvalue() out = open(ref_file_orig + ".gz.uu", "w") #print val uu.encode(out_file=out, in_file=StringIO(val)) out.close()
def fuzz(workfile_in, workfile_out): with open(sys.argv[1], "rb") as fp: data_orig = fp.read() out_decode = workfile_in out_encode = workfile_out try: uu.decode(sys.argv[1], out_decode, mode=0o600, quiet=True) except uu.Error: pass uu.encode(sys.argv[1], out_encode) uu.decode(out_encode, out_decode, mode=0o600) with open(out_decode, "rb") as fp: data_encdec = fp.read() assert data_orig == data_encdec
def vid(): lan = flask.request.get_json(force=True) user = lan['user'] name = lan['name'] image = lan['image'] with open(name, 'wb') as fh: fh.write(base64.b64decode(image)) uu.encode(name, 'video.txt') res = client.add('video.txt') hash_file = res['Hash'] fil = open(user + '.txt', 'a+') fil.write('\n' + hash_file + name) fil.close() os.remove(name) return 'True'
def set_uuencode_payload(msg, data): """Encodees the payload with uuencode""" outfile = BytesIO() ct = msg.get("Content-Type", "") cd = msg.get("Content-Disposition", "") params = dict(HEADER_PARAMS.findall(ct)) params.update(dict(HEADER_PARAMS.findall(cd))) name = params.get("filename") or params.get("name") uu.encode(BytesIO(data), outfile, name=name) enc_data = outfile.getvalue() msg.set_payload(enc_data)
def uuencode_action(target, source, env): if env['UUE_ELF'] == '': strUUEPre = env['UUE_PRE'] strUUEPost = env['UUE_POST'] else: tElfFile = env['UUE_ELF'] if( isinstance(tElfFile, list) or isinstance(tElfFile, SCons.Node.NodeList) ): strElfFileName = tElfFile[0].get_path() elif isinstance(tElfFile, SCons.Node.FS.Base): strElfFileName = tElfFile.get_path() else: strElfFileName = tElfFile # Extract the segments. atSegments = elf_support.get_segment_table(env, strElfFileName) # Get the load address. ulLoadAddress = elf_support.get_load_address(atSegments) # Get the estimated binary size from the segments. ulEstimatedBinSize = elf_support.get_estimated_bin_size(atSegments) # Get the execution address. ulExecAddress = elf_support.get_exec_address(env, strElfFileName) aSubst = dict({ 'EXEC_DEZ': ulExecAddress, 'EXEC_HEX': '%x' % ulExecAddress, 'LOAD_DEZ': ulLoadAddress, 'LOAD_HEX': '%x' % ulLoadAddress, 'SIZE_DEZ': ulEstimatedBinSize, 'SIZE_HEX': '%x' % ulEstimatedBinSize }) strUUEPre = Template(env['UUE_PRE']).safe_substitute(aSubst) strUUEPost = Template(env['UUE_POST']).safe_substitute(aSubst) file_source = open(source[0].get_path(), 'rb') file_target = open(target[0].get_path(), 'wt') file_target.write(strUUEPre) uu.encode(file_source, file_target) file_target.write(strUUEPost) file_source.close() file_target.close() return 0
def img_to_xml(self, url): url=url.replace("-small", "") data=urllib.urlopen(url).read() fh=open("/tmp/img.jpg", "w") fh.write(data) fh.close() im = Image.open("/tmp/img.jpg") uu.encode("/tmp/img.jpg" , "/tmp/img.xml") fh=open("/tmp/img.xml", "r") data=fh.read() fh.close() return([data, im.size])
def test_encode(self): with open(self.tmpin, 'wb') as fin: fin.write(plaintext) with open(self.tmpin, 'rb') as fin: with open(self.tmpout, 'w') as fout: uu.encode(fin, fout, self.tmpin, mode=0o644) with open(self.tmpout, 'r') as fout: s = fout.read() self.assertEqual(s, encodedtextwrapped % (0o644, self.tmpin)) # in_file and out_file as filenames uu.encode(self.tmpin, self.tmpout, self.tmpin, mode=0o644) with open(self.tmpout, 'r') as fout: s = fout.read() self.assertEqual(s, encodedtextwrapped % (0o644, self.tmpin))
def test_encode(self): with open(self.tmpin, 'wb') as fin: fin.write(plaintext) with open(self.tmpin, 'rb') as fin: with open(self.tmpout, 'wb') as fout: uu.encode(fin, fout, self.tmpin, mode=0o644) with open(self.tmpout, 'rb') as fout: s = fout.read() self.assertEqual(s, encodedtextwrapped(0o644, self.tmpin)) # in_file and out_file as filenames uu.encode(self.tmpin, self.tmpout, self.tmpin, mode=0o644) with open(self.tmpout, 'rb') as fout: s = fout.read() self.assertEqual(s, encodedtextwrapped(0o644, self.tmpin))
def gen_icon(self,url): data=urllib.urlopen(url).read() fh=open("/tmp/thumb", "w") fh.write(data) fh.close() size = 150,150 im = Image.open("/tmp/thumb") im.thumbnail(size, Image.ANTIALIAS) im.save("/tmp/thumb.png", "PNG") uu.encode("/tmp/thumb.png" , "/tmp/thumb.xml") fh=open("/tmp/thumb.xml", "r") data=fh.read() fh.close() return([data,im.size])
def uuencode_action(target, source, env): if env['UUE_ELF']=='': strUUEPre = env['UUE_PRE'] strUUEPost = env['UUE_POST'] else: tElfFile = env['UUE_ELF'] if isinstance(tElfFile, ListType) or isinstance(tElfFile, SCons.Node.NodeList): strElfFileName = tElfFile[0].get_path() elif isinstance(tElfFile, SCons.Node.FS.Base): strElfFileName = tElfFile.get_path() else: strElfFileName = tElfFile # Extract the segments. atSegments = elf_support.get_segment_table(env, strElfFileName) # Get the load address. ulLoadAddress = elf_support.get_load_address(atSegments) # Get the estimated binary size from the segments. ulEstimatedBinSize = elf_support.get_estimated_bin_size(atSegments) # Get the execution address. ulExecAddress = elf_support.get_exec_address(env, strElfFileName) aSubst = dict({ 'EXEC_DEZ': ulExecAddress, 'EXEC_HEX': '%x'%ulExecAddress, 'LOAD_DEZ': ulLoadAddress, 'LOAD_HEX': '%x'%ulLoadAddress, 'SIZE_DEZ': ulEstimatedBinSize, 'SIZE_HEX': '%x'%ulEstimatedBinSize }) strUUEPre = Template(env['UUE_PRE']).safe_substitute(aSubst) strUUEPost = Template(env['UUE_POST']).safe_substitute(aSubst) file_source = open(source[0].get_path(), 'rb') file_target = open(target[0].get_path(), 'wt') file_target.write(strUUEPre) uu.encode(file_source, file_target) file_target.write(strUUEPost) file_source.close() file_target.close() return 0
def test_encode(self): try: fin = open(self.tmpin, 'wb') fin.write(plaintext) fin.close() fin = open(self.tmpin, 'rb') fout = open(self.tmpout, 'w') uu.encode(fin, fout, self.tmpin, mode=0644) fin.close() fout.close() fout = open(self.tmpout, 'r') s = fout.read() fout.close() self.assertEqual(s, encodedtextwrapped % (0644, self.tmpin)) finally: self._kill(fin) self._kill(fout)
def test_encode(self): try: fin = open(self.tmpin, 'wb') fin.write(plaintext) fin.close() fin = open(self.tmpin, 'rb') fout = open(self.tmpout, 'w') uu.encode(fin, fout, self.tmpin, mode=0644) fin.close() fout.close() fout = open(self.tmpout, 'r') s = fout.read() fout.close() self.assertEqual(s, encodedtextwrapped % (0644, self.tmpin)) # in_file and out_file as filenames # If the 'name' argument is not passed to uu.encode then it # defaults to filename i.e. 'testfile' instead of c:\testfile # resulting in an AssertionError. This is only seen on Symbian # as TESTFN is a path. if sys.platform == 'symbian_s60': uu.encode(self.tmpin, self.tmpout, self.tmpin, mode=0644) else: uu.encode(self.tmpin, self.tmpout, mode=0644) fout = open(self.tmpout, 'r') s = fout.read() fout.close() self.assertEqual(s, encodedtextwrapped % (0644, self.tmpin)) finally: self._kill(fin) self._kill(fout)
def handle(self): put = self.wfile.write challenge = hexlify(os.urandom(3))######[:5] put('\nWelcome to the Dr. Utonium computer! As he usually says, passwords are out-of-style nowadays. So I\'m going to test if you\'re my lovely boss through crypto challenges that only him can solve <3\n\nFirst of all, let\'s fight fire with fire. BLAKE2B(X) = %s. Let me know X. Hint: my $X =~ ^[0-9a-f]{6}$\nSolution: ' % miblake2.BLAKE2b(challenge).hexdigest().strip()) print "input: " + challenge response = self.rfile.readline()[:-1] if response != challenge: put('You\'re a cheater! Get out of here, now.\n') return random.seed(datetime.now()) o_challenge = btc_addr[randint(0,len(btc_addr)-1)] challenge = hexlify(base58.b58decode(o_challenge)) challenge = "Iep! Next! FINAL! " + challenge[::-1] key = "ANDYRLZANDYRLZANDYRLZANDYRLZANDYRLZANDYRLZANDYRLZANDYRLZANDYRLZANDYRLZANDYRLZANDYRLZANDYRLZANDYRLZANDYRLZANDYRLZANDYRLZANDYRLZANDYRLZANDYRLZANDYRLZANDYRLZANDYRLZANDYRLZANDYRLZANDYRLZANDYRLZANDYRLZANDYRLZANDYRLZANDYRLZANDYRLZ" x_challenge = '' for x in range (0,len(challenge)): x_challenge += str(ord(challenge[x])^ord(key[x])) + ',' challenge = "Iep! Next! " + x_challenge.rstrip(',') outf = StringIO.StringIO() inf = StringIO.StringIO(challenge) uu.encode(inf, outf) challenge = "Iep! Next! " + outf.getvalue() challenge = "Iep! Next! " + rot43(challenge) challenge = base64.b16encode(challenge) put(call_mojo()) put('\nHmmm...ok, here is your challenge. Hint: !yenom eht em wohS\n\n' + challenge + "\n\nSolution: ") challenge = balance(o_challenge) print " --- " + str(challenge*0.00000001) sol = self.rfile.readline().strip() if (len(sol)>15) or (not re.match('^[0-9]+\.[0-9]+$', sol)): put('You\'re a cheater! Get out of here, now.\nHint: ^[0-9]+\\.[0-9]+$\n') return if float(sol) != float(challenge*0.00000001): put('You\'re a cheater! Get out of here, now.\n') return put('%s\n' % FLAG) print " ^^^ Right!"
def test_encode(self): inp = io.BytesIO(plaintext) out = io.BytesIO() uu.encode(inp, out, "t1") self.assertEqual(out.getvalue(), encodedtextwrapped(0o666, "t1")) inp = io.BytesIO(plaintext) out = io.BytesIO() uu.encode(inp, out, "t1", 0o644) self.assertEqual(out.getvalue(), encodedtextwrapped(0o644, "t1")) inp = io.BytesIO(plaintext) out = io.BytesIO() uu.encode(inp, out, "t1", backtick=True) self.assertEqual(out.getvalue(), encodedtextwrapped(0o666, "t1", True)) with self.assertRaises(TypeError): uu.encode(inp, out, "t1", 0o644, True)
def test_encode(self): fin = fout = None try: support.unlink(self.tmpin) fin = open(self.tmpin, 'wb') fin.write(plaintext) fin.close() fin = open(self.tmpin, 'rb') fout = open(self.tmpout, 'wb') uu.encode(fin, fout, self.tmpin, mode=420) fin.close() fout.close() fout = open(self.tmpout, 'rb') s = fout.read() fout.close() self.assertEqual(s, encodedtextwrapped(420, self.tmpin)) uu.encode(self.tmpin, self.tmpout, self.tmpin, mode=420) fout = open(self.tmpout, 'rb') s = fout.read() fout.close() self.assertEqual(s, encodedtextwrapped(420, self.tmpin)) finally: self._kill(fin) self._kill(fout)
def pack(self,command,result): # Exception! self.service = command.service self.method = command.method self.result = result self.exception = result.exception self.command = command if(self.exception != '' and self.exception != 'None'): status = "FAILED" else: status = 'OK' ## if type is not a String, then we UUEncode it # and the receiver will decode. dataResult = result.result if self.command.encode: print "Encoding data ..." infile = StringIO.StringIO(dataResult) outfile = StringIO.StringIO() uu.encode( infile, outfile ) dataResult = outfile.getvalue() ## we Need to replace any ]]> chars with special marker ## to avoid screwing up the XML CDATA section if dataResult.find(']]>') > -1: print 'Check complete' dataResult = string.replace(dataResult, ']]>', self.END_OF_CDATA_TOKEN) resultXML = "<SbServerReply status='%s' ><data><![CDATA[%s]]></data><message><![CDATA[%s]]></message></SbServerReply>" % (status, dataResult, self.exception) resultHeader = 'XML:RESULT:%07d' % len(resultXML) self.buffer = array.array('c', resultHeader + ':' + resultXML)
def encode(input, output, encoding): if encoding == 'base64': import base64 return base64.encode(input, output) if encoding == 'quoted-printable': import quopri return quopri.encode(input, output, 0) if encoding in ('uuencode', 'x-uuencode', 'uue', 'x-uue'): import uu return uu.encode(input, output) if encodetab.has_key(encoding): pipethrough(input, encodetab[encoding], output) else: raise ValueError, \ 'unknown Content-Transfer-Encoding: %s' % encoding
def encode(input, output, encoding): if encoding == 'base64': import base64 return base64.encode(input, output) if encoding == 'quoted-printable': import quopri return quopri.encode(input, output, 0) if encoding in ('uuencode', 'x-uuencode', 'uue', 'x-uue'): import uu return uu.encode(input, output) if encoding in ('7bit', '8bit'): return output.write(input.read()) else: raise ValueError, \ 'unknown Content-Transfer-Encoding: %s' % encoding
def encode(input, output, encoding): if encoding == 'base64': import base64 return base64.encode(input, output) if encoding == 'quoted-printable': import quopri return quopri.encode(input, output, 0) if encoding in ('uuencode', 'x-uuencode', 'uue', 'x-uue'): import uu return uu.encode(input, output) if encoding in ('7bit', '8bit'): return output.write(input.read()) if encoding in encodetab: pipethrough(input, encodetab[encoding], output) else: raise ValueError, 'unknown Content-Transfer-Encoding: %s' % encoding
def encode(input, output, encoding): """Encode common content-transfer-encodings (base64, quopri, uuencode).""" if encoding == 'base64': import base64 return base64.encode(input, output) if encoding == 'quoted-printable': import quopri return quopri.encode(input, output, 0) if encoding in ('uuencode', 'x-uuencode', 'uue', 'x-uue'): import uu return uu.encode(input, output) if encoding in ('7bit', '8bit'): return output.write(input.read()) if encoding in encodetab: pipethrough(input, encodetab[encoding], output) else: raise ValueError, 'unknown Content-Transfer-Encoding: %s' % encoding
def encode(input, output, encoding): """Encode common content-transfer-encodings (base64, quopri, uuencode).""" if encoding == 'base64': import base64 return base64.encode(input, output) if encoding == 'quoted-printable': import quopri return quopri.encode(input, output, 0) if encoding in ('uuencode', 'x-uuencode', 'uue', 'x-uue'): import uu return uu.encode(input, output) if encoding in ('7bit', '8bit'): output.write(input.read()) if encodetab.has_key(encoding): pipethrough(input, encodetab[encoding], output) else: raise ValueError, \ 'unknown Content-Transfer-Encoding: %s' % encoding
def test_encode(self): sys.stdin = FakeIO(plaintext.decode("ascii")) sys.stdout = FakeIO() uu.encode("-", "-", "t1", 0o666) self.assertEqual(sys.stdout.getvalue(), encodedtextwrapped(0o666, "t1").decode("ascii"))
def uuencode(self, string): # uu encode a srting stringio = StringIO() uu.encode(StringIO(string), stringio) return stringio.getvalue()
def main(script, infile, outfile): """ Write a script and embed the infile. On run of the script it will create the outfile :param script: (String) Path to script to be created :param infile: (String) Path to infile to be embedded :param outfile: (String) Path to outfile that will be created :return: 2: Problem validating path/files """ # If no script is specified. use the name of the infile as a template if script is None: infile_path = os.path.dirname(infile) if os.path.isdir(infile_path): script = '{0}/{1}_expand.py'.format( infile_path, os.path.basename(infile).replace('.', '_')) else: print('Path to infile is invalid, check destination and try again') exit(2) # If no outfile, assume the outfile will be the same file if outfile is None: outfile = infile # Cannot proceed without a file to embed if not os.path.isfile(infile): print('File to embed cannot be found, check destination and try again') exit(2) # Temporary file to contain the uuencode data tmp_path = '/tmp/' + os.path.splitext(os.path.basename(infile))[0] + '.tmp' # print summary print('{0:10s} : {1}'.format('infile', infile)) print('{0:10s} : {1}'.format('outfile', outfile)) print('{0:10s} : {1}'.format('script', script)) # Header of the script header = '\n'.join([ '#!/usr/bin/env python3\n', 'import uu\n', 'data = """', ]) # Footer of the script footer = '\n'.join([ '"""\n', 'with open("{0}", "w") as tmp_file:'.format(tmp_path), ' tmp_file.write(data)', ' tmp_file.close()', 'uu.decode("{0}")'.format(tmp_path), '', '## TODO: Insert code to work with file unpacked', '', 'exit()\n', ]) # Write the script try: uu.encode(infile, tmp_path, outfile) tmp_file = open(tmp_path) with open(script, 'w') as script_file: script_file.write(header) script_file.write(tmp_file.read()) script_file.write(footer) script_file.close() except uu.Error as err: print(err) exit(3) # Make the script executable os.chmod(script, 0o755) return 0
from test_support import verify, TestFailed, verbose, TESTFN import sys, os import uu from StringIO import StringIO teststr = "The smooth-scaled python crept over the sleeping dog\n" expected = """\ M5&AE('-M;V]T:\"US8V%L960@<'ET:&]N(&-R97!T(&]V97(@=&AE('-L965P (:6YG(&1O9PH """ encoded1 = "begin 666 t1\n"+expected+"\n \nend\n" if verbose: print '1. encode file->file' inp = StringIO(teststr) out = StringIO() uu.encode(inp, out, "t1") verify(out.getvalue() == encoded1) inp = StringIO(teststr) out = StringIO() uu.encode(inp, out, "t1", 0644) verify(out.getvalue() == "begin 644 t1\n"+expected+"\n \nend\n") if verbose: print '2. decode file->file' inp = StringIO(encoded1) out = StringIO() uu.decode(inp, out) verify(out.getvalue() == teststr) inp = StringIO("""UUencoded files may contain many lines, even some that have 'begin' in them.\n"""+encoded1) out = StringIO()
__author__ = 'luowen' "uu module allowing arbitrary binary data to be transferred over ASCII-only connections" import uu # encode demo inFile = open('base64Demo.py', 'rb') outFile = open('tmp.bin', 'wb') uu.encode(inFile, outFile) # decode demo inFile = open('tmp.bin', 'rb') outFile = open('base64demo1.py', 'wb') uu.decode(inFile, outFile)
"""Various tools used by MIME-reading or MIME-writing programs."""
""" Tests for uu module. Nick Mathewson """ from test_support import verify, TestFailed, verbose, TESTFN import sys, os import uu from StringIO import StringIO teststr = "The smooth-scaled python crept over the sleeping dog\n" expected = """\ M5&AE('-M;V]T:\"US8V%L960@<'ET:&]N(&-R97!T(&]V97(@=&AE('-L965P (:6YG(&1O9PH """ encoded1 = "begin 666 t1\n"+expected+"\n \nend\n" if verbose: print '1. encode file->file' inp = StringIO(teststr) out = StringIO() uu.encode(inp, out, "t1") verify(out.getvalue() == encoded1) inp = StringIO(teststr) out = StringIO() uu.encode(inp, out, "t1", 0644) verify(out.getvalue() == "begin 644 t1\n"+expected+"\n \nend\n") if verbose: print '2. decode file->file' inp = StringIO(encoded1) out = StringIO() uu.decode(inp, out) verify(out.getvalue() == teststr) inp = StringIO("""UUencoded files may contain many lines,
import uu import os, sys infile = "samples/sample.jpg" uu.encode(infile, sys.stdout, os.path.basename(infile)) ## begin 666 sample.jpg ## M_]C_X 02D9)1@ ! 0 0 ! #_VP!# @&!@<&!0@'!P<)"0@*#!0-# L+ ## M#!D2$P\4'1H?'AT:'!P@)"XG("(L(QP<*#<I+# Q-#0T'R<Y/3@R/"XS-#+_ ## MVP!# 0D)"0P+#!@-#1@R(1PA,C(R,C(R,C(R,C(R,C(R,C(R,C(R,C(R,C(R ## M,C(R,C(R,C(R,C(R,C(R,C(R,C(R,C+_P 1" " ( # 2( A$! Q$!_\0 ## M'P 04! 0$! 0$ $" P0%!@<("0H+_\0 M1 @$# P($ P4%
def uu_encoder(msg): """For BBB only, don't send uuencoded emails""" orig = StringIO(msg.get_payload()) encdata = StringIO() uu.encode(orig, encdata) msg.set_payload(encdata.getvalue())