Exemple #1
0
        count = 0
        destination = socket.create_connection(("127.0.0.1", 6000))
        sockets = [self.request, destination]
        while True:
            inp, out, exce = select.select(sockets, [], [])
            for s in inp:
                if s == self.request:
                    data = s.recv(1048576)
                    count += 1
                    if data == "":
                        print "-" * 144
                        return
                    print "Going Content"
                    print list(map(ord, str(data)))
                    destination.send(data)
                elif s == destination:
                    data = s.recv(1048576)
                    if data == "":
                        print "-" * 144
                        return
                    content, ver, length = struct.unpack('>BHH', data[:5])
                    print "Receiving Content"
                    print list(map(ord, str(data)))
                    self.request.send(data)
        return


ssl_serverloc = ("127.0.0.1", 6001)
SocketServer.TCPServer.allow_reuse_address = True
ssl_server = SocketServer.TCPServer(ssl_serverloc, mitmserver)
ssl_server.serve_forever()
Exemple #2
0
import SimpleHTTPServer
import SocketServer
import sys
PORT = 80
if len(sys.argv) != 2:
    print("use: web.exe port")
else:
    PORT = int(sys.argv[1])
    Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
    httpd = SocketServer.TCPServer(("", PORT), Handler)
    print "SimpleHTTPServer is ", PORT
    print "by k8gege"
    httpd.serve_forever()
Exemple #3
0
            print "didn't find a user"
            return

        # insert numbers they are allowed to insert
        insertable_numbers = [
            n for n in requested_numbers if requesting_user.may("put", n)
        ]
        NUMS += insertable_numbers
        NUMS = sorted(list(set(NUMS)))

        # reset the list if the user wants to and is allowed to
        if requesting_user.may("reset", NUMS):
            if re.search("RESET", path):
                NUMS = []

        # then return all then numbers they are allowed to see
        viewable_numbers = [n for n in NUMS if requesting_user.may("get", n)]
        self.wfile.write("The numbers are: {}".format(viewable_numbers))
        print "all ", NUMS
        print "sent", viewable_numbers


if __name__ == "__main__":
    try:
        httpd = SocketServer.TCPServer(("", 8000), NumberHandler)
        print "listening on 8000"
        httpd.serve_forever()
    except KeyboardInterrupt:
        print "SHUTTING DOWN!!!!!"
        httpd.shutdown()
Exemple #4
0
"""
This is a very simple TCP server that does not use SSL. It simply completes
the 3-way handshake and closes the connection.
"""
import SocketServer, SimpleHTTPServer


class MyTCPHandler(SocketServer.BaseRequestHandler):
    def handle(self):
        print 'incoming ', self.client_address[0]
        self.request.close()
        # run your custom code


if __name__ == "__main__":
    # Create the server, binding to localhost on port 443
    server = SocketServer.TCPServer(("", 443), MyTCPHandler)
    server.serve_forever()
Exemple #5
0
        response = h.doCommand(s.path)
        s.send_response(responseCode)
        s.end_headers()
        s.wfile.write(response)

    def version_string(s):
        return "Minecraft & Openstack"


if __name__ == '__main__':
    f = open("mc2os_config.txt", "r")
    for line in f:
        line = line.replace("\n", "")
        if line.startswith("LISTEN"):
            name = line.split('=')[1]
            HOST_NAME = name.split(':')[0]
            PORT_NUMBER = int(name.split(':')[1])
        if line.startswith("USERNAME"):
            helper.USERNAME = line.split('=')[1]
        if line.startswith("PASSWORD"):
            helper.PASSWORD = line.split('=')[1]
        if line.startswith("PROJECT"):
            helper.PROJECT = line.split('=')[1]
        if line.startswith("AUTHURL"):
            helper.AUTHURL = line.split('=')[1]
    f.close()
    Handler = MyHandler
    httpd = SocketServer.TCPServer((HOST_NAME, PORT_NUMBER), Handler)

    httpd.serve_forever()
