Example #1
0
def  copyfile(file,remotedir):
    print 'copyfile=',file,remotedir
    adb = ADB('/Users/aadebuger/Documents/android-sdk-mac_x86/platform-tools/adb') 
    print adb.pyadb_version()
    aa =adb.push_local_file(file, remotedir)
#    aa=adb.shell_command("""push "%s" storage/sdcard0/coursera"""%(file))
    print 'copyfile lines=',aa   
Example #2
0
def main():
    # creates the ADB object
    adb = ADB()
    # IMPORTANT: You should supply the absolute path to ADB binary 
    if adb.set_adb_path('/home/chema/.android-sdks/platform-tools/adb') is True:
        print "Version: %s" % adb.get_version()
    else:
        print "Check ADB binary path"
Example #3
0
def main():
    # creates the ADB object
    adb = ADB()
    # IMPORTANT: You should supply the absolute path to ADB binary
    if adb.set_adb_path(
            '/home/chema/.android-sdks/platform-tools/adb') is True:
        print("Version: %s" % adb.get_version())
    else:
        print("Check ADB binary path")
 def render_GET(self, request):
     adb = ADB('/usr/bin/adb')
     retour=''
     items=split(request.path,'/')[1:]
     if items[0]=='c':
         retour=adb.connect_remote(items[1])
     elif items[0]=='d':
         retour=adb.disconnect_remote(items[1])
     print "adb : %s" % retour 
     return "OK\n"
Example #5
0
    def get_adb_obj(self):
        adb_object = None

        adb_path = self.get_path()

        if os.name == "nt":
            adb_object = ADB(adb_path + "\\adb.exe")
        elif os.name == "posix":
            adb_object = ADB(str(adb_path) + "/adb")

        return adb_object
Example #6
0
def main():
    # creates the ADB object
    adb = ADB()
    # IMPORTANT: You should supply the absolute path to ADB binary 
    if adb.set_adb_path('/usr/bin/adb') is True:
        print ("Version: %s" % adb.get_version())
    else:
        print ("Check ADB binary path")

    apps = adb.shell_command("pm list packages")
    for app in apps:
        path = adb.shell_command("pm path {}".format(app.split(':')[1]))
        print ("{}: {}".format(app,path))
Example #7
0
def init_adb():
    device_id = os.getenv("ANDROID_SERIAL")
    global adb
    adb = ADB()
    adb.enable_debug()
    adb.set_adb_path()
    adb.set_target_device(device_id)
def get_user_plane_state():
    '''
    checks aether user plane connectivity with ping to 8.8.8.8
    '''
    adb = ADB()
    if adb.set_adb_path(CONF.adb.path) is False:
        err = "[ERROR]: " + CONF.adb.path + " not found"
        return State.error, err

    success, result = _run_adb_shell(adb, ADB_GET_COMMANDS['ping_result'])
    if not success or result is None:
        return State.error, result

    state = State.connected if result == "0" else State.disconnected
    return state, None
Example #9
0
class SmsReader():
    def __init__(self, adb_path, local_sms_db = "sms/", remote_sms_db = '/data/data/com.android.providers.telephony/databases/mmssms.db'):
        #Thread.__init__:
        self.ADB_PATH = adb_path
        # avoid using ~/ at the beginning of path
        self.phone = ADB(self.ADB_PATH)
        self.LOCAL_SMS_DB = local_sms_db + 'mmssms.db'        
        self.REMOTE_SMS_DB = remote_sms_db
        self.phone.get_remote_file(
                self.REMOTE_SMS_DB, 
                self.LOCAL_SMS_DB
                )
        self.engine = create_engine('sqlite:///%s' % self.LOCAL_SMS_DB, echo=False)
        self.metadata = MetaData(self.engine)
        self.sms_table = Table('sms', self.metadata, autoload=True)
        mapper(Sms,self.sms_table )
        Session = sessionmaker(bind=self.engine)
        self.session = Session()
        
        self.sms = self.session.query(Sms)
        self.messages = [msg.body for msg in self.sms]
        self.num_sms = self.sms.count()
        self.last_sms_num = self.num_sms
        self.new_sms  = []
        self.session.close()

    #copy sms database
    def update(self):
        self.phone.get_remote_file(
                self.REMOTE_SMS_DB, 
                self.LOCAL_SMS_DB 
                )
        self.sms = self.session.query(Sms)
        self.messages = [msg.body for msg in self.sms]
        self.sms_num = self.sms.count()
        if self.sms_num > self.last_sms_num:
            difference = self.sms_num - self.last_sms_num
            temp_sms = self.sms.slice(self.last_sms_num, self.sms_num).all()
            self.new_sms = [x.body for x in temp_sms]
            self.last_sms_num = self.sms_num

        self.session.close()

    def quit(self):
        self.session.close() 
 def __init__(self, name):
     vbox = VBOX_MGR.vbox
     self.session = VBOX_MGR.getSessionObject(vbox)
     self.vm = vbox.findMachine(name)
     self.name = name
     self.adb = ADB('adb')
     self.ip = ''
     self.cmd_ip = ''
     self.network_key = None
