示例#1
0
    def format(self):
        import uos
        log.info("Formatting filesystem ...")

        while uos.listdir("/"):
            lst = uos.listdir("/")
            uos.chdir("/")
            while lst:
                try:
                    uos.remove(lst[0])
                    log.info("Removed '" + uos.getcwd() + "/" + lst[0] + "'")
                    lst = uos.listdir(uos.getcwd())
                except:
                    dir = lst[0]
                    log.info("Directory '" + uos.getcwd() + "/" + dir +
                             "' detected. Opening it...")
                    uos.chdir(dir)
                    lst = uos.listdir(uos.getcwd())
                    if len(lst) == 0:
                        log.info("Directory '" + uos.getcwd() +
                                 "' is empty. Removing it...")
                        uos.chdir("..")
                        uos.rmdir(dir)
                        break

        log.info("Format completed successfully")
示例#2
0
def del_directory(directory, sock=None):
    try:
        uos.rmdir(directory)
    except:
        out = "could not remove %s" % directory
        print(out)
        send_output(sock, out)
 async def RMD(self, stream, argument):
     try:
         os.rmdir(argument)
         await stream.awrite("257 Okey.\r\n")
     except OSError as e:
         await stream.awrite("550 {}.\r\n".format(e))
     return True
示例#4
0
 async def RMD(self, stream, argument):
     try:
         uos.rmdir(self.get_path(argument))
         await _awrite(stream, "257 Okey.\r\n")
     except Exception as e:
         await _awrite(stream, "550 {}.\r\n".format(e))
     return True
示例#5
0
def rmvdir(dir):
    for i in os.ilistdir(dir):
        if i[1] == 16384:
            rmvdir('{}/{}'.format(dir, i))
        elif i[1] == 32678:
            os.remove('{}/{}'.format(dir, i[0]))
    os.rmdir(dir)
示例#6
0
    def restore_backup(dir_to_restore='firmware'):
        target = 'backup'
        try:
            uos.rmdir(dir_to_restore)
        except OSError:
            pass

        uos.mkdir(dir_to_restore)
        move_f(target, dir_to_restore)
示例#7
0
def rm(path):
    if (not exists(path)):
        raise OSError(2, )
    if (stat.S_ISDIR(uos.stat(path)[stat.ST_MODE])):
        li = listdir(path)
        for i in li:
            rm(path + '/' + i, forced)
        uos.rmdir(path)
    else:
        uos.remove(path)
示例#8
0
    def backup(dir_to_backup='firmware'):
        target = 'backup'
        try:
            uos.rmdir(target)
        except OSError:
            pass

        uos.mkdir(target)

        move_f(dir_to_backup, target)
示例#9
0
    def __download_latest(self):
        target = 'firmware'
        try:
            uos.rmdir(target)
        except OSError:
            pass

        uos.mkdir(target)

        self.__download_from_git(git_dir=self.conf['remote'].get('root_dir', ''), target_dir=target)
示例#10
0
    def sync(source, target, delete=True, include=None, exclude=None):
        #just_contents = source.endswith('/')
        # source = source.rstrip('/')
        rel_paths = []
        if target.endswith('/'):
            tdir = target
        else:
            tdir = target[0:target.rfind('/') + 1]

        Util.mkdirs(tdir)

        if include is not None:
            include = re.compile(include)

        if exclude is not None:
            exclude = re.compile(exclude)

        for src_path in Util.walk(source):
            gc.collect()
            if include:
                if not include.match(src_path):
                    continue
            if exclude:
                if exclude.match(src_path):
                    continue
            rel_path = src_path[source.rfind('/') + 1:]
            tgt_path = target + rel_path

            rel_paths.append(rel_path)

            tgt_dir = tgt_path[0:tgt_path.rfind('/') + 1]
            Util.mkdirs(tgt_dir)

            Util.copy(src_path=src_path, tgt_path=tgt_path)

        if delete:
            if target.endswith('/'):
                tdir = target + source.split('/')[-1]
            else:
                tdir = target

            for existing in Util.walk(tdir):
                isdir = Util.isdir(existing)
                if isdir:
                    if len(uos.listdir(existing)):
                        continue
                if existing[tdir.rfind('/') + 1:] not in rel_paths:
                    if exclude:
                        if exclude.match(existing):
                            continue
                    if isdir:
                        uos.rmdir(existing)
                    else:
                        uos.remove(existing)
                    print("Deleted      %s" % existing)
示例#11
0
def rmdir(dir):
    print("rmdir contents:", dir)
    for f in uos.ilistdir(dir):
        if f[1] == 0x4000:
            rmdir(dir+"/"+f[0])
        else:
            print("rm", dir + '/' + f[0])
            uos.remove(dir + '/' + f[0])
    if dir != "/" and dir != "":
        print("rmdir", dir)
        uos.rmdir(dir)