Exemple #6
0
        return data

    def process_tag(self, data, tag, json_dic={}):
        print "  processing $%s$" % tag
        if tag in json_dic.keys():
            data = data.replace("$" + tag + "$", json_dic[tag])
        elif tag.startswith("INCLUDE[") and tag.endswith("]"):
            fn = tag[8:-1]
            fn = os.path.join(base_path, fn)
            d = open(fn).read()
            p0 = data.find("$" + tag)
            p1 = data.find("]", p0) + 2
            data = data[:p0] + d + data[p1:]

        return data


if __name__ == '__main__':
    print "=" * 60
    print "Serving files from:"
    print base_path
    print "\ntags.json is located at:"
    print tools_path
    print "\nOpen your browser at http://localhost:" + str(server_port)

    os.chdir(base_path)
    print "=" * 60
    handler = MyHandler
    server = SocketServer.TCPServer(("", server_port), handler)
    server.serve_forever()
Exemple #7
0
#    traceback.print_tb()
            

# minimal web server.  serves files relative to the
# current directory.
logging.basicConfig(level=logging.INFO)
if settings.DEBUG:
    logging.getLogger("blendfile").setLevel(logging.DEBUG)
    logging.getLogger("server").setLevel(logging.DEBUG)
    logging.getLogger("indexer").setLevel(logging.DEBUG)
else:
    logging.getLogger("blendfile").setLevel(logging.INFO)
    logging.getLogger("server").setLevel(logging.INFO)
    logging.getLogger("indexer").setLevel(logging.INFO)
indexer.setup()
os.chdir("www")
httpd=None
log.info("Blender-aid "+str(settings.VERSION)+" ["+settings.VERSION_DESCRIPTION+"]")
log.info("starting server on "+str(settings.WEBSERVER_BINDING))
while httpd == None:
    try:
        httpd = SocketServer.TCPServer(settings.WEBSERVER_BINDING, MyHandler)
    except:
        httpd = None
        log.info("waiting")
        time.sleep(5)
        
log.info("server started on "+str(settings.WEBSERVER_BINDING))
log.info("browse to http://"+str(settings.WEBSERVER_BINDING[0])+":"+str(settings.WEBSERVER_BINDING[1])+"/")
httpd.serve_forever()
Exemple #8
0
        data = self.other.read(size)
        print repr(data)
        return data

    def flush(self):
        return self.other.flush()

    def close(self):
        return self.other.close()


if __name__ == '__main__':
    import codecs, socket, threading

    address = ('localhost', 0)  # auto-port number
    server = SocketServer.TCPServer(address, Echo)

    # Set up server
    t = threading.Thread(target=server.serve_forever)
    t.setDaemon(True)  # don't hang on exit
    t.start()

    # Connect to server
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect(server.server_address)

    # Wrap the socket with a reader and a writer
    incoming = codecs.getreader('utf-8')(PassThrough(s.makefile('r')))
    outgoing = codecs.getwriter('utf-8')(PassThrough(s.makefile('w')))

    # Send the data
Exemple #9
0
                credentials.refresh()

            try:
                xero = Xero(credentials)

            except XeroException as e:
                self.send_error(500,
                                message='{}: {}'.format(
                                    e.__class__, e.message))
                return

            page_body = 'Your contacts:<br><br>'

            contacts = xero.contacts.all()

            if contacts:
                page_body += '<br>'.join(
                    [str(contact) for contact in contacts])
            else:
                page_body += 'No contacts'
            self.page_response(title='Xero Contacts', body=page_body)
            return

        SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self)


if __name__ == '__main__':
    httpd = SocketServer.TCPServer(("", PORT), PartnerCredentialsHandler)

    print "serving at port", PORT
    httpd.serve_forever()