Example #11
0
class SmsReader():
    def __init__(self):

        self.ADB_PATH = '/Users/cmart/code/android/android-sdk-macosx/platform-tools/adb'
        # avoid using ~/ at the beginning of path
        self.phone = ADB(self.ADB_PATH)
        self.DATABASE_PATH = 'db/mmssms.db'
        self.phone.get_remote_file(
                '/data/data/com.android.providers.telephony/databases/mmssms.db', 
                self.DATABASE_PATH
                )

        self.engine = create_engine('sqlite:///%s' % self.DATABASE_PATH, echo=False)
        self.metadata = MetaData(self.engine)
        self.sms_table = Table('sms', self.metadata, autoload=True)
        mapper(Sms,self.sms_table )
        Session = sessionmaker(bind=self.engine)
        self.session = Session()
        
        self.sms = self.session.query(Sms)
        self.messages = [msg.body for msg in self.sms]
        self.num_sms = self.sms.count()
        self.last_sms_num = self.num_sms
        self.new_sms  = []
        self.session.close()

    #copy sms database
    def update(self):
        self.phone.get_remote_file(
                '/data/data/com.android.providers.telephony/databases/mmssms.db', 
                self.DATABASE_PATH  
                )
        self.sms = self.session.query(Sms)
        self.messages = [msg.body for msg in self.sms]
        self.sms_num = self.sms.count()
        if self.sms_num > self.last_sms_num:
            difference = self.sms_num - self.last_sms_num
            temp_sms = self.sms.slice(self.last_sms_num, self.sms_num).all()
            self.new_sms = [x.body for x in temp_sms]
            self.last_sms_num = self.sms_num

        self.session.close() 
Example #12
0
def main():
    # creates the ADB object
    adb = ADB()
    # set ADB path, using a couple of popular addresses.
    try:
        adb.set_adb_path('~/android-sdk-linux/platform-tools/adb')
    except ADB.BadCall:
        adb.set_adb_path(r'C:\Android\android-sdk\platform-tools\adb.exe')

    apps, error = adb.shell_command("pm list packages")
    for app in apps:
        path, error = adb.shell_command("pm path {}".format(app.split(':')[1]))
        print(("{}: {}".format(app, path)))
def get_control_plane_state():
    '''
    check aether control plane works by toggling airplane mode
    '''
    adb = ADB()
    if adb.set_adb_path(CONF.adb.path) is False:
        err = "[ERROR]: " + CONF.adb.path + " not found"
        return State.error, err

    # get the current airplane mode
    success, result = _run_adb_shell(adb, ADB_GET_COMMANDS['apn_mode'])
    if not success or result is None:
        return State.error, result
    apn_mode_on = True if result == "1" else False

    # toggle the airplane mode
    for command in ADB_APN_COMMANDS.values():
        success, result = _run_adb_shell(adb, command)
        if not success:
            return State.error, result
    if not apn_mode_on:
        success, result = _run_adb_shell(adb, ADB_APN_COMMANDS['toggle'])
        if not success:
            return State.error, result

    # additional wait for UE to fully attach
    time.sleep(3)

    # get connection state
    state = State.connecting.value
    while state == State.connecting.value:
        success, result = _run_adb_shell(adb, ADB_GET_COMMANDS['lte_state'])
        if not success or result is None:
            return State.error, result
        state = result.split("=")[1]

    if not State.has_value(state):
        return State.error, None
    return State(state), None
Example #14
0
def main():
    # creates the ADB object using the system adb
    adb = ADB()
    print("Version: %s" % adb.get_version())

    # Or create ADB object with specific version of adb
    path = '/home/chema/.android-sdks/platform-tools/adb'
    adb = ADB(path)

    if adb.set_adb_path(path):
        print("Version: %s" % adb.get_version())
    else:
        print("Check ADB binary path")
        return

    print(adb.get_devices())
Example #15
0
def main():
    # creates the ADB object
    adb = ADB()
    # IMPORTANT: You should supply the absolute path to ADB binary
    if adb.set_adb_path('/usr/bin/adb') is True:
        print("Version: %s" % adb.get_version())
    else:
        print("Check ADB binary path")

    apps = adb.shell_command("pm list packages")
    for app in apps:
        path = adb.shell_command("pm path {}".format(app.split(':')[1]))
        print("{}: {}".format(app, path))
Example #16
0
def main():
    # creates the ADB object
    adb = ADB()

    # set ADB path, using a couple of popular addresses.
    try:
        adb.set_adb_path('~/android-sdk-linux/platform-tools/adb')
    except ADB.BadCall:
        adb.set_adb_path(r'C:\Android\android-sdk\platform-tools\adb.exe')

    print("Version: %s" % adb.get_version())

    print("Waiting for device...")
    adb.wait_for_device()

    dev = adb.get_devices()

    if len(dev) == 0:
        print("Unexpected error, may be you're a very fast guy?")
        return

    print("Selecting: %s" % dev[0])
    adb.set_target_device(dev[0])

    print("Executing 'ls' command")
    output, error = adb.shell_command('ls')

    if output:
        print("Output:\n  %s" % "\n  ".join(output))
    if error:
        print("Error:\n  %s" % error)