def rm_r(dir: str) -> None:
    os.chdir(dir)
    for f in os.listdir():
        try:
            os.remove(f)
        except OSError:
            pass
    for f in os.listdir():
        rm_r(f)
    os.chdir("..")
    os.rmdir(dir)
示例#13
0
	def perform_uninstall(ok):
		global install_path
		if ok:
			easydraw.msg("Removing "+currentListTitles[selected]+"...", "Uninstalling...",True)
			install_path = "/lib" #FIXME
			for rm_file in os.listdir("%s/%s" % (install_path, currentListTargets[selected]["file"])):
				easydraw.msg("Deleting '"+rm_file+"'...")
				os.remove("%s/%s/%s" % (install_path, currentListTargets[selected]["file"], rm_file))
			easydraw.msg("Deleting folder...")
			os.rmdir("%s/%s" % (install_path, currentListTargets[selected]["file"]))
			easydraw.msg("Uninstall completed!")
		start()
示例#14
0
def rm(s):
    try:
        import uos as os
    except ImportError:
        import os
    try:
        _ = os.stat(s)[0]
        try:
            os.remove(s)  # A file
        except OSError:  # A folder
            for i in os.listdir(s):
                s_ = "{}/{}".format(s, i)
                rm(s_)
            os.rmdir(s)
    except OSError:
        print("Not found: '{}'".format(s))
示例#15
0
def exp():

    global depth

    for fd in uos.listdir():
        try:
            uos.remove(fd)
            print(('--' * depth) + "rm %s" % fd)
        except:
            print(('--' * depth) + "> %s" % fd)
            depth += 1
            uos.chdir(fd)
            exp()
            uos.chdir("..")
            depth -= 1
            uos.rmdir(fd)
            print(('--' * depth) + "rmdir %s" % fd)
示例#16
0
 def clean(C, path=E):
     A = path
     if A is E: A = C.path
     V('Clean/remove files in folder: {}'.format(A))
     try:
         G = os.listdir(A)
     except (D, F):
         return
     for H in G:
         B = a.format(A, H)
         try:
             os.remove(B)
         except D:
             try:
                 C.clean(B)
                 os.rmdir(B)
             except D:
                 pass
 def clean(E, path=C):
     A = path
     if A is C: A = E.path
     W('Clean/remove files in folder: {}'.format(A))
     try:
         G = os.listdir(A)
     except (D, F):
         return
     for H in G:
         B = Z.format(A, H)
         try:
             os.remove(B)
         except D:
             try:
                 E.clean(B)
                 os.rmdir(B)
             except D:
                 pass
示例#18
0
 def clean(self, path: str = None):
     if path is None:
         path = self.path
     print("Clean/remove files in folder: {}".format(path))
     try:
         items = os.listdir(path)
     except (OSError, AttributeError):
         return
     for fn in items:
         try:
             item = "{}/{}".format(path, fn)
             os.remove(item)
         except OSError:
             try:
                 self.clean(item)
                 os.rmdir(item)
             except OSError:
                 pass
示例#19
0
 def rm(self, files, opts):
     for f in files:
         try:
             m = uos.stat(f)[0]
         except OSError:
             print('No such file:', f)
             break
         if not self.is_dir(m):
             if 'v' in opts: print(f)
             if 'n' not in opts: uos.remove(f)
         else:
             if 'r' in opts:
                 self.rm((self.path(f, i[0]) for i in uos.ilistdir(f)),
                         opts)
                 if 'v' in opts: print(f)
                 if 'n' not in opts: uos.rmdir(f)
             else:
                 print('Can not remove directory "{}": Use "%rm -r"'.format(
                     f))
示例#20
0
 def clean(self, path: str = None):
     "Remove all files from the stub folder"
     if path is None:
         path = self.path
     self._log.info("Clean/remove files in folder: {}".format(path))
     try:
         items = os.listdir(path)
     except (OSError, AttributeError):  # lgtm [py/unreachable-statement]
         # os.listdir fails on unix
         return
     for fn in items:
         item = "{}/{}".format(path, fn)
         try:
             os.remove(item)
         except OSError:
             try:  # folder
                 self.clean(item)
                 os.rmdir(item)
             except OSError:
                 pass
示例#21
0
def wipe_dir(path=".", sub=True):
    print("wipe path {}".format(path))
    l = os.listdir(path)
    l.sort()
    #print(l)
    if l != ['']:
        for f in l:
            child = "{}/{}".format(path, f)
            #print(" - "+child)
            st = os.stat(child)
            if st[0] & 0x4000:  # stat.S_IFDIR
                if sub:
                    wipe_dir(child, sub)
                    try:
                        os.rmdir(child)
                    except:
                        print("Error deleting folder {}".format(child))
            else:  # File
                try:
                    os.remove(child)
                except:
                    print("Error deleting file {}".format(child))