#  Licensed to the Apache Software Foundation (ASF) under one
#  or more contributor license agreements.  See the NOTICE file
#  distributed with this work for additional information
#  regarding copyright ownership.  The ASF licenses this file
#  to you under the Apache License, Version 2.0 (the
#  "License"); you may not use this file except in compliance
#  with the License.  You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
# limitations under the License.
################################################################################

import SimpleHTTPServer
import SocketServer

handler = SimpleHTTPServer.SimpleHTTPRequestHandler

# azure says that ports are still in use if this is not set
SocketServer.TCPServer.allow_reuse_address = True
httpd = SocketServer.TCPServer(("", 9999), handler)

try:
    httpd.handle_request()
except:
    httpd.shutdown()
        self.sinterrupt.listen(1)

        self.ccontrol, cinfo = self.scontrol.accept()
        self.cinterrupt, cinfo = self.sinterrupt.accept()


class JsonResponseHandler(SimpleHTTPRequestHandler):
    def do_POST(self):
        content_len = int(self.headers.get("content-length"))
        requestBody = self.rfile.read(content_len).decode('UTF-8')
        jsonData = json.loads(requestBody)
        self.send_response(200)
        self.send_header("Content-type", "Application/json")
        self.end_headers()
        hid.send_cmd(jsonData["control"])
        time.sleep(0.01)
        hid.release_cmd()


if __name__ == "__main__":
    try:
        DBusGMainLoop(set_as_default=True)
        hid = Hid()
        server = SocketServer.TCPServer(("", 8000), JsonResponseHandler)
        server.serve_forever()
    except KeyboardInterrupt as ex:
        server.server_close()
        hid.close()
    except BluetoothError as ex:
        print("Bluetooth ERROR!")
Exemple #12
0
 def run(self):
     server = SocketServer.TCPServer(parseAddress(options.tcpAddress),
                                     CommandHandler)
     server.serve_forever()
Exemple #13
0
import SimpleHTTPServer
import SocketServer
import urlparse


class CustomResponseHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200)
        self.end_headers()
        self.wfile.write("a" * 9000)
        self.wfile.close()


httpd = SocketServer.TCPServer(("", 80), CustomResponseHandler)
httpd.serve_forever()
Exemple #14
0
# Host HTTP Python
import SimpleHTTPServer
import SocketServer

HOST = '0.0.0.0'
PORT = 8000

Handler = SimpleHTTPServer.SimpleHTTPRequestHandler

httpd = SocketServer.TCPServer((HOST, PORT), Handler)

print "View log at http://%s:%d" % (HOST, PORT)
httpd.serve_forever()
        except socket.error, e:
            print 'Records sending error: {}'.format(e)
        except IOError:
            print 'File with records not found'
            self.wfile.write('~')

    def handle_unknown(self):
        raise RuntimeError('Can not recognize received command')


def clear_directory():
    """
    Remove outdated records text files if they exist
    These files produced by previous runs and not deleted during error
    occured
    """
    records_directory = os.path.join(os.getcwd(), 'records')
    if os.path.isdir(records_directory):
        rmtree(records_directory)
        print 'Records cleared'
    os.mkdir(records_directory)


if __name__ == '__main__':
    clear_directory()

    host, port = 'localhost', 9000
    server = SocketServer.TCPServer((host, port), CustomTCPHandler)
    server.serve_forever()
    server.allow_reuse_address = True
Exemple #16
0
import os
import sys
import random
import SimpleHTTPServer

import SocketServer as socketserver

class MyHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
    path_to_image = ''

    def do_GET(self):
        self.send_response(200)
        self.send_header("Content-type", "image/jpg")
        self.end_headers()
        random_pic = '{}{}'.format(
            self.path_to_image,
            random.choice(os.listdir(self.path_to_image)))
        print random_pic
        f = open(random_pic, 'rb')
        self.wfile.write(f.read())
        f.close()

if __name__ == "__main__":
    try:
        MyHandler.path_to_image = sys.argv[1]
        server = socketserver.TCPServer(("", 8080), MyHandler)
        server.serve_forever()
    except IndexError:
        print "Missing PATH to folder"
    except KeyboardInterrupt:
        print "Server stopped"