Example #17
0
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
'''

import numpy as np
import os
import sys
import argparse

from pyadb import ADB
adb = ADB('adb')

PAGE_SIZE = 1024 * 1024 * 4
SIDEBAND_BUF_SIZE = PAGE_SIZE * 2

SAT_HOME = os.environ.get('SAT_HOME')

parser = argparse.ArgumentParser(description='sat-panic-fetch fetch crash data from system')
parser.add_argument('tracename', nargs='?', default=False, help='Panic trace matching trace filename')
parser.add_argument('-p', '--panic', action='store', help='Panic tracing mode: 1=Normal, 2=Hooked(default)',
                    required=False, default=2)
args = parser.parse_args()


def CrashlogKey(s):
    return int(s[8:])
Example #18
0
File: adb.py Project: bigzz/moniter
def main():

    adb = ADB()

    # set ADB path
    adb.set_adb_path('/home/bigzhang/Android/Sdk/platform-tools/adb')

    print "[+] Using PyADB version %s" % adb.pyadb_version()

    # verity ADB path
    print "[+] Verifying ADB path...",
    if adb.check_path() is False:
        print "ERROR"
        exit(-2)
    print "OK"

    # print ADB Version
    print "[+] ADB Version: %s" % adb.get_version()

    print ""

    # restart server (may be other instances running)
    print "[+] Restarting ADB server..."
    adb.restart_server()
    if adb.lastFailed():
        print "\t- ERROR\n"
        exit(-3)

    # get detected devices
    dev = 0
    while dev is 0:
        print "[+] Detecting devices..." ,
        error,devices = adb.get_devices()

        if error is 1:
            # no devices connected
            print "No devices connected"
            print "[+] Waiting for devices..."
            adb.wait_for_device()
            continue
        elif error is 2:
            print "You haven't enought permissions!"
            exit(-3)

        print "OK"
        dev = 1

    # this should never be reached
    if len(devices) == 0:
        print "[+] No devices detected!"
        exit(-4)

    # show detected devices
    i = 0
    for dev in devices:
        print "\t%d: %s" % (i,dev)
        i += 1

    # if there are more than one devices, ask to the user to choose one of them
    if i > 1:
        dev = i + 1
        while dev < 0 or dev > int(i - 1):
            print "\n[+] Select target device [0-%d]: " % int(i - 1) ,
            dev = int(stdin.readline())
    else:
        dev = 0

    # set target device
    try:
        adb.set_target_device(devices[dev])
    except Exception,e:
        print "\n[!] Error:\t- ADB: %s\t - Python: %s" % (adb.get_error(),e.args)
        exit(-5)
Example #19
0
        for size in self.__size_list:
            loop = 0
            print('=== %s ===\n' % size)
            fd.writelines('=== %s Size ===\n' % size)
            while loop < self.__times:
                self.__adb.shell_command('echo 3 > /proc/sys/vm/drop_caches')
                perf_out = self.__adb.shell_command(
                    '/data/lmdd if=%s of=internal move=%s fsync=1' %
                    (self.__target_path, size))
                print(perf_out)
                fd.writelines(perf_out)
                loop = loop + 1


if __name__ == '__main__':
    adb = ADB()
    adb.set_adb_path('/home/bigzhang/Android/Sdk/platform-tools/adb')
    # verity ADB path
    if adb.check_path() is False:
        print "ERROR"
        exit(-2)

    tester = LmddSpeed(None, None, adb)
    input_file = open('lmdd_perf_.log', 'wb+')

    tester.lmdd_header(input_file)
    tester.prepare_env()
    tester.lmdd_write(input_file)
    tester.lmdd_read(input_file)
    tester.finish()
Example #20
0
from pyadb import ADB
from struct import *
import os
os_path=os.getcwd()
#file_path=raw_input("please input .thumbdata file path:")

print "initializing ADB... Please allow the permission on your phone."
adb = ADB('/usr/bin/adb')
print "Waiting for device..."
adb.wait_for_device()
print "getting devices list..."
error,lst_device=adb.get_devices()
print "found " + str(len(lst_device)/2) + " devices."
print lst_device
#device_id=raw_input("input device id:")
print "locating thumbdata files.."
thumbfiles=adb.shell_command("ls -a /sdcard/DCIM/.thumbnails/ ")
lst_thumb=thumbfiles.split("\n")

for item in lst_thumb:
    if item.find(".thumbdata")!=-1:
        print "found:" + item
        print "copying..."
        #adb.run_cmd("pull /storage/emulated/0/DCIM/.thumbnails/" + item[:-1] + " " + os.getcwd() + "/tmp/" + item[:-1] )
        if not  os.path.isfile(os.getcwd() + "/tmp/" + item[:-1]):
            adb.get_remote_file("/sdcard/DCIM/.thumbnails/" + item[:-1] ,os.getcwd() + "/tmp/" + item[:-1] )
            print "copy OK!"
        else:
            print "cache found. skipping..."
        print "extracting thumb pictures..."
        if not os.path.exists(os.getcwd() + "/extract/" + item[:-1] ): # make a new dir
Example #21
0
 def __init__(self, *args, **kw):
     Fuse.__init__(self, *args, **kw)
     self.adb = ADB('adb')
Example #22
0
def main():
	APKTOOL = "/home/example/Downloads/apktool_2.0.0rc3.jar"  # APKTOOL Directory
	ADBTOOL = "/usr/bin/adb" # ADB Directory
	print "#################################################################################"
	print "#                                APKmole V1.0                                   #"
	print "# ADB & APKTool wrapper for application analysis located on an android device   #"
	print "# Author: Stas Volfus                                                           #"
	print "# the author isn't responsible for any damage caused by using this tool         #"                                                                              #"
	print "#################################################################################"
	print "\nADB Path: "+ADBTOOL
	print "APKtool Path: "+APKTOOL    
	print "\n\n[*] Setting up ADB.."
	adb = ADB()
	adb.set_adb_path(ADBTOOL) 	# path to adb..
	print "[*] Checking APKTool path.." ,
	if os.path.isfile(APKTOOL) is False:
		print R+"\t[FAILED] - path not found."+W
		exit(-1)
	print G+"\t[OK]"+W
	print "[*] Checking ADB path.." ,
	if adb.check_path() is False:
		print "\t"+R+"\t[FAILED] - ADB path doesn't exists..\n"+W
		exit(-2)
	print "\t"+G+"[OK]"+W
	print "[*] Restarting ADB server.." ,
	adb.restart_server()
	if adb.lastFailed():
		print "\t"+R+"[ERROR]"+W
		exit(-3)
	print "\t"+G+"[OK]"+W
	dev = 0
	while dev is 0:
		print "[*] Detecting devices..." ,
		error,devices = adb.get_devices()
		if error is 2:
			print R+"[-] You haven't enought permissions."+W
			exit(-3)
		print "\t"+G+"[OK]"+W
		dev = 1
		if len(devices) == 0:
			print C+"[-] No devices detected! waiting for devices.."+W
			adb.wait_for_device()
			error,devices = adb.get_devices()
			continue
	# devices...
	i = 0
	for dev in devices:
		print "\t%d: %s" % (i,dev)
		i += 1
	#more than one device..
	if i > 1:
		dev = i + 1
		while dev < 0 or dev > int(i - 1):
			print "\n[+] Select target device [0-%d]: " % int(i - 1) ,
			dev = int(stdin.readline())
	else:
		dev = 0
	try:
		adb.set_target_device(devices[dev])
	except Exception,e:
		print R+"\n[-] Error:\t- ADB: %s\t - Python: %s" % (adb.get_error(),e.args)
		exit(-5)
Example #23
0
def  pushfile(file):
    adb = ADB('/Users/aadebuger/Documents/android-sdk-mac_x86/platform-tools/adb') 
    print adb.pyadb_version()
    aa =adb.push_local_file(file, "storage/sdcard0/coursera"+"/")
#    aa=adb.shell_command("""push "%s" storage/sdcard0/coursera"""%(file))
    print 'lines=',aa    
	Receive data from Pupol Server broadcast using TCP/IP
	connection and establish an connection with Android devices
	sending shell_command for clicking.

	This is an inital design. Will need some improvement later.

	For using adb establishing connection, you need to install
	pyadb first.
'''
import zmq
import math
import signal
from pyadb import ADB
from sys import stdin, exit

