mirror of
https://github.com/gryf/mc_adbfs.git
synced 2026-03-27 13:53:35 +01:00
Compare commits
6 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| ae08a7329a | |||
| ebef125f38 | |||
| de5793c672 | |||
| d1e8f42429 | |||
| 89c783e9cd | |||
| 7cb2a09282 |
@@ -17,7 +17,7 @@ Make sure, that issuing from command line::
|
||||
|
||||
$ adb shell busybox ls
|
||||
|
||||
should display files from root directory on the device.
|
||||
it should display files from root directory on the device.
|
||||
|
||||
Features
|
||||
========
|
||||
@@ -55,6 +55,8 @@ Limitations
|
||||
files are on the device and so on
|
||||
* Some filenames might be still inaccessible for operating
|
||||
* All files operations which needs root privileges will fail (for now)
|
||||
* The implementation is experimental and it's by now working with mine device;
|
||||
while it might not work with yours
|
||||
|
||||
License
|
||||
=======
|
||||
|
||||
336
adbfs
336
adbfs
@@ -2,36 +2,136 @@
|
||||
"""
|
||||
adbfs Virtual filesystem for Midnight Commander
|
||||
|
||||
* Copyright (c) 2015, Roman Dobosz,
|
||||
* Copyright (c) 2016, Roman Dobosz,
|
||||
* Published under 3-clause BSD-style license (see LICENSE file)
|
||||
|
||||
Version: 0.7
|
||||
"""
|
||||
|
||||
import ConfigParser
|
||||
import argparse
|
||||
from datetime import datetime
|
||||
import errno
|
||||
import json
|
||||
import os
|
||||
import pipes
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
__version__ = 0.8
|
||||
|
||||
DEBUG = os.getenv("ADBFS_DEBUG", False)
|
||||
SKIP_SYSTEM_DIR = os.getenv("ADBFS_SKIP_SYSTEM_DIR", True)
|
||||
XDG_CONFIG_HOME = os.getenv("XDG_CONFIG_HOME", os.path.expanduser("~/.config"))
|
||||
|
||||
|
||||
class NoBoxFoundException(OSError):
|
||||
"""
|
||||
Exception raised in case of not found either toolbox or busybox on remote
|
||||
filesystem accessed via adb
|
||||
"""
|
||||
pass
|
||||
|
||||
class Conf(object):
|
||||
"""Simple config parser"""
|
||||
boxes = {'busybox': {'ls': 'busybox ls -anel',
|
||||
'rls': 'busybox ls -Ranel {}',
|
||||
'file_re': r'^(?P<perms>[-bcdlps][-rwxsStT]{9})\s+'
|
||||
r'(?P<links>\d+)\s'
|
||||
r'(?P<uid>\d+)\s+'
|
||||
r'(?P<gid>\d+)\s+'
|
||||
r'(?P<size>\d+)\s[A-Z,a-z]{3}\s'
|
||||
r'(?P<date_time>[A-Z,a-z]{3}\s+'
|
||||
r'\d+\s\d{2}:\d{2}:\d{2}\s+\d{4})\s'
|
||||
r'(?P<name>.*)'},
|
||||
'toolbox': {'ls': 'toolbox ls -anl',
|
||||
'rls': 'toolbox ls -Ranl {}',
|
||||
'file_re': r'^(?P<perms>[-bcdlps][-rwxsStT]{9})\s+'
|
||||
r'(?P<uid>\d+)\s+'
|
||||
r'(?P<gid>\d+)\s+'
|
||||
r'(?P<size>\d+)?\s'
|
||||
r'(?P<date>\d{4}-\d{2}-\d{2}\s'
|
||||
r'\d{2}:\d{2})\s'
|
||||
r'(?P<name>.*)'}
|
||||
}
|
||||
|
||||
def __init__(self):
|
||||
self.box = None
|
||||
self.debug = False
|
||||
self.skip_dirs = True
|
||||
self.dirs_to_skip = ["acct", "charger", "d", "dev", "proc", "sys"]
|
||||
|
||||
self.get_the_box()
|
||||
self.read()
|
||||
|
||||
def get_the_box(self):
|
||||
"""Detect if we dealing with busybox or toolbox"""
|
||||
try:
|
||||
with open(os.devnull, "w") as fnull:
|
||||
result = subprocess.check_output('adb shell which '
|
||||
'busybox'.split(),
|
||||
stderr=fnull)
|
||||
|
||||
if 'busybox' in result:
|
||||
self.box = Conf.boxes['busybox']
|
||||
Adb.file_re = re.compile(self.box['file_re'])
|
||||
return
|
||||
except subprocess.CalledProcessError:
|
||||
pass
|
||||
|
||||
try:
|
||||
with open(os.devnull, "w") as fnull:
|
||||
result = subprocess.check_output('adb shell which '
|
||||
'toolbox'.split(),
|
||||
stderr=fnull)
|
||||
|
||||
if 'toolbox' in result:
|
||||
self.box = Conf.boxes['toolbox']
|
||||
Adb.file_re = re.compile(self.box['file_re'])
|
||||
return
|
||||
except subprocess.CalledProcessError:
|
||||
pass
|
||||
|
||||
raise NoBoxFoundException(errno.ENOENT,
|
||||
"There is no toolbox or busybox available")
|
||||
|
||||
def read(self):
|
||||
"""
|
||||
Read config file and change the options according to values from that
|
||||
file.
|
||||
"""
|
||||
if not os.path.exists(XDG_CONFIG_HOME):
|
||||
return
|
||||
|
||||
conf_fname = os.path.join(XDG_CONFIG_HOME, 'mc', 'adbfs.ini')
|
||||
if not os.path.exists(conf_fname):
|
||||
return
|
||||
|
||||
cfg = ConfigParser.SafeConfigParser()
|
||||
cfg_map = {'debug': (cfg.getboolean, 'debug'),
|
||||
'skip_dirs': (cfg.getboolean, 'skip_dirs'),
|
||||
'dirs_to_skip': (cfg.get, 'dirs_to_skip')}
|
||||
cfg.read(conf_fname)
|
||||
|
||||
for key, (function, attr) in cfg_map.items():
|
||||
try:
|
||||
setattr(self, attr, function('adbfs', key))
|
||||
except (ConfigParser.NoSectionError, ConfigParser.NoOptionError):
|
||||
pass
|
||||
|
||||
if isinstance(self.dirs_to_skip, str):
|
||||
self.dirs_to_skip = json.loads(self.dirs_to_skip, encoding="ascii")
|
||||
|
||||
|
||||
class File(object):
|
||||
"""Item in filesystem representation"""
|
||||
def __init__(self, perms=None, links=1, uid=0, gid=0, size=0,
|
||||
date_time=None, name=None):
|
||||
def __init__(self, perms=None, links=1, uid=0, gid=0, size=None,
|
||||
date_time=None, date=None, name=None):
|
||||
"""initialize file"""
|
||||
self.perms = perms
|
||||
self.links = links
|
||||
self.uid = uid
|
||||
self.gid = gid
|
||||
self.size = size
|
||||
self.size = size if size else 0
|
||||
self.date_time = date_time # as string
|
||||
self.name = name
|
||||
self.date = date # as string
|
||||
|
||||
self.dirname = ""
|
||||
self.type = None
|
||||
@@ -47,6 +147,10 @@ class File(object):
|
||||
return
|
||||
|
||||
self.name = name
|
||||
|
||||
if not self.size:
|
||||
self.size = 0
|
||||
|
||||
if target.startswith("/"):
|
||||
self.link_target = target
|
||||
else:
|
||||
@@ -68,13 +172,18 @@ class File(object):
|
||||
"Nov": 11,
|
||||
"Dec": 12}
|
||||
self.dirname = dirname
|
||||
if self.date_time:
|
||||
date = self.date_time.split()
|
||||
date = "%s-%02d-%s %s" % (date[1],
|
||||
month_num[date[0]],
|
||||
date[3],
|
||||
date[2])
|
||||
date = datetime.strptime(date, "%d-%m-%Y %H:%M:%S")
|
||||
elif self.date:
|
||||
date = datetime.strptime(self.date, "%Y-%m-%d %H:%M")
|
||||
|
||||
self.date_time = date.strftime("%m/%d/%Y %H:%M:01")
|
||||
|
||||
self.type = self.perms[0] if self.perms else None
|
||||
|
||||
if self.type == "l" and " -> " in self.name:
|
||||
@@ -82,12 +191,9 @@ class File(object):
|
||||
|
||||
self.filepath = os.path.join(self.dirname, self.name)
|
||||
|
||||
def mk_link_relative(self, target_type):
|
||||
def mk_link_relative(self):
|
||||
"""Convert links to relative"""
|
||||
rel_path = self.dirname
|
||||
# if target_type == "d":
|
||||
# rel_path = self.filepath
|
||||
self.link_target = os.path.relpath(self.link_target, rel_path)
|
||||
self.link_target = os.path.relpath(self.link_target, self.dirname)
|
||||
|
||||
def __repr__(self):
|
||||
"""represent the file/entire node"""
|
||||
@@ -122,24 +228,34 @@ class File(object):
|
||||
class Adb(object):
|
||||
"""Class for interact with android rooted device through adb"""
|
||||
dirs_to_skip = ["acct", "charger", "d", "dev", "proc", "sys"]
|
||||
file_re = re.compile(r'^(?P<perms>[-bcdlps][-rwxsStT]{9})\s+'
|
||||
r'(?P<links>\d+)\s'
|
||||
r'(?P<uid>\d+)\s+'
|
||||
r'(?P<gid>\d+)\s+'
|
||||
r'(?P<size>\d+)\s[A-Z,a-z]{3}\s'
|
||||
r'(?P<date_time>[A-Z,a-z]{3}\s+'
|
||||
r'\d+\s\d{2}:\d{2}:\d{2}\s+\d{4})\s'
|
||||
r'(?P<name>.*)')
|
||||
|
||||
file_re = None
|
||||
current_re = re.compile(r"^(\./)?(?P<dir>.+):$")
|
||||
as_root = os.getenv("ADBFS_AS_ROOT", False)
|
||||
verbose = os.getenv("ADBFS_VERBOSE", False)
|
||||
|
||||
def __init__(self):
|
||||
"""Prepare archive content for operations"""
|
||||
super(Adb, self).__init__()
|
||||
self.conf = Conf()
|
||||
self.error = ''
|
||||
self._entries = []
|
||||
self._links = {}
|
||||
self._got_root = False
|
||||
|
||||
self.__su_check()
|
||||
|
||||
def __su_check(self):
|
||||
"""Check if we are able to get elevated privileges"""
|
||||
try:
|
||||
with open(os.devnull, "w") as fnull:
|
||||
result = subprocess.check_output('adb shell su -c '
|
||||
'whoami'.split(),
|
||||
stderr=fnull)
|
||||
|
||||
except subprocess.CalledProcessError:
|
||||
return
|
||||
|
||||
if 'root' in result:
|
||||
self._got_root = True
|
||||
return
|
||||
|
||||
def _find_target(self, needle):
|
||||
"""Find link target"""
|
||||
@@ -153,6 +269,7 @@ class Adb(object):
|
||||
for entry in self._entries:
|
||||
if entry.filepath == needle:
|
||||
return entry
|
||||
|
||||
return None
|
||||
|
||||
def _normalize_links(self):
|
||||
@@ -170,7 +287,7 @@ class Adb(object):
|
||||
target_entry = self._find_target(entry.link_target)
|
||||
if target_entry:
|
||||
entry.link_target = target_entry.filepath
|
||||
entry.mk_link_relative(target_entry.type)
|
||||
entry.mk_link_relative()
|
||||
else:
|
||||
elems_to_remove.append(self._entries.index(entry))
|
||||
|
||||
@@ -179,16 +296,18 @@ class Adb(object):
|
||||
|
||||
def _retrieve_file_list(self, root=None):
|
||||
"""Retrieve file list using adb"""
|
||||
|
||||
# if root:
|
||||
# print "retrieve for %s" % root.filepath
|
||||
command = ["adb", "shell", "su", "-c"]
|
||||
skip_dirs = self.conf.skip_dirs
|
||||
|
||||
if not root:
|
||||
command.append("'busybox ls -anel'")
|
||||
command.append(self.conf.box['ls'])
|
||||
else:
|
||||
command.append("'busybox ls -Ranel {}'".format(root.filepath))
|
||||
command.append(self.conf.box['rls'].format(root.filepath))
|
||||
|
||||
try:
|
||||
if self.conf.debug:
|
||||
print "executing", " ".join(command)
|
||||
|
||||
lines = subprocess.check_output(command)
|
||||
except subprocess.CalledProcessError:
|
||||
sys.stderr.write("Cannot read directory. Is device connected?\n")
|
||||
@@ -212,11 +331,11 @@ class Adb(object):
|
||||
if entry.name in (".", ".."):
|
||||
continue
|
||||
|
||||
if SKIP_SYSTEM_DIR and entry.name in Adb.dirs_to_skip:
|
||||
continue
|
||||
|
||||
entry.update(current_dir)
|
||||
|
||||
if skip_dirs and entry.filepath in self.conf.dirs_to_skip:
|
||||
continue
|
||||
|
||||
self._entries.append(entry)
|
||||
if root is None and entry.type == "d":
|
||||
self._retrieve_file_list(entry)
|
||||
@@ -232,29 +351,59 @@ class Adb(object):
|
||||
|
||||
def list(self):
|
||||
"""Output list contents directory"""
|
||||
if self.error:
|
||||
sys.stderr.write(self.error)
|
||||
return 1
|
||||
|
||||
self._retrieve_file_list()
|
||||
# self._retrieve_file_list_from_pickle()
|
||||
# self._save_file_list_to_pickle()
|
||||
self._normalize_links()
|
||||
# with open(os.path.join(os.path.dirname(os.path.realpath(__file__)),
|
||||
# # "list.pcl"), "w") as fob:
|
||||
# "list.pcl")) as fob:
|
||||
# import cPickle
|
||||
# # cPickle.dump(self._entries, fob)
|
||||
# self._entries = cPickle.load(fob)
|
||||
sys.stdout.write("".join([str(entry) for entry in self._entries]))
|
||||
return 0
|
||||
|
||||
def copyout(self, src, dst):
|
||||
"""Copy file form the device using adb."""
|
||||
if self.error:
|
||||
sys.stderr.write(self.error)
|
||||
return 1
|
||||
|
||||
cmd = ["adb", "pull", src, dst]
|
||||
if self.conf.debug:
|
||||
sys.stderr.write(" ".join(cmd) + "\n")
|
||||
|
||||
with open(os.devnull, "w") as fnull:
|
||||
return subprocess.call(["adb", "pull", pipes.quote(src),
|
||||
pipes.quote(dst)],
|
||||
stdout=fnull, stderr=fnull)
|
||||
try:
|
||||
err = subprocess.call(cmd, stdout=fnull, stderr=fnull)
|
||||
except subprocess.CalledProcessError:
|
||||
sys.stderr.write('Error executing adb shell')
|
||||
return 1
|
||||
|
||||
return err
|
||||
|
||||
def copyin(self, src, dst):
|
||||
"""Copy file to the device through adb."""
|
||||
if self.error:
|
||||
sys.stderr.write(self.error)
|
||||
return 1
|
||||
if not dst.startswith("/"):
|
||||
dst = "/" + dst
|
||||
|
||||
# cmd = ["adb", "push", pipes.quote(src), pipes.quote(dst)]
|
||||
cmd = ["adb", "push", src, dst]
|
||||
if self.conf.debug:
|
||||
sys.stderr.write(" ".join(cmd) + "\n")
|
||||
|
||||
with open(os.devnull, "w") as fnull:
|
||||
err = subprocess.call(["adb", "push", pipes.quote(src),
|
||||
pipes.quote(dst)],
|
||||
stdout=fnull, stderr=fnull)
|
||||
try:
|
||||
err = subprocess.call(cmd, stdout=fnull, stderr=fnull)
|
||||
except subprocess.CalledProcessError:
|
||||
sys.stderr.write('Error executing adb shell')
|
||||
return 1
|
||||
|
||||
if err != 0:
|
||||
sys.stderr.write("Cannot push the file, "
|
||||
@@ -264,8 +413,16 @@ class Adb(object):
|
||||
|
||||
def rm(self, dst):
|
||||
"""Remove file from device."""
|
||||
cmd = ["adb", "shell", "rm", pipes.quote(dst)]
|
||||
if self.error:
|
||||
sys.stderr.write(self.error)
|
||||
return 1
|
||||
|
||||
cmd = ["adb", "shell", "rm", dst]
|
||||
try:
|
||||
err = subprocess.check_output(cmd)
|
||||
except subprocess.CalledProcessError:
|
||||
sys.stderr.write('Error executing adb shell')
|
||||
return 1
|
||||
|
||||
if err != "":
|
||||
sys.stderr.write(err)
|
||||
@@ -274,8 +431,16 @@ class Adb(object):
|
||||
|
||||
def rmdir(self, dst):
|
||||
"""Remove directory from device."""
|
||||
cmd = ["adb", "shell", "rm", "-r", pipes.quote(dst)]
|
||||
if self.error:
|
||||
sys.stderr.write(self.error)
|
||||
return 1
|
||||
|
||||
cmd = ["adb", "shell", "rm", "-r", dst]
|
||||
try:
|
||||
err = subprocess.check_output(cmd)
|
||||
except subprocess.CalledProcessError:
|
||||
sys.stderr.write('Error executing adb shell')
|
||||
return 1
|
||||
|
||||
if err != "":
|
||||
sys.stderr.write(err)
|
||||
@@ -284,8 +449,19 @@ class Adb(object):
|
||||
|
||||
def mkdir(self, dst):
|
||||
"""Make directory on the device through adb."""
|
||||
cmd = ["adb", "shell", "mkdir", pipes.quote(dst)]
|
||||
if self.error:
|
||||
sys.stderr.write(self.error)
|
||||
return 1
|
||||
|
||||
if not dst.startswith("/"):
|
||||
dst = "/" + dst
|
||||
|
||||
cmd = ["adb", "shell", "mkdir", dst]
|
||||
try:
|
||||
err = subprocess.check_output(cmd)
|
||||
except subprocess.CalledProcessError:
|
||||
sys.stderr.write('Error executing adb shell')
|
||||
return 1
|
||||
|
||||
if err != "":
|
||||
sys.stderr.write(err)
|
||||
@@ -301,39 +477,55 @@ CALL_MAP = {'list': lambda a: Adb().list(),
|
||||
'rm': lambda a: Adb().rm(a.dst),
|
||||
'run': lambda a: Adb().run(a.dst)}
|
||||
|
||||
|
||||
def main():
|
||||
"""parse commandline"""
|
||||
try:
|
||||
if DEBUG:
|
||||
sys.stderr.write("commandline: %s\n" % " ".join(sys.argv))
|
||||
if sys.argv[1] not in ('list', 'copyin', 'copyout', 'rm', "rmdir",
|
||||
'mkdir', "run"):
|
||||
sys.exit(2)
|
||||
except IndexError:
|
||||
sys.exit(2)
|
||||
parser = argparse.ArgumentParser()
|
||||
subparsers = parser.add_subparsers(help='supported commands')
|
||||
parser_list = subparsers.add_parser('list')
|
||||
parser_copyin = subparsers.add_parser('copyin')
|
||||
parser_copyout = subparsers.add_parser('copyout')
|
||||
parser_rm = subparsers.add_parser('rm')
|
||||
parser_mkdir = subparsers.add_parser('mkdir')
|
||||
parser_rmdir = subparsers.add_parser('rmdir')
|
||||
parser_run = subparsers.add_parser('run')
|
||||
|
||||
class Arg(object):
|
||||
"""Mimic argparse/optparse object"""
|
||||
dst = None
|
||||
src = None
|
||||
arch = None
|
||||
parser_list.add_argument('arch')
|
||||
parser_list.set_defaults(func=CALL_MAP['list'])
|
||||
|
||||
arg = Arg()
|
||||
parser_copyin.add_argument('arch')
|
||||
parser_copyin.add_argument('dst')
|
||||
parser_copyin.add_argument('src')
|
||||
parser_copyin.set_defaults(func=CALL_MAP['copyin'])
|
||||
|
||||
try:
|
||||
arg.arch = sys.argv[2]
|
||||
if sys.argv[1] == 'copyin':
|
||||
arg.src = sys.argv[4]
|
||||
arg.dst = sys.argv[3]
|
||||
if sys.argv[1] == 'copyout':
|
||||
arg.src = sys.argv[3]
|
||||
arg.dst = sys.argv[4]
|
||||
elif sys.argv[1] in ('rm', 'rmdir', 'run', 'mkdir'):
|
||||
arg.dst = sys.argv[3]
|
||||
except IndexError:
|
||||
sys.exit(2)
|
||||
parser_copyout.add_argument('arch')
|
||||
parser_copyout.add_argument('src')
|
||||
parser_copyout.add_argument('dst')
|
||||
parser_copyout.set_defaults(func=CALL_MAP['copyout'])
|
||||
|
||||
parser_rm.add_argument('arch')
|
||||
parser_rm.add_argument('dst')
|
||||
parser_rm.set_defaults(func=CALL_MAP['rm'])
|
||||
|
||||
parser_mkdir.add_argument('arch')
|
||||
parser_mkdir.add_argument('dst')
|
||||
parser_mkdir.set_defaults(func=CALL_MAP['mkdir'])
|
||||
|
||||
parser_rmdir.add_argument('arch')
|
||||
parser_rmdir.add_argument('dst')
|
||||
parser_rmdir.set_defaults(func=CALL_MAP['rmdir'])
|
||||
|
||||
parser_run.add_argument('arch')
|
||||
parser_run.add_argument('dst')
|
||||
parser_run.set_defaults(func=CALL_MAP['run'])
|
||||
|
||||
parser.add_argument('--version', action='version',
|
||||
version='%(prog)s ' + str(__version__))
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
return args.func(args)
|
||||
|
||||
return CALL_MAP[sys.argv[1]](arg)
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
|
||||
Reference in New Issue
Block a user