示例#22
0
def ctap2(command):
    global ks_ctap2, ks_pin, REM_LAST_CMD
    if 'RESET_CTAP2' in listdir():  # reload keystore?
        rmdir('RESET_CTAP2')
        ks_ctap2 = KS_CTAP2()
    if 'RESET_PIN' in listdir():  # reload keystore?
        rmdir('RESET_PIN')
        ks_pin = KS_PIN()
    if len(command) == 0:
        return CTAP1_ERR_INVALID_LENGTH
    cmd, data = command[0], command[1:]
    REM_LAST_CMD = cmd
    if cmd == authenticatorGetInfo:
        if len(data) > 0:
            return CTAP1_ERR_INVALID_LENGTH
        return getInfo()
    elif cmd == authenticatorMakeCredential:
        if len(data) == 0:
            return CTAP1_ERR_INVALID_LENGTH
        return makeCredential(data)
    elif cmd == authenticatorGetAssertion:
        if len(data) == 0:
            return CTAP1_ERR_INVALID_LENGTH
        return getAssertion(data)
    elif cmd == authenticatorGetNextAssertion:
        if len(data) > 0:
            return CTAP1_ERR_INVALID_LENGTH
        return getNextAssertion()
    elif cmd == authenticatorClientPIN:
        if len(data) == 0:
            return CTAP1_ERR_INVALID_LENGTH
        return clientPIN(data)
    elif cmd == authenticatorReset:
        if len(data) > 0:
            return CTAP1_ERR_INVALID_LENGTH
        return reset()
    else:
        return CTAP2_ERR_OPERATION_DENIED
示例#23
0
def delete_file(nummer=0):
    ''' Verwijdert het bestand of folder uit de <lijst> met volgnummer <nummer>.
        Opgelet: voor het verwijderen van een folder moet die leeg zijn.'''
    global lijst, pwd
    # haal status bestand op
    stats = get_file_stats(nummer)
    # verwijder bestand/folder
    if stats[0] == 'F':  #bestand
        try:
            uos.remove(lijst[nummer - 1])
        except OSError as err:
            show_error('Verwijderen van bestand mislukt! - %s' % err)
            return
    elif stats[0] == 'D':  #folder
        try:
            uos.rmdir(lijst[nummer - 1])
        except OSError as err:
            show_error(
                'Verwijderen van folder mislukt. Is de folder wel leeg ? - %s'
                % err)
            return
    # update lijst
    get_files(pwd)
示例#24
0
    print('OSError')

# rename across a filesystem
try:
    uos.rename('/test_mnt/a', '/test_mnt2/b')
except OSError:
    print('OSError')

# delegating to mounted filesystem
uos.chdir('test_mnt')
print(uos.listdir())
print(uos.getcwd())
uos.mkdir('test_dir')
uos.remove('test_file')
uos.rename('test_file', 'test_file2')
uos.rmdir('test_dir')
print(uos.stat('test_file'))
print(uos.statvfs('/test_mnt'))
open('test_file')
open('test_file', 'wb')

# umount
uos.umount('/test_mnt')
uos.umount('/test_mnt2')

# umount a non-existent mount point
try:
    uos.umount('/test_mnt')
except OSError:
    print('OSError')