adb = ADB()

def signal_handler(signal, frame):
	adb.kill_server()
	exit(0)

def main():

	# reference surface we are going to track
	surface_name = 'nexus'
	# error message constant
	error_message = 'Error occur in extracing gaze locataion'

	# lowest acceptant level
	con_level = 0.65
Example #25
0
class HotplugManager(threading.Thread):
    _instance = None

    def __init__(self, lock, config_path):
        print config_path
        self.conf = ConfigObj(config_path)
        self.adb = ADB(self.conf['mainConfiguration']
                                ['adbConfiguration']['adbPath'])
        self.adb.restart_server()
        self.lock = lock
        self.storage = ZODB.DB(None)
        self.connection = self.storage.open()
        self.root = self.connection.root
        self.root.devices = BTrees.OOBTree.BTree()

    def __new__(cls, *args, **kwargs):
        if not cls._instance:
            cls._instance = super(HotplugManager,
                                  cls).__new__(cls, *args, **kwargs)
            cls._ins = super(HotplugManager,
                             cls).__new__(cls, *args, **kwargs)
        return cls._instance

    @retry(libusb1.LIBUSB_ERROR_ACCESS, tries=2)
    def _usb_connection(self, device, event):
        """ TODO: Manage missing udev rules """
        
        key = "%04x:%04x" % (device.getVendorID(), device.getProductID())
        if event == 2:
            self.lock.acquire()
            try:
                # Delete key object from ZODB
                del self.root.devices[key]
                transaction.get().commit()
            except Exception as e:
                print str(e.message)
                transaction.abort()
                pass
            self.lock.release()

        elif event == 1 and device.getSerialNumber() is not None:
            self.adb.restart_server()
            devices = list(self.adb.get_devices())[1:][0]
            try:
                if device.getSerialNumber() in devices:
                    self.adb.set_target_device(device.getSerialNumber())
                    version = self.adb.shell_command('getprop ro.build.version.release').rstrip()
                    model = ''.join((self.adb.shell_command('settings get secure android_id')).splitlines())

                    self.lock.acquire()
                    try:
                        dm = DeviceManager(model, version)
                        self.root.devices[str(key)] = dm
                        transaction.commit()
                    except (Exception, AttributeError) as e:
                        print str(e.message)
                        transaction.abort()
                        pass
                    self.lock.release()

            except (IndexError, AttributeError, TypeError, KeyError) as e:
                print str(e.message)
                pass

        self.adb.kill_server()

    def callback(self, context, device, event):
        try:
            print "Device %s: %s" % (
                {
                    libusb1.LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED: 'arrived',
                    libusb1.LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT: 'left',
                }[event],
                device
            )

            self._usb_connection(device, event)

        except (AttributeError, libusb1.USBError) as e:
            print str(e.message)
            pass
import Tkinter as Tk
import sys
import os
import glob
import re
import thread
import time
workpath = os.path.dirname(sys.argv[0])

fields = "netperf-server", "single-duration", "test-times"
if sys.platform.startswith("win"):
    # the latest version works under windows
    sys.path.insert(0, os.path.join(workpath, "modules", "pyadb-master"))
    from pyadb import ADB
    adb = ADB(os.path.join(workpath, "adb-win", "adb"))
elif sys.platform.startswith("linux") or sys.platform.startswith("darwin"):
    # this old version works under linux
    sys.path.insert(0, os.path.join(workpath, "modules", "pyadb-81712c4"))
    from pyadb import ADB
    adb = None

    for i in os.environ['PATH'].split(':'):
        if len(glob.glob(os.path.join(i, "adb"))) > 0:
            adb = ADB(glob.glob(os.path.join(i, "adb"))[0])
            break
    if adb == None:
        if sys.platform.startswith("linux"):
            adb = ADB(os.path.join(workpath, "adb-linux", "adb"))
        elif sys.platform.startswith("darwin"):
            adb = ADB(os.path.join(workpath, "adb-darwin", "adb"))
Example #27
0
def main():
    # creates the ADB object
    adb = ADB()
    # IMPORTANT: You should supply the absolute path to ADB binary 
    if adb.set_adb_path('/home/chema/.android-sdks/platform-tools/adb') is True:
        print "Version: %s" % adb.get_version()
    else:
        print "Check ADB binary path"
    
    print "Waiting for device..."
    adb.wait_for_device()
    err,dev = adb.get_devices()
    
    if len(dev) == 0:
        print "Unexpected error, may be you're a very fast guy?"
        return
    
    print "Selecting: %s" % dev[0]
    adb.set_target_device(dev[0])
    
    print "Executing 'ls' command"
    adb.shell_command('ls')
    
    print "Output:\n%s" % adb.get_output()