Exemple #17
0
class MyHandler(BaseHTTPRequestHandler):
    def do_POST(self):
        content_len = int(self.headers.getheader('content-length', 0))
        post_body = self.rfile.read(content_len)

        id = uniqid()
        sud_file = dir + id + ".sud.conll"
        ud_file = dir + id + ".ud.conll"
        with open(sud_file, 'w') as f:
            f.write(post_body)

        try:
            subprocess.call([
                grew, "transform", "-grs", grs, "-i", sud_file, "-o", ud_file
            ])
        except:
            self.send_response(402)
            return

        self.send_response(200)
        self.send_header('Content-type', 'text/plain')
        self.end_headers()

        file = open(ud_file, "r")
        self.wfile.write(file.read())


httpd = SocketServer.TCPServer(("", 8383), MyHandler)
httpd.serve_forever()
Exemple #18
0
                    command)  # Send the command APDU to the ESP32
                response = self.request.recv(
                    257).strip()  # Get the response APDU
            except SocketError:  # ESP32 probably disconnected
                err = 1  # Set the error flag

            processing = 0  # Processing finished, got the response
            newCommand = 0  # Reset the newCommand flag
            condResponse.notify()


if __name__ == '__main__':
    HOST, PORT = '10.42.0.1', 5511

    SocketServer.TCPServer.allow_reuse_address = True
    server = SocketServer.TCPServer((HOST, PORT), handleConnection)
    srvThrd = threading.Thread(target=server.serve_forever)
    srvThrd.daemon = True
    srvThrd.start()

    global command  # The command APDU
    global response  # The response APDU
    global condCommand  # Condition to wait until a new APDU command arrives
    global condResponse  # Condition to wait until a response is available
    global newCommand  # Flag for the handler that there is a new command
    global processing  # Flag for the run function that the processing has finished
    global err  # Flag for the run function that an error happened

    condCommand = threading.Condition()
    condResponse = threading.Condition()
class EchoRequestHandler(SocketServer.BaseRequestHandler):
    def handle(self):
        # Echo the back to the client
        while True:
            data = self.request.recv(1024)

            if data:
                self.request.send(data)
            else:
                print "close socket"
                break
        return


if __name__ == '__main__':
    import threading

    address = ('localhost', 0)  # let the kernel give us a port
    server = SocketServer.TCPServer(address, EchoRequestHandler)
    ip, port = server.server_address  # find out what port we were given

    t = threading.Thread(target=server.serve_forever)
    t.setDaemon(True)  # don't hang on exit
    t.start()

    while True:
        pass

    # Clean up
    server.socket.close()
Exemple #20
0
import SimpleHTTPServer
import SocketServer
import sys


class ServerHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
    def do_GET(self):
        print(self.headers)
        SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self)


if __name__ == "__main__":
    if len(sys.argv) == 2:
        try:
            port = int(sys.argv[1])
        except:
            port = 80
    else:
        port = 80
    Handler = ServerHandler
    SocketServer.TCPServer(("", port), Handler).serve_forever()