示例#25
0
  def exec_ftp_command(self, cl):
    global datasocket
    global client_busy
    global my_ip_addr

    try:
      collect()

      data = cl.readline().decode("utf-8").rstrip("\r\n")

      if len(data) <= 0:
          # No data, close
          # This part is NOT CLEAN; there is still a chance that a
          # closing data connection will be signalled as closing
          # command connection
          log_msg(1, "*** No data, assume QUIT")
          close_client(cl)
          return

      if client_busy:  # check if another client is busy
          cl.sendall("400 Device busy.\r\n")  # tell so the remote client
          return  # and quit
      client_busy = True  # now it's my turn

      # check for log-in state may done here, like
      # if self.logged_in == False and not command in\
      #    ("USER", "PASS", "QUIT"):
      #    cl.sendall("530 Not logged in.\r\n")
      #    return

      command = data.split()[0].upper()
      payload = data[len(command):].lstrip()  # partition is missing
      path = self.get_absolute_path(self.cwd, payload)
      log_msg(1, "Command={}, Payload={}".format(command, payload))

      if command == "USER":
        # self.logged_in = True
        cl.sendall("230 Logged in.\r\n")
        # If you want to see a password,return
        #   "331 Need password.\r\n" instead
        # If you want to reject an user, return
        #   "530 Not logged in.\r\n"
      elif command == "PASS":
        # you may check here for a valid password and return
        # "530 Not logged in.\r\n" in case it's wrong
        # self.logged_in = True
        cl.sendall("230 Logged in.\r\n")
      elif command == "SYST":
        cl.sendall("215 UNIX Type: L8\r\n")
      elif command in ("TYPE", "NOOP", "ABOR"):  # just accept & ignore
        cl.sendall('200 OK\r\n')
      elif command == "QUIT":
        cl.sendall('221 Bye.\r\n')
        close_client(cl)
      elif command == "PWD" or command == "XPWD":
        cl.sendall('257 "{}"\r\n'.format(self.cwd))
      elif command == "CWD" or command == "XCWD":
        try:
          if (uos.stat(path)[0] & 0o170000) == 0o040000:
            self.cwd = path
            cl.sendall('250 OK\r\n')
          else:
            cl.sendall('550 Fail\r\n')
        except:
          cl.sendall('550 Fail\r\n')
      elif command == "PASV":
        cl.sendall('227 Entering Passive Mode ({},{},{}).\r\n'.format(
          self.pasv_data_addr.replace('.', ','),
          _DATA_PORT >> 8, _DATA_PORT % 256))
        self.active = False
      elif command == "PORT":
        items = payload.split(",")
        if len(items) >= 6:
          self.act_data_addr = '.'.join(items[:4])
          if self.act_data_addr == "127.0.1.1":
            # replace by command session addr
            self.act_data_addr = self.remote_addr
          self.DATA_PORT = int(items[4]) * 256 + int(items[5])
          cl.sendall('200 OK\r\n')
          self.active = True
        else:
            cl.sendall('504 Fail\r\n')
      elif command == "LIST" or command == "NLST":
        if payload.startswith("-"):
          option = payload.split()[0].lower()
          path = self.get_absolute_path(
                 self.cwd, payload[len(option):].lstrip())
        else:
          option = ""
        try:
          data_client = self.open_dataclient()
          cl.sendall("150 Directory listing:\r\n")
          self.send_list_data(path, data_client,
                              command == "LIST" or 'l' in option)
          cl.sendall("226 Done.\r\n")
          data_client.close()
        except:
          cl.sendall('550 Fail\r\n')
          if data_client is not None:
            data_client.close()
      elif command == "RETR":
        try:
          data_client = self.open_dataclient()
          cl.sendall("150 Opened data connection.\r\n")
          self.send_file_data(path, data_client)
          # if the next statement is reached,
          # the data_client was closed.
          data_client = None
          cl.sendall("226 Done.\r\n")
        except:
          cl.sendall('550 Fail\r\n')
          if data_client is not None:
            data_client.close()
      elif command == "STOR" or command == "APPE":
        result = False
        try:
          data_client = self.open_dataclient()
          cl.sendall("150 Opened data connection.\r\n")
          if path == "/fpga":
            import ecp5
            ecp5.prog_stream(data_client,_CHUNK_SIZE)
            result = ecp5.prog_close()
            data_client.close()
          elif path.startswith("/flash@"):
            import ecp5
            dummy, addr = path.split("@")
            addr = int(addr)
            result = ecp5.flash_stream(data_client,addr)
            ecp5.flash_close()
            del addr, dummy
            data_client.close()
          elif path.startswith("/sd@"):
            import sdraw
            dummy, addr = path.split("@")
            addr = int(addr)
            sd_raw = sdraw.sdraw()
            result = sd_raw.sd_write_stream(data_client,addr)
            del sd_raw, addr, dummy
            data_client.close()
          else:
            self.save_file_data(path, data_client,
                                "w" if command == "STOR" else "a")
            result = True
          # if the next statement is reached,
          # the data_client was closed.
          data_client = None
        except:
          if data_client is not None:
            data_client.close()
        if result:
          cl.sendall("226 Done.\r\n")
        else:
          cl.sendall('550 Fail\r\n')
        del result
      elif command == "SIZE":
        try:
          cl.sendall('213 {}\r\n'.format(uos.stat(path)[6]))
        except:
          cl.sendall('550 Fail\r\n')
      elif command == "STAT":
        if payload == "":
          cl.sendall("211-Connected to ({})\r\n"
                     "    Data address ({})\r\n"
                     "    TYPE: Binary STRU: File MODE: Stream\r\n"
                     "    Session timeout {}\r\n"
                     "211 Client count is {}\r\n".format(
                      self.remote_addr, self.pasv_data_addr,
                      _COMMAND_TIMEOUT, len(client_list)))
        else:
          cl.sendall("213-Directory listing:\r\n")
          self.send_list_data(path, cl, True)
          cl.sendall("213 Done.\r\n")
      elif command == "DELE":
        try:
          uos.remove(path)
          cl.sendall('250 OK\r\n')
        except:
          cl.sendall('550 Fail\r\n')
      elif command == "RNFR":
        try:
          # just test if the name exists, exception if not
          uos.stat(path)
          self.fromname = path
          cl.sendall("350 Rename from\r\n")
        except:
          cl.sendall('550 Fail\r\n')
      elif command == "RNTO":
        try:
          uos.rename(self.fromname, path)
          cl.sendall('250 OK\r\n')
        except:
          cl.sendall('550 Fail\r\n')
        self.fromname = None
      elif command == "CDUP" or command == "XCUP":
        self.cwd = self.get_absolute_path(self.cwd, "..")
        cl.sendall('250 OK\r\n')
      elif command == "RMD" or command == "XRMD":
        try:
          uos.rmdir(path)
          cl.sendall('250 OK\r\n')
        except:
          cl.sendall('550 Fail\r\n')
      elif command == "MKD" or command == "XMKD":
        try:
          uos.mkdir(path)
          cl.sendall('250 OK\r\n')
        except:
          cl.sendall('550 Fail\r\n')
      elif command == "SITE":
        if path == "/mount":
          if self.mount():
            cl.sendall('250 OK\r\n')
          else:
            cl.sendall('550 Fail\r\n')
        elif path == "/umount":
          if self.umount():
            cl.sendall('250 OK\r\n')
          else:
            cl.sendall('550 Fail\r\n')
        elif path == "/passthru":
          import ecp5
          ecp5.passthru()
          cl.sendall('250 OK passthru\r\n')
        elif path.endswith(".bit") or path.endswith(".bit.gz"):
          try:
            import ecp5
            if ecp5.prog(path, close=False):
              if path.startswith("/sd/"):
                try:
                  self.umount()
                  cl.sendall('111 umount /sd OK\r\n')
                except:
                  cl.sendall('411 umount /sd Fail\r\n')
              if ecp5.prog_close():
                cl.sendall('250 OK\r\n')
              else:
                cl.sendall('550 Fail\r\n')
            else:
              cl.sendall('550 Fail\r\n')
          except:
            cl.sendall('550 Fail\r\n')
        else:
          if path.startswith("/"):
            exe=path[1:]
          else:
            exe=path
          try:
            exec(exe)
            cl.sendall('250 OK '+exe+'\r\n')
          except:
            cl.sendall('550 Fail '+exe+'\r\n')
          del exe
      else:
        cl.sendall("502 Unsupported command.\r\n")
        # log_msg(2,
        #  "Unsupported command {} with payload {}".format(command,
        #  payload))
    # handle unexpected errors
    except Exception as err:
      log_msg(1, "Exception in exec_ftp_command: {}".format(err))
    # tidy up before leaving
    client_busy = False