Example #28
0
                      default = 10, type = "int")

    parser.add_option('-d', '--dest', dest = "target",
                      help = "The target test path, data or sdcard or sdcard1",
                      type = "string")

    (options, args) = parser.parse_args()

    # get adb path for config file.
    adb_conf = open('adb.conf', 'r')
    adbpath = adb_conf.readlines()
    adb_conf.close()
    if adbpath == []:
        print "Please config ADB PATH!"
        exit(0)
    adb = ADB()
    adb.set_adb_path(adbpath[0])
    # verity ADB path
    if adb.check_path() is False:
        print "ERROR: ADB PATH NOT Correct."
        exit(-2)

    # get detected devices
    dev = 0
    while dev is 0:
        print "Detecting devices..." ,
        error,devices = adb.get_devices()

        if len(devices) == 0:
            print "[+] No devices detected!"
            print "Waiting for devices..."
Example #29
0
if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='clean or pull line stickers')
    parser.add_argument('--clean', action='store_true', help='clean instead')
    parser.add_argument('--keep',
                        action='store_true',
                        help='keep all pulled stickers')
    parser.add_argument('--skipadb',
                        action='store_true',
                        help='skip adb pull, just generate html')
    args = parser.parse_args()

    with open('stickers.json') as jf:
        stickers_json = json.load(jf)

    if not args.skipadb:
        adb = ADB('{0}/platform-tools/adb'.format(os.environ['ANDROID_HOME']))

        if args.clean:
            adb.shell_command(
                'rm -rf /sdcard/Android/data/jp.naver.line.android/stickers')
            exit(0)

        print json.dumps(stickers_json,
                         sort_keys=True,
                         indent=2,
                         separators=(',', ': '))

        adb.get_remote_file(
            '/sdcard/Android/data/jp.naver.line.android/stickers', 'stickers')
        for d in os.listdir('stickers'):
            if d in stickers_json:
Example #30
0
def main():

    adb = ADB()

    # set ADB path
    adb.set_adb_path('~/android-sdk-linux/platform-tools/adb')

    print "[+] Using PyADB version %s" % adb.pyadb_version()

    # verity ADB path
    print "[+] Verifying ADB path...",
    if adb.check_path() is False:
        print "ERROR"
        exit(-2)
    print "OK"

    # print ADB Version
    print "[+] ADB Version: %s" % adb.get_version()

    print ""

    # restart server (may be other instances running)
    print "[+] Restarting ADB server..."
    adb.restart_server()
    if adb.lastFailed():
        print "\t- ERROR\n"
        exit(-3)

    # get detected devices
    dev = 0
    while dev is 0:
        print "[+] Detecting devices...",
        error, devices = adb.get_devices()

        if error is 1:
            # no devices connected
            print "No devices connected"
            print "[+] Waiting for devices..."
            adb.wait_for_device()
            continue
        elif error is 2:
            print "You haven't enought permissions!"
            exit(-3)

        print "OK"
        dev = 1

    # this should never be reached
    if len(devices) == 0:
        print "[+] No devices detected!"
        exit(-4)

    # show detected devices
    i = 0
    for dev in devices:
        print "\t%d: %s" % (i, dev)
        i += 1

    # if there are more than one devices, ask to the user to choose one of them
    if i > 1:
        dev = i + 1
        while dev < 0 or dev > int(i - 1):
            print "\n[+] Select target device [0-%d]: " % int(i - 1),
            dev = int(stdin.readline())
    else:
        dev = 0

    # set target device
    try:
        adb.set_target_device(devices[dev])
    except Exception, e:
        print "\n[!] Error:\t- ADB: %s\t - Python: %s" % (adb.get_error(),
                                                          e.args)
        exit(-5)
Example #31
0
    def lmdd_read(self, fd):
        fd.writelines('=============== lmdd read test ===============\n')
        for size in self.__size_list:
            loop = 0
            print('=== %s ===\n' %size)
            fd.writelines('=== %s Size ===\n' %size)
            while loop < self.__times:
                self.__adb.shell_command('echo 3 > /proc/sys/vm/drop_caches')
                perf_out = self.__adb.shell_command('/data/lmdd if=/data/dumb of=internal move=%s fsync=1' % size)
                print(perf_out)
                fd.writelines(perf_out)
                loop = loop + 1

if __name__ == '__main__':
    adb = ADB()
    adb.set_adb_path('/home/bigzhang/Android/Sdk/platform-tools/adb')
    # verity ADB path
    if adb.check_path() is False:
        print "ERROR"
        exit(-2)

    tester = LmddSpeed(None,None,adb)
    input_file = open('lmdd_perf_.log', 'wb+')

    tester.lmdd_header(input_file)
    tester.prepare_env()
    tester.lmdd_write(input_file)
    tester.lmdd_read(input_file)
    tester.finish()
Example #32
0
def  mkdir(dir):
    adb = ADB('/Users/aadebuger/Documents/android-sdk-mac_x86/platform-tools/adb') 
    print adb.pyadb_version()
    adb.shell_command("mkdir %s"%(dir))