the only observable side-channel is the wait time.
"""

import SocketServer
import zlib
import random
import string
import time
from common import send_blob, recv_blob

secret = ''.join([random.choice(string.printable) for c in range(20)])

class MyTCPHandler(SocketServer.BaseRequestHandler):

  def handle(self):
    data = recv_blob(self.request)
    msg = zlib.compress('user_data=%s;secret=%s' % (data, secret))
    t = sum([random.randint(600,700) / 1000. for i in range(len(msg) / 300)])
    time.sleep(t)
    send_blob(self.request, 'ok')
    return

if __name__ == "__main__":
  HOST, PORT = "0.0.0.0", 30001

  print('THE SECRET IS %s' % repr(secret))

  SocketServer.TCPServer.allow_reuse_address = True
  server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler)
  server.serve_forever()
Exemple #22
0
                return self.list_directory(path)
        ctype = self.guess_type(path)
        try:
            # Always read in binary mode. Opening files in text mode may cause
            # newline translations, making the actual size of the content
            # transmitted *less* than the content-length!
            f = open(path, 'rb')
        except IOError:
            if os.path.islink(path):
                linkto = os.readlink(path)
                if os.path.exists(linkto):
                    f = open(linkto, 'rb')
                else:
                    self.send_error(404, "Symlink not found")
                    return None
            else:
                self.send_error(404, "File not found")
                return None
        self.send_response(200)
        self.send_header("Content-type", ctype)
        fs = os.fstat(f.fileno())
        self.send_header("Content-Length", str(fs[6]))
        self.send_header("Last-Modified", self.date_time_string(fs.st_mtime))
        self.end_headers()
        return f


httpd = SocketServer.TCPServer(("", PORT), SymlinksHandler)

print "serving at port", PORT
httpd.serve_forever()
Exemple #23
0
def get_simple_http_server():
    handler = SimpleTestHTTPRequestHandler
    httpd = SocketServer.TCPServer(("localhost", 0), handler)
    return httpd
Exemple #24
0
                                      % ( all_entries, self.path ))
        # Display web refresh info only if setting is turned on
        f.write('</b></p>')
        length = f.tell()
        f.seek(0)
        self.send_response(200)
        encoding = sys.getfilesystemencoding()
        self.send_header("Content-type", "text/html; charset=%s" % encoding)
        self.send_header("Content-Length", str(length))
        self.end_headers()
        return f

# Start Web Server Processing        
os.chdir(web_server_root)
SocketServer.TCPServer.allow_reuse_address = True
httpd = SocketServer.TCPServer(("", web_server_port), DirectoryHandler)
print("----------------------------------------------------------------")
print("%s %s" % ( prog_name, version))
print("---------------------------- Settings --------------------------")
print("Server  - web_page_title   = %s" % ( web_page_title ))
print("          web_server_root  = %s/%s" % ( base_dir, web_server_root ))
print("          web_server_port  = %i " % ( web_server_port ))
print("Content - web_image_height = %s px (height of content)" % ( web_image_height))
print("          web_iframe_width = %s  web_iframe_height = %s" % ( web_iframe_width, web_iframe_height ))
print("          web_iframe_width_usage = %s (of avail screen)" % ( web_iframe_width_usage))
print("          web_page_refresh_sec = %s  (default=180 sec)" % (  web_page_refresh_sec ))
print("          web_page_blank = %s ( True=blank left pane until item selected)" % ( web_page_blank ))
print("Listing - web_max_list_entries = %s ( 0=all )" % ( web_max_list_entries ))
print("          web_list_by_datetime = %s  sort_decending = %s" % ( web_list_by_datetime, web_list_sort_descending ))
print("----------------------------------------------------------------")
print("From a computer on the same LAN. Use a Web Browser to access this server at")
Exemple #25
0
        if length <= 125:
            self.request.send(chr(length))
        elif length >= 126 and length <= 65535:
            self.request.send(126)
            self.request.send(struct.pack(">H", length))
        else:
            self.request.send(127)
            self.request.send(struct.pack(">Q", length))
        self.request.send(message)

    def handshake(self):
        data = self.request.recv(1024).strip()
        headers = Message(StringIO(data.split('\r\n', 1)[1]))
        if headers.get("Upgrade", None) != "websocket":
            return
        print 'Handshaking...'
        key = headers['Sec-WebSocket-Key']
        digest = b64encode(sha1(key + self.magic).hexdigest().decode('hex'))
        response = 'HTTP/1.1 101 Switching Protocols\r\n'
        response += 'Upgrade: websocket\r\n'
        response += 'Connection: Upgrade\r\n'
        response += 'Sec-WebSocket-Accept: %s\r\n\r\n' % digest
        self.handshake_done = self.request.send(response)

    def on_message(self, message):
        print messsage


if __name__ == "__main__":
    server = SocketServer.TCPServer(("localhost", 9999), WebSocketsHandler)
    server.serve_forever()
Exemple #26
0
        # Even though the final file will be in memory the module uses temp
        # files during assembly for efficiency. To avoid this on servers that
        # don't allow temp files, for example the Google APP Engine, set the
        # 'in_memory' constructor option to True:
        workbook = xlsxwriter.Workbook(output, {'in_memory': True})
        worksheet = workbook.add_worksheet()

        # Write some test data.
        worksheet.write(0, 0, 'Hello, world!')

        # Close the workbook before streaming the data.
        workbook.close()

        # Rewind the buffer.
        output.seek(0)

        # Construct a server response.
        self.send_response(200)
        self.send_header('Content-Disposition', 'attachment; filename=test.xlsx')
        self.send_header('Content-type',
                         'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
        self.end_headers()
        self.wfile.write(output.read())
        return


print('Server listening on port 8000...')
httpd = SocketServer.TCPServer(('', 8000), Handler)
httpd.serve_forever()
Exemple #27
0
def main():
    arguments = docopt(__doc__, version='0.1.3')
    if arguments['--dir'] is not None:
        static_path = arguments['--dir']
    else:
        static_path = os.path.join(os.getcwd(), 'static')

    if arguments['generate']:
        command = (
            "wget "
            "--recursive "  # follow links to download entire site
            "--convert-links "  # make links relative
            "--page-requisites "  # grab everything: css / inlined images
            "--no-parent "  # don't go to parent level
            "--directory-prefix {1} "  # download contents to static/ folder
            "--no-host-directories "  # don't create domain named folder
            "--restrict-file-name=unix "  # don't escape query string
            "{0}").format(arguments['--domain'], static_path)
        os.system(command)

        if arguments['--domain']:
            domain = arguments['--domain']
        else:
            domain = 'http://localhost:2368'
        target_domain = arguments['--target_domain']

        # remove query string since Ghost 0.4
        file_regex = re.compile(r'.*?(\?.*)')
        for root, dirs, filenames in os.walk(static_path):
            for filename in filenames:
                if file_regex.match(filename):
                    newname = re.sub(r'\?.*', '', filename)
                    print "Rename", filename, "=>", newname
                    os.rename(os.path.join(root, filename),
                              os.path.join(root, newname))

        # remove superfluous "index.html" from relative hyperlinks found in text
        abs_url_regex = re.compile(r'^(?:[a-z]+:)?//', flags=re.IGNORECASE)

        def fixLinks(text, parser):
            d = PyQuery(bytes(bytearray(text, encoding='utf-8')),
                        parser=parser)
            for element in d('a'):
                e = PyQuery(element)
                href = e.attr('href')
                if not abs_url_regex.search(href):
                    new_href = re.sub(r'rss/index\.html$', 'rss/index.rss',
                                      href)
                    new_href = re.sub(r'/index\.html$', '/', new_href)
                    e.attr('href', new_href)
                    print "\t", href, "=>", new_href
            if parser == 'html':
                return d.html(method='html').encode('utf8')
            return d.__unicode__().encode('utf8')

        def fix_share_links(text, parser):
            filetext = text.decode('utf8')
            td_regex = re.compile(target_domain + '|')

            assert target_domain, "target domain must be specified --target_domain=<http://your-host-url>"
            d = PyQuery(bytes(bytearray(filetext, encoding='utf-8')),
                        parser=parser)
            for share_class in ['.share_links a']:
                print "share_class : ", share_class
                for element in d(share_class):
                    e = PyQuery(element)
                    print "element : ", e
                    href = e.attr('href')
                    print "href : ", href
                    print "domain : ", domain
                    print "target_domain : ", target_domain
                    new_href = re.sub(domain, target_domain, href)
                    e.attr('href', new_href)
                    print "\t", href, "=>", new_href
            if parser == 'html':
                return d.html(method='html').encode('utf8')
            return d.__unicode__().encode('utf8')

        def fix_meta_url_links(text, parser):
            filetext = text.decode('utf8')
            td_regex = re.compile(target_domain + '|')

            assert target_domain, "target domain must be specified --target_domain=<http://your-host-url>"
            d = PyQuery(bytes(bytearray(filetext, encoding='utf-8')),
                        parser=parser)
            for share_class in [
                    'meta[property="og:url"], meta[name="twitter:url"]'
            ]:
                print "share_class : ", share_class
                for element in d(share_class):
                    e = PyQuery(element)
                    print "element : ", e
                    href = e.attr('content')
                    print "href : ", href
                    print "domain : ", domain
                    print "target_domain : ", target_domain
                    new_href = re.sub(domain, target_domain, href)
                    e.attr('content', new_href)
                    print "\t", href, "=>", new_href
            if parser == 'html':
                return d.html(method='html').encode('utf8')
            return d.__unicode__().encode('utf8')

        def fix_meta_image_links(text, parser):
            filetext = text.decode('utf8')
            td_regex = re.compile(target_domain + '|')

            assert target_domain, "target domain must be specified --target_domain=<http://your-host-url>"
            d = PyQuery(bytes(bytearray(filetext, encoding='utf-8')),
                        parser=parser)
            for share_class in [
                    'meta[property="og:image"], meta[name="twitter:image"]'
            ]:
                print "share_class : ", share_class
                for element in d(share_class):
                    e = PyQuery(element)
                    print "element : ", e
                    href = e.attr('content')
                    print "href : ", href
                    print "domain : ", domain
                    content_target_domain = target_domain.replace(
                        "/static", "")
                    print "target_domain : ", content_target_domain
                    new_href = re.sub(domain, content_target_domain, href)
                    e.attr('content', new_href)
                    print "\t", href, "=>", new_href
            if parser == 'html':
                return d.html(method='html').encode('utf8')
            return d.__unicode__().encode('utf8')

        # fix links in all html files
        for root, dirs, filenames in os.walk(static_path):
            for filename in fnmatch.filter(filenames, "*.html"):
                filepath = os.path.join(root, filename)
                parser = 'html'
                if root.endswith("/rss"):  # rename rss index.html to index.rss
                    parser = 'xml'
                    newfilepath = os.path.join(
                        root,
                        os.path.splitext(filename)[0] + ".rss")
                    os.rename(filepath, newfilepath)
                    filepath = newfilepath
                with open(filepath) as f:
                    filetext = f.read().decode('utf8')
                print "fixing links in ", filepath
                newtext = fixLinks(filetext, parser)
                newtext = fix_share_links(newtext, parser)
                newtext = fix_meta_url_links(newtext, parser)
                newtext = fix_meta_image_links(newtext, parser)
                with open(filepath, 'w') as f:
                    f.write(newtext)

    elif arguments['preview']:
        os.chdir(static_path)

        Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
        httpd = SocketServer.TCPServer(("", 9000), Handler)

        print "Serving at port 9000"
        # gracefully handle interrupt here
        httpd.serve_forever()

    elif arguments['setup']:
        if arguments['--gh-repo']:
            repo_url = arguments['--gh-repo']
        else:
            repo_url = raw_input("Enter the Github repository URL:\n").strip()

        # Create a fresh new static files directory
        if os.path.isdir(static_path):
            confirm = raw_input(
                "This will destroy everything inside static/."
                " Are you sure you want to continue? (y/N)").strip()
            if confirm != 'y' and confirm != 'Y':
                sys.exit(0)
            shutil.rmtree(static_path)

        # User/Organization page -> master branch
        # Project page -> gh-pages branch
        branch = 'gh-pages'
        regex = re.compile(".*[\w-]+\.github\.(?:io|com).*")
        if regex.match(repo_url):
            branch = 'master'

        # Prepare git repository
        repo = Repo.init(static_path)
        git = repo.git

        if branch == 'gh-pages':
            git.checkout(b='gh-pages')
        repo.create_remote('origin', repo_url)

        # Add README
        file_path = os.path.join(static_path, 'README.md')
        with open(file_path, 'w') as f:
            f.write(
                '# Blog\nPowered by [Ghost](http://ghost.org) and [Buster](https://github.com/axitkhurana/buster/).\n'
            )

        print "All set! You can generate and deploy now."

    elif arguments['deploy']:
        repo = Repo(static_path)
        repo.git.add('.')

        current_time = strftime("%Y-%m-%d %H:%M:%S", gmtime())
        repo.index.commit('Blog update at {}'.format(current_time))

        origin = repo.remotes.origin
        repo.git.execute(
            ['git', 'push', '-u', origin.name, repo.active_branch.name])
        print "Good job! Deployed to Github Pages."

    elif arguments['add-domain']:
        repo = Repo(static_path)
        custom_domain = arguments['<domain-name>']

        file_path = os.path.join(static_path, 'CNAME')
        with open(file_path, 'w') as f:
            f.write(custom_domain + '\n')

        print "Added CNAME file to repo. Use `deploy` to deploy"

    else:
        print __doc__
Exemple #28
0
def unused_port():
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.bind((interface, 0))
    port = sock.getsockname()[1]
    sock.close()
    return port


service_port = unused_port()
addon.setSetting('http.service.port', str(service_port))
xbmc.log('OneDrive Download service port: ' + str(service_port),
         xbmc.LOGNOTICE)

SocketServer.TCPServer.allow_reuse_address = True

service_server = SocketServer.TCPServer((interface, service_port), download)
service_server.server_activate()
service_server.timeout = 1

if dirlist_allow:
    dirlist_port = int(addon.getSetting('port_directory_listing'))
    dirlist_server = SocketServer.TCPServer((interface, dirlist_port), source)
    dirlist_server.server_activate()
    dirlist_server.timeout = 1

if __name__ == '__main__':
    monitor = xbmc.Monitor()
    service_thread = threading.Thread(target=service_server.serve_forever)
    service_thread.daemon = True
    service_thread.start()
Exemple #29
0
images = os.listdir('img')
html = ''

# Build an HTML snippet that contains
# a JavaScript list of string-literals.
for img in images:
    html = html + '\"img/' + img + '\"'
    # Place a comma on the end
    # unless this is the last item in
    # the list
    if img != images[-1]:
        html = html + ','

with open('template.htm', "r") as tplfile:
    payload = tplfile.read()

# Replace $$1 and $$2 with the delay
# in milliseconds and generated list
# of images.  Write the output to
# index.html
payload = string.replace(payload, "$$1", delay_millis)
payload = string.replace(payload, "$$2", html)
with open("index.html", "w") as indexfile:
    indexfile.write(payload)

    # Now, start serving up pages
Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
httpd = SocketServer.TCPServer(("", 80), Handler)
print "HTTP server running..."
httpd.serve_forever()
Exemple #30
0
for entry in settings['domains']:
    domain = entry['domain']
    for host in entry['hosts']:
        args.append("-d")
        if host == '.':
            fqdn = domain
        else:
            fqdn = host + '.' + domain
        args.append(fqdn)

print("Args: ", args)

os.chdir('host')

Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
httpd = SocketServer.TCPServer(("", port), Handler)

# Start a thread with the server
server_thread = threading.Thread(target=httpd.serve_forever)

# Exit the server thread when the main thread terminates
server_thread.daemon = True
server_thread.start()
print("Server loop listening on port ", port, ". Running in thread: ",
      server_thread.name)

print("Starting Let's Encrypt process in 1 minute...")

time.sleep(60)

print("Calling letsencrypt...")