for exist in ('', '/', 'dir', '/dir', 'dir/subdir'):
    try:
        uos.mkdir(exist)
    except OSError as er:
        print('mkdir OSError', er.args[0] == 17) # EEXIST

uos.chdir('/')
print(uos.stat('test5.txt')[:-3])

uos.VfsFat.mkfs(bdev2)
uos.mount(bdev2, '/sys')
print(uos.listdir())
print(uos.listdir('sys'))
print(uos.listdir('/sys'))

uos.rmdir('dir2')
uos.remove('test5.txt')
print(uos.listdir())

uos.umount('/')
print(uos.getcwd())
print(uos.listdir())
print(uos.listdir('sys'))

# test importing a file from a mounted FS
import sys
sys.path.clear()
sys.path.append('/sys')
with open('sys/test_module.py', 'w') as f:
    f.write('print("test_module!")')
import test_module
示例#27
0
def ftpserver(timeout=300, inthread=False, prnip=True):
    global quiet_run
    quiet_run = inthread
    notify_quit = _thread.EXIT

    if prnip:
        print("Starting ftp server. Version 1.2")

    if not network.WLAN().wifiactive():
        print("WiFi not started!")
        return

    DATA_PORT = 1050

    ftpsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    datasocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    ftpsocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    datasocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

    ftpsocket.bind(socket.getaddrinfo("0.0.0.0", 21)[0][4])
    datasocket.bind(socket.getaddrinfo("0.0.0.0", DATA_PORT)[0][4])

    ftpsocket.listen(1)
    ftpsocket.settimeout(1)

    datasocket.listen(1)
    datasocket.settimeout(None)

    msg_250_OK = '250 OK\r\n'
    msg_550_fail = '550 Failed\r\n'
    addr = network.WLAN().ifconfig()[0]
    if prnip:
        print("FTPServer IP address: ", addr)

    try:
        dataclient = None
        fromname = None
        do_run = True
        while do_run:
            cl, remote_addr = ftpsocket.accepted()
            if cl == None:
                if inthread:
                    notif = check_notify(notify_quit)
                    if notif == notify_quit:
                        break
                    utime.sleep_ms(2)
                continue
            cl.settimeout(timeout)
            cwd = '/'
            try:
                if inthread:
                    notif = check_notify(notify_quit)
                    if notif == notify_quit:
                        do_run = False
                        break
                if not quiet_run:
                    print("FTP connection from:", remote_addr)
                cl.sendall("220 Hello, this is the ESP32.\r\n")
                while True:
                    gc.collect()

                    data = cl.readline().decode("utf-8").rstrip("\r\n")
                    if len(data) <= 0:
                        if not quiet_run:
                            print("Client disconnected")
                        break

                    command = data.split(" ")[0].upper()
                    payload = data[len(command):].lstrip()

                    path = get_absolute_path(cwd, payload)

                    if not quiet_run:
                        print("Command: [{}], Payload: [{}]".format(
                            command, payload))

                    if command == "USER":
                        cl.sendall("230 Logged in.\r\n")
                    elif command == "SYST":
                        cl.sendall("215 UNIX Type: L8\r\n")
                    elif command == "NOOP":
                        cl.sendall("200 OK\r\n")
                    elif command == "FEAT":
                        cl.sendall("502 no-features\r\n")
                    elif command == "PWD":
                        cl.sendall('257 "{}"\r\n'.format(cwd))
                    elif command == "CWD":
                        try:
                            files = uos.listdir(path)
                            cwd = path
                            cl.sendall(msg_250_OK)
                        except:
                            cl.sendall(msg_550_fail)
                    elif command == "CDUP":
                        cwd = get_absolute_path(cwd, "..")
                        cl.sendall(msg_250_OK)
                    elif command == "TYPE":
                        # probably should switch between binary and not
                        cl.sendall('200 Transfer mode set\r\n')
                    elif command == "SIZE":
                        try:
                            size = uos.stat(path)[6]
                            cl.sendall('213 {}\r\n'.format(size))
                        except:
                            cl.sendall(msg_550_fail)
                    elif command == "QUIT":
                        cl.sendall('221 Bye.\r\n')
                        if not inthread:
                            print("Received QUIT, exiting")
                            do_run = False
                            break
                    elif command == "PASV":
                        result = '227 Entering Passive Mode ({},{},{}).\r\n'.format(
                            addr.replace('.', ','), DATA_PORT >> 8,
                            DATA_PORT % 256)
                        cl.sendall(result)
                        if not quiet_run:
                            print("Sending:", result)
                        #dataclient, data_addr = datasocket.accept()
                        #print("FTP Data connection from:", data_addr)

                    elif command == "LIST" or command == "NLST":
                        if not payload.startswith("-"):
                            place = path
                        else:
                            place = cwd
                        try:
                            dataclient, data_addr = datasocket.accept()
                            send_list_data(
                                place, dataclient, command == "LIST"
                                or payload == "-l")
                            cl.sendall(
                                "150 Here comes the directory listing.\r\n")
                            cl.sendall("226 Listed.\r\n")
                        except:
                            cl.sendall(msg_550_fail)
                        if dataclient is not None:
                            dataclient.close()
                            dataclient = None
                    elif command == "RETR":
                        try:
                            dataclient, data_addr = datasocket.accept()
                            send_file_data(path, dataclient)
                            cl.sendall("150 Opening data connection.\r\n")
                            cl.sendall("226 Transfer complete.\r\n")
                        except:
                            cl.sendall(msg_550_fail)
                        if dataclient is not None:
                            dataclient.close()
                            dataclient = None
                    elif command == "STOR":
                        try:
                            cl.sendall("150 Ok to send data.\r\n")
                            dataclient, data_addr = datasocket.accept()
                            dataclient.setblocking(False)

                            if not quiet_run:
                                print("Socket accepted")
                            save_file_data(path, dataclient)
                            cl.sendall("226 Transfer complete.\r\n")
                        except:
                            cl.sendall(msg_550_fail)
                        if dataclient is not None:
                            dataclient.close()
                            dataclient = None
                    elif command == "DELE":
                        try:
                            uos.remove(path)
                            cl.sendall(msg_250_OK)
                        except:
                            cl.sendall(msg_550_fail)
                    elif command == "RMD":
                        try:
                            uos.rmdir(path)
                            cl.sendall(msg_250_OK)
                        except:
                            cl.sendall(msg_550_fail)
                    elif command == "MKD":
                        try:
                            uos.mkdir(path)
                            cl.sendall(msg_250_OK)
                        except:
                            cl.sendall(msg_550_fail)
                    elif command == "RNFR":
                        fromname = path
                        cl.sendall("350 Rename from\r\n")
                    elif command == "RNTO":
                        if fromname is not None:
                            try:
                                uos.rename(fromname, path)
                                cl.sendall(msg_250_OK)
                            except:
                                cl.sendall(msg_550_fail)
                        else:
                            cl.sendall(msg_550_fail)
                        fromname = None
                    elif command == "STAT":
                        if payload == "":
                            cl.sendall(
                                "211-Connected to ({})\r\n"
                                "    Data address ({})\r\n"
                                "211 TYPE: Binary STRU: File MODE: Stream\r\n".
                                format(remote_addr[0], addr))
                        else:
                            cl.sendall("213-Directory listing:\r\n")
                            send_list_data(path, cl, True)
                            cl.sendall("213 Done.\r\n")
                    else:
                        cl.sendall("502 Unsupported command.\r\n")
                        if not quiet_run:
                            print("Unsupported command [{}] with payload [{}]".
                                  format(command, payload))
            except Exception as err:
                if not quiet_run:
                    print(err)
                    do_run = False

            finally:
                cl.close()
                cl = None
    finally:
        datasocket.close()
        ftpsocket.close()
        if dataclient is not None:
            dataclient.close()