Example #33
0
def main():

    adb = ADB()

    # set ADB path
    adb.set_adb_path('~/android-sdk-linux/platform-tools/adb')

    print("[+] Using PyADB version %s" % adb.pyadb_version())

    # verity ADB path
    print("[+] Verifying ADB path...", )
    if adb.check_path() is False:
        print("ERROR")
        exit(-2)
    print("OK")

    # print(ADB Version)
    print("[+] ADB Version: %s" % adb.get_version())

    print("")

    # restart server (may be other instances running)
    print("[+] Restarting ADB server...")
    adb.restart_server()
    if adb.last_failed():
        print("\t- ERROR\n")
        exit(-3)

    # get detected devices
    dev = 0
    while dev is 0:
        print("[+] Detecting devices...", )
        error, devices = adb.get_devices()

        if error is 1:
            # no devices connected
            print("No devices connected")
            print("[+] Waiting for devices...")
            adb.wait_for_device()
            continue
        elif error is 2:
            print("You haven't enought permissions!")
            exit(-3)

        print("OK")
        dev = 1

    # this should never be reached
    if len(devices) == 0:
        print("[+] No devices detected!")
        exit(-4)

    # show detected devices
    i = 0
    for dev in devices:
        print("\t%d: %s" % (i, dev))
        i += 1

    # if there are more than one devices, ask to the user to choose one of them
    if i > 1:
        dev = i + 1
        while dev < 0 or dev > int(i - 1):
            print("\n[+] Select target device [0-%d]: " % int(i - 1), )
            dev = int(stdin.readline())
    else:
        dev = 0

    # set target device
    try:
        adb.set_target_device(devices[dev])
    except Exception as e:
        print("\n[!] Error:\t- ADB: %s\t - Python: %s" %
              (adb.get_error(), e.args))
        exit(-5)

    print("\n[+] Using \"%s\" as target device" % devices[dev])

    # check if 'su' binary is available
    print("[+] Looking for 'su' binary: ", )
    supath = adb.find_binary("su")

    if supath is not None:
        print("%s" % supath)
    else:
        print("Error: %s" % adb.get_error())

    # 'su' binary has been found
    if supath is not None:
        print("[+] Checking if 'su' binary can give root access:")
        rootid = adb.shell_command('%s -c id' % supath)
        if adb.last_failed() is False and 'root' in rootid.replace(
                '(', ')').split(')'):  # it can provide root privileges
            print("\t- Yes")
            get_whatsapp_root(adb, supath)
        else:  # only have normal-user
            print("\t- No: %s" % adb.get_error())
            get_whatsapp_nonroot(adb)
    else:
        get_whatsapp_nonroot(adb)

    exit(0)
Example #34
0
def main():
    # creates the ADB object
    adb = ADB()
    # IMPORTANT: You should supply the absolute path to ADB binary
    if adb.set_adb_path(
            '/home/chema/.android-sdks/platform-tools/adb') is True:
        print("Version: %s" % adb.get_version())
    else:
        print("Check ADB binary path")

    print("Waiting for device...")
    adb.wait_for_device()
    err, dev = adb.get_devices()

    if len(dev) == 0:
        print("Unexpected error, may be you're a very fast guy?")
        return

    print("Selecting: %s" % dev[0])
    adb.set_target_device(dev[0])

    print("Executing 'ls' command")
    adb.shell_command('ls')

    print("Output:\n%s" % adb.get_output())
Example #35
0
class ADBFS(Fuse):
    opened = {}

    def __init__(self, *args, **kw):
        Fuse.__init__(self, *args, **kw)
        self.adb = ADB('adb')

    def connect(self):
        print 'Connect device to computer...'
        self.adb.wait_for_device()
        err = self.adb.get_error()
        if err:
            print 'ADB error:', err.strip()
            exit(5)

        print 'Driver enabled!'

    def _sh(self, cmd):
        try:
            return self.adb.shell_command("'%s'" % cmd) or ""
        except Exception as e:
            print 'Command ', cmd, 'failed:', self.adb.get_error()
            raise e
    
    def _ls(self, path):
        if USE_LS:
            return self._sh('ls "%s"' % path).split()
        return self._sh('ls -a "%s"' % path).splitlines()

    # ---- DIRECTORIES ----
    def readdir(self, path, offset):
        if self._sh('test -d "%s"&&echo true' % path).strip() == 'true':
            if path[:-1] != '/':
                path += '/'
            dd = self._ls(path)
            for i in dd:
                yield Direntry(i)

    def rmdir(self, path):
        self.adb.shell_command('rmdir "%s"' % path)
        non_cached(path)

    def mkdir(self, path, mode):
        self.adb.shell_command('mkdir "%s"' % path)
        self.adb.shell_command('chmod %s "%s"' % (oct(mode), path))
        non_cached(path)

    # ---- FILES ----
    def create(self, path, mode):
        self.adb.shell_command('echo "" >"%s"' % path)
        self.adb.shell_command('chmod %s "%s"' % (oct(mode), path))
        non_cached(path)

    def mknod(self, path, mode, dev):
        self.adb.shell_command('touch "%s"' % path)
        self.adb.shell_command('chmod %s "%s"' % (oct(mode), path))
        non_cached(path)

    def open(self, path, flags):
        if self._sh('test -e "%s"&&echo true' % path).strip() != 'true':
            return -ENOENT

        if path in self.opened:
            self.opened[path][1] += 1
        else:
            rfn = cached(path, lambda x: self.adb.get_remote_file(path, x))
            self.opened[path] = [open(rfn, 'rb+'), 1]

    def release(self, path, flags):
        f = self.opened[path]
        f[1] -= 1
        if f[1] == 0:
            f[0].close()
            del self.opened[path]

    def read(self, path, size, offset):
        f = self.opened[path][0]
        f.seek(0, 2)
        slen = f.tell()
        if offset < slen:
            if offset + size > slen:
                size = slen - offset

            f.seek(offset)
            return f.read(size)
        return ''

    def write(self, path, data, offset):
        f = self.opened[path][0]
        f.seek(0, 2)
        slen = f.tell()
        if offset < slen:

            f.seek(offset)
            l = f.write(data)

            rfn = cached(path, lambda x: self.adb.get_remote_file(path, x))
            self.adb.push_local_file(rfn, path)
            return l
        return 0

    def fsync(self, path):
        if path in FILES_CACHE:
            rfn = FILES_CACHE[path]
            self.adb.push_local_file(rfn, path)
            non_cached(path)

    def unlink(self, path):
        self.adb.shell_command('rm "%s"' % path)
        non_cached(path)

    # ---- OTHER ----
    @lru_cache
    def getattr(self, path):
        st = Stat()
        st.st_nlink = 1
        if self._sh('test -e "%s"&&echo true' % path).strip() != 'true':
            return -ENOENT

        elif self._sh('test -h "%s"&&echo true' % path).strip() == 'true':
            st.st_mode = stat.S_IFLNK

        elif self._sh('test -d "%s"&&echo true' % path).strip() == 'true':
            st.st_mode = stat.S_IFDIR

        elif self._sh('test -f "%s"&&echo true' % path).strip() == 'true':
            st.st_mode = stat.S_IFREG

        elif self._sh('test -c "%s"&&echo true' % path).strip() == 'true':
            st.st_mode = stat.S_IFCHR

        elif self._sh('test -b "%s"&&echo true' % path).strip() == 'true':
            st.st_mode = stat.S_IFBLK

        elif self._sh('test -p "%s"&&echo true' % path).strip() == 'true':
            st.st_mode = stat.S_IFIFO

        elif self._sh('test -s "%s"&&echo true' % path).strip() == 'true':
            st.st_mode = stat.S_IFSOCK

        else:
            st.st_mode = 0

        st.st_mode |= int(self._sh('stat -c%%a "%s"' % path) or '0', 8)
        st.st_size = int(self._sh('stat -c%%s "%s"' % path) or '0')
        print "file:", path, "size: ", st.st_size, "mode:", oct(st.st_mode)

        return st

    def chmod(self, path, mode):
        self._sh('chmod %s "%s"' % (oct(mode), path))
        non_cached(path)

    def chown(self, oid, gid, path):
        pass # TODO: chown

    def rename(self, path, new):
        self._shd('mv "%s" "%s"' % (path, new))
        non_cached(path)
        non_cached(new)

    def statfs(self):
        st = StatVfs()
        st.f_bsize = 1024
        st.f_frsize = 1024
        st.f_bfree = 0
        st.f_bavail = 0
        st.f_files = 2
        st.f_blocks = 4
        st.f_ffree = 0
        st.f_favail = 0
        st.f_namelen = 255
        return st
	Receive data from Pupol Server broadcast using TCP/IP
	connection and establish an connection with Android devices
	sending shell_command for clicking.

	This is an inital design. Will need some improvement later.

	For using adb establishing connection, you need to install
	pyadb first.