示例#28
0
vfs = uos.VfsPosix(temp_dir)
print(list(i[0] for i in vfs.ilistdir(".")))

# stat, statvfs
print(type(vfs.stat(".")))
print(type(vfs.statvfs(".")))

# check types of ilistdir with str/bytes arguments
print(type(list(vfs.ilistdir("."))[0][0]))
print(type(list(vfs.ilistdir(b"."))[0][0]))

# remove
uos.remove(temp_dir + "/test2")
print(uos.listdir(temp_dir))

# remove with error
try:
    uos.remove(temp_dir + "/test2")
except OSError:
    print("remove OSError")

# rmdir
uos.rmdir(temp_dir)
print(temp_dir in uos.listdir())

# rmdir with error
try:
    uos.rmdir(temp_dir)
except OSError:
    print("rmdir OSError")
示例#29
0
    print("OSError")

# rename across a filesystem
try:
    uos.rename("/test_mnt/a", "/test_mnt2/b")
except OSError:
    print("OSError")

# delegating to mounted filesystem
uos.chdir("test_mnt")
print(uos.listdir())
print(uos.getcwd())
uos.mkdir("test_dir")
uos.remove("test_file")
uos.rename("test_file", "test_file2")
uos.rmdir("test_dir")
print(uos.stat("test_file"))
print(uos.statvfs("/test_mnt"))
open("test_file")
open("test_file", "wb")

# umount
uos.umount("/test_mnt")
uos.umount("/test_mnt2")

# umount a non-existent mount point
try:
    uos.umount("/test_mnt")
except OSError:
    print("OSError")
示例#30
0
 def _execute_update(self):
     for file in uos.listdir("next"):
         uos.rename("next/"+file, file)
     uos.rmdir("next")
     machine.reset()
示例#31
0
for exist in ("", "/", "dir", "/dir", "dir/subdir"):
    try:
        uos.mkdir(exist)
    except OSError as er:
        print("mkdir OSError", er.args[0] == 17)  # EEXIST

uos.chdir("/")
print(uos.stat("test5.txt")[:-3])

uos.VfsFat.mkfs(bdev2)
uos.mount(bdev2, "/sys")
print(uos.listdir())
print(uos.listdir("sys"))
print(uos.listdir("/sys"))

uos.rmdir("dir2")
uos.remove("test5.txt")
print(uos.listdir())

uos.umount("/")
print(uos.getcwd())
print(uos.listdir())
print(uos.listdir("sys"))

# test importing a file from a mounted FS
import sys

sys.path.clear()
sys.path.append("/sys")
with open("sys/test_module.py", "w") as f:
    f.write('print("test_module!")')
示例#32
0
def ftpserver():

    DATA_PORT = 13333

    ftpsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    datasocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    ftpsocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    datasocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

    ftpsocket.bind(socket.getaddrinfo("0.0.0.0", 21)[0][4])
    datasocket.bind(socket.getaddrinfo("0.0.0.0", DATA_PORT)[0][4])

    ftpsocket.listen(1)
    ftpsocket.settimeout(None)
    datasocket.listen(1)
    datasocket.settimeout(None)

    msg_250_OK = '250 OK\r\n'
    msg_550_fail = '550 Failed\r\n'
    # check for an active interface, STA first
    wlan = network.WLAN(network.STA_IF)
    if wlan.active():
        addr = wlan.ifconfig()[0]
    else:
        wlan = network.WLAN(network.AP_IF)
        if wlan.active():
            addr = wlan.ifconfig()[0]
        else:
            print("No active connection")
            return

    print("FTP Server started on ", addr)
    try:
        dataclient = None
        fromname = None
        do_run = True
        while do_run:
            cl, remote_addr = ftpsocket.accept()
            cl.settimeout(300)
            cwd = '/'
            try:
                # print("FTP connection from:", remote_addr)
                cl.sendall("220 Hello, this is the ESP8266/ESP32.\r\n")
                while True:
                    gc.collect()
                    data = cl.readline().decode("utf-8").rstrip("\r\n")
                    if len(data) <= 0:
                        print("Client disappeared")
                        do_run = False
                        break

                    command = data.split(" ")[0].upper()
                    payload = data[len(command):].lstrip()

                    path = get_absolute_path(cwd, payload)

                    print("Command={}, Payload={}".format(command, payload))

                    if command == "USER":
                        cl.sendall("230 Logged in.\r\n")
                    elif command == "SYST":
                        cl.sendall("215 UNIX Type: L8\r\n")
                    elif command == "NOOP":
                        cl.sendall("200 OK\r\n")
                    elif command == "FEAT":
                        cl.sendall("211 no-features\r\n")
                    elif command == "PWD" or command == "XPWD":
                        cl.sendall('257 "{}"\r\n'.format(cwd))
                    elif command == "CWD" or command == "XCWD":
                        try:
                            files = uos.listdir(path)
                            cwd = path
                            cl.sendall(msg_250_OK)
                        except:
                            cl.sendall(msg_550_fail)
                    elif command == "CDUP":
                        cwd = get_absolute_path(cwd, "..")
                        cl.sendall(msg_250_OK)
                    elif command == "TYPE":
                        # probably should switch between binary and not
                        cl.sendall('200 Transfer mode set\r\n')
                    elif command == "SIZE":
                        try:
                            size = uos.stat(path)[6]
                            cl.sendall('213 {}\r\n'.format(size))
                        except:
                            cl.sendall(msg_550_fail)
                    elif command == "QUIT":
                        cl.sendall('221 Bye.\r\n')
                        do_run = False
                        break
                    elif command == "PASV":
                        cl.sendall(
                            '227 Entering Passive Mode ({},{},{}).\r\n'.format(
                                addr.replace('.', ','), DATA_PORT >> 8,
                                DATA_PORT % 256))
                        dataclient, data_addr = datasocket.accept()
                        print("FTP Data connection from:", data_addr)
                        DATA_PORT = 13333
                        active = False
                    elif command == "PORT":
                        items = payload.split(",")
                        if len(items) >= 6:
                            data_addr = '.'.join(items[:4])
                            if data_addr == "127.0.1.1":  # replace by command session addr
                                data_addr = remote_addr
                            DATA_PORT = int(items[4]) * 256 + int(items[5])
                            dataclient = socket.socket(socket.AF_INET,
                                                       socket.SOCK_STREAM)
                            dataclient.settimeout(10)
                            dataclient.connect((data_addr, DATA_PORT))
                            print("FTP Data connection with:", data_addr)
                            cl.sendall('200 OK\r\n')
                            active = True
                        else:
                            cl.sendall('504 Fail\r\n')
                    elif command == "LIST" or command == "NLST":
                        if not payload.startswith("-"):
                            place = path
                        else:
                            place = cwd
                        try:
                            cl.sendall(
                                "150 Here comes the directory listing.\r\n")
                            send_list_data(
                                place, dataclient, command == "LIST"
                                or payload == "-l")
                            cl.sendall("226 Listed.\r\n")
                        except:
                            cl.sendall(msg_550_fail)
                        if dataclient is not None:
                            dataclient.close()
                            dataclient = None
                    elif command == "RETR":
                        try:
                            cl.sendall("150 Opening data connection.\r\n")
                            send_file_data(path, dataclient)
                            cl.sendall("226 Transfer complete.\r\n")
                        except:
                            cl.sendall(msg_550_fail)
                        if dataclient is not None:
                            dataclient.close()
                            dataclient = None
                    elif command == "STOR":
                        try:
                            cl.sendall("150 Ok to send data.\r\n")
                            save_file_data(path, dataclient)
                            cl.sendall("226 Transfer complete.\r\n")
                        except:
                            cl.sendall(msg_550_fail)
                        if dataclient is not None:
                            dataclient.close()
                            dataclient = None
                    elif command == "DELE":
                        try:
                            uos.remove(path)
                            cl.sendall(msg_250_OK)
                        except:
                            cl.sendall(msg_550_fail)
                    elif command == "RMD" or command == "XRMD":
                        try:
                            uos.rmdir(path)
                            cl.sendall(msg_250_OK)
                        except:
                            cl.sendall(msg_550_fail)
                    elif command == "MKD" or command == "XMKD":
                        try:
                            uos.mkdir(path)
                            cl.sendall(msg_250_OK)
                        except:
                            cl.sendall(msg_550_fail)
                    elif command == "RNFR":
                        fromname = path
                        cl.sendall("350 Rename from\r\n")
                    elif command == "RNTO":
                        if fromname is not None:
                            try:
                                uos.rename(fromname, path)
                                cl.sendall(msg_250_OK)
                            except:
                                cl.sendall(msg_550_fail)
                        else:
                            cl.sendall(msg_550_fail)
                        fromname = None
                    elif command == "STAT":
                        if payload == "":
                            cl.sendall(
                                "211-Connected to ({})\r\n"
                                "    Data address ({})\r\n"
                                "211 TYPE: Binary STRU: File MODE: Stream\r\n".
                                format(remote_addr[0], addr))
                        else:
                            cl.sendall("213-Directory listing:\r\n")
                            send_list_data(path, cl, True)
                            cl.sendall("213 Done.\r\n")
                    else:
                        cl.sendall("502 Unsupported command.\r\n")
                        print("Unsupported command {} with payload {}".format(
                            command, payload))
            except Exception as err:
                print(err)

            finally:
                cl.close()
                cl = None
    finally:
        datasocket.close()
        ftpsocket.close()
        if dataclient is not None:
            dataclient.close()