'''
import zmq
import math
import signal
from pyadb import ADB
from sys import stdin, exit

adb = ADB()


def signal_handler(signal, frame):
    adb.kill_server()
    exit(0)


def main():

    # reference surface we are going to track
    surface_name = 'nexus'
    # error message constant
    error_message = 'Error occur in extracing gaze locataion'

    # lowest acceptant level
Example #37
0
def main():
    APKTOOL = "/home/example/Downloads/apktool_2.0.0rc3.jar"  # APKTOOL Directory
    ADBTOOL = "/usr/bin/adb"  # ADB Directory
    print "#################################################################################"
    print "#                                APKmole V1.0                                   #"
    print "# ADB & APKTool wrapper for application analysis located on an android device   #"
    print "# Author: Stas Volfus                                                           #"
    print "# the author isn't responsible for any damage caused by using this tool         #"  #"
    print "#################################################################################"
    print "\nADB Path: " + ADBTOOL
    print "APKtool Path: " + APKTOOL
    print "\n\n[*] Setting up ADB.."
    adb = ADB()
    adb.set_adb_path(ADBTOOL)  # path to adb..
    print "[*] Checking APKTool path..",
    if os.path.isfile(APKTOOL) is False:
        print R + "\t[FAILED] - path not found." + W
        exit(-1)
    print G + "\t[OK]" + W
    print "[*] Checking ADB path..",
    if adb.check_path() is False:
        print "\t" + R + "\t[FAILED] - ADB path doesn't exists..\n" + W
        exit(-2)
    print "\t" + G + "[OK]" + W
    print "[*] Restarting ADB server..",
    adb.restart_server()
    if adb.lastFailed():
        print "\t" + R + "[ERROR]" + W
        exit(-3)
    print "\t" + G + "[OK]" + W
    dev = 0
    while dev is 0:
        print "[*] Detecting devices...",
        error, devices = adb.get_devices()
        if error is 2:
            print R + "[-] You haven't enought permissions." + W
            exit(-3)
        print "\t" + G + "[OK]" + W
        dev = 1
        if len(devices) == 0:
            print C + "[-] No devices detected! waiting for devices.." + W
            adb.wait_for_device()
            error, devices = adb.get_devices()
            continue
    # devices...
    i = 0
    for dev in devices:
        print "\t%d: %s" % (i, dev)
        i += 1
    #more than one device..
    if i > 1:
        dev = i + 1
        while dev < 0 or dev > int(i - 1):
            print "\n[+] Select target device [0-%d]: " % int(i - 1),
            dev = int(stdin.readline())
    else:
        dev = 0
    try:
        adb.set_target_device(devices[dev])
    except Exception, e:
        print R + "\n[-] Error:\t- ADB: %s\t - Python: %s" % (adb.get_error(),
                                                              e.args)
        exit(-5)
Example #38
0
def update_db():
	adb = ADB()
        adb.set_adb_path('adb')

	adb.connect_remote(smartphone_addr)

        cmd = "su -c 'cat /data/data/com.android.providers.telephony/databases/mmssms.db > /sdcard/mmssms.db'"
        adb.shell_command(cmd)

	cmd = "su -c 'cat /data/data/com.android.providers.telephony/databases/mmssms.db-journal > /sdcard/mmssms.db-journal'"
        adb.shell_command(cmd)
	

        adb.get_remote_file('/sdcard/mmssms.db','./')
	adb.get_remote_file('/sdcard/mmssms.db-journal','./')

        cmd = "su -c 'rm /sdcard/mmssms.db'"
	adb.shell_command(cmd)
	cmd = "su -c 'rm /sdcard/mmssms.db-journal'"
        adb.shell_command(cmd)
Example #39
0
def main():

    adb = ADB()

    # set ADB path
    adb.set_adb_path('~/android-sdk-linux/platform-tools/adb')

    print("[+] Using PyADB version %s" % adb.pyadb_version())

    # verity ADB path
    print("[+] Verifying ADB path...",)
    if adb.check_path() is False:
        print("ERROR")
        exit(-2)
    print("OK")

    # print(ADB Version)
    print("[+] ADB Version: %s" % adb.get_version())

    print("")

    # restart server (may be other instances running)
    print("[+] Restarting ADB server...")
    adb.restart_server()
    if adb.last_failed():
        print("\t- ERROR\n")
        exit(-3)

    # get detected devices
    dev = 0
    while dev is 0:
        print("[+] Detecting devices..." ,)
        error,devices = adb.get_devices()

        if error is 1:
            # no devices connected
            print("No devices connected")
            print("[+] Waiting for devices...")
            adb.wait_for_device()
            continue
        elif error is 2:
            print("You haven't enought permissions!")
            exit(-3)

        print("OK")
        dev = 1

    # this should never be reached
    if len(devices) == 0:
        print("[+] No devices detected!")
        exit(-4)

    # show detected devices
    i = 0
    for dev in devices:
        print("\t%d: %s" % (i,dev))
        i += 1

    # if there are more than one devices, ask to the user to choose one of them
    if i > 1:
        dev = i + 1
        while dev < 0 or dev > int(i - 1):
            print("\n[+] Select target device [0-%d]: " % int(i - 1) ,)
            dev = int(stdin.readline())
    else:
        dev = 0

    # set target device
    try:
        adb.set_target_device(devices[dev])
    except Exception as e:
        print("\n[!] Error:\t- ADB: %s\t - Python: %s" % (adb.get_error(),e.args))
        exit(-5)

    print("\n[+] Using \"%s\" as target device" % devices[dev])

    # check if 'su' binary is available
    print("[+] Looking for 'su' binary: ",)
    supath = adb.find_binary("su")

    if supath is not None:
        print("%s" % supath)
    else:
        print("Error: %s" % adb.get_error())

    # 'su' binary has been found
    if supath is not None:
        print("[+] Checking if 'su' binary can give root access:")
        rootid = adb.shell_command('%s -c id' % supath)
        if adb.last_failed() is False and 'root' in rootid.replace('(',')').split(')'): # it can provide root privileges
            print("\t- Yes")
            get_whatsapp_root(adb,supath)
        else: # only have normal-user
            print("\t- No: %s" % adb.get_error())
            get_whatsapp_nonroot(adb)
    else:
        get_whatsapp_nonroot(adb)

    exit(0)
Example #40
0
def main():
    logging.basicConfig(level=logging.WARNING)
    adb = ADB()

    # set ADB path, using a couple of popular addresses.
    try:
        adb.set_adb_path('~/android-sdk-linux/platform-tools/adb')
    except ADB.BadCall:
        adb.set_adb_path(r'C:\Android\android-sdk\platform-tools\adb.exe')

    print("[+] Using PyADB version %s" % adb.pyadb_version())

    # verity ADB path
    print("[+] Verifying ADB path...", end='')
    if not adb.check_path():
        print("ERROR")
        exit(-2)
    print("OK")

    # print ADB Version
    print("[+] ADB Version: %s" % adb.get_version())

    print("")

    # restart server (may be other instances running)
    print("[+] Restarting ADB server...")
    try:
        adb.restart_server()
    except Exception as err:
        print("\t- ERROR\n", err)
        exit(-3)

    # get detected devices
    while True:
        print("[+] Detecting devices...", end=' ')
        try:
            devices = adb.get_devices()
        except adb.PermissionsError:
            devices = None
            print("You haven't enough permissions!")
            exit(-3)

        if devices:
            print("OK")
            break

        # no devices connected
        print("No devices connected")
        print("[+] Waiting for devices...")
        adb.wait_for_device()

    # this should never be reached
    if len(devices) == 0:
        print("[+] No devices detected!")
        exit(-4)

    # show detected devices
    i = 0
    for dev in devices:
        print("\t%d: %s" % (i, dev))
        i += 1

    # if there are more than one devices, ask to the user to choose one of them
    if i > 1:
        dev = i + 1
        while dev < 0 or dev > int(i - 1):
            print("\n[+] Select target device [0-%d]: " % int(i - 1), end=' ')
            dev = int(stdin.readline())
    else:
        dev = 0

    # set target device
    try:
        adb.set_target_device(devices[dev])
    except Exception as e:
        print("\n[!] Error: " % e)
        exit(-5)

    print("\n[+] Using \"%s\" as target device" % devices[dev])

    # check if 'su' binary is available
    print("[+] Looking for 'su' binary: ", end=' ')

    try:
        supath = adb.find_binary("su")
    except ADB.AdbException as err:
        if str(err) != "'su' was not found":
            print("Error: %s" % err)
            exit(-6)
        supath = None

    if supath is not None:
        # 'su' binary has been found

        print("[+] Checking if 'su' binary can give root access:")
        try:
            rootid = adb.shell_command('%s -c id' % supath)
            if 'root' in rootid.replace('(', ')').split(')'):
                # it can provide root privileges
                print("\t- Yes")
                get_whatsapp_root(adb, supath)
            else:
                print("\t- No: %s" % rootid)
                get_whatsapp_nonroot(adb)
        except adb.AdbException as err:
            print("\t- No: %s" % err)
            get_whatsapp_nonroot(adb)
    else:
        print("Not found.")
        get_whatsapp_nonroot(adb)

    exit(0)
Example #41
-1
 def __init__(self, lock, config_path):
     print config_path
     self.conf = ConfigObj(config_path)
     self.adb = ADB(self.conf['mainConfiguration']
                             ['adbConfiguration']['adbPath'])
     self.adb.restart_server()
     self.lock = lock
     self.storage = ZODB.DB(None)
     self.connection = self.storage.open()
     self.root = self.connection.root
     self.root.devices = BTrees.OOBTree.BTree()