利用ADB 协议建立PC与手机端本地unix套接字的连接

来源:互联网 发布:网络的利与弊作文800 编辑:程序博客网 时间:2024/05/18 03:44

设置环境变量
export ADB_TRACE=adb
可以取的值包括 all, adb, sockets, packets, rwx, usb, sync, sysdeps, transport, jdwp, services, auth, fdevent, shell
取多个值用空格分割

但是adb 内部限制了输出的字数,导致最重要的writex输出(即最总发送给adb server的数据)长度只有16字节。为此,必须修改代码:
system/core/adb_utils.cpp文件,找到

 std::string dump_hex(const void* data, size_t byte_count) {-    byte_count = std::min(byte_count, size_t(16));+    //byte_count = std::min(byte_count, size_t(16));

重新编译adb
make adb

adb发送的协议是 4字节16进制数+命令。
比如 adb devices
发送的命令就是 000chost:devices
返回: ‘OKAY0010d9dbe061\tdevice\n’

adb shell 命令:
需要先发送: 0012host:transport-any
收到 ‘OKAY’
继续发送’0029shell:ls\ncat /proc/net/unix’
收到 ‘OKAYacct init.miui.post_boot.sh oem \nbin init.miui.rc persist \nbt_firmware init.miui8.rc proc \nbugreports init.msm.usb.configfs.rc property_contexts \ncache init.offline.log.rc res \ncharger init.qcom.class_core.sh root \nconfig init.qcom.early_boot.sh sbin \ncust init.qcom.factory.rc sdcard …’
可以看到,shell: 后跟命令,而且可以用’\n’发送多个命令。返回值是OKAY后加结果。
在实际中,adb shell ls 这样的命令,会发送”shell,v2,TERM=xterm:ls” 这样的字符串,这样返回值中就会带有xterm的很多标志字符串。
如果你只是取数据的话,用”shell:< command >”的方法是最简单的。

adb forward tcp:7843 localabstract:unix_name
将手机上的一个unix套接字foward到端口7843上。
发送 ‘host:forward:tcp:7843;localabstract:unix_name’
将得到 OKAY
随后,你就可以访问localhost:7843了。
localabstract是用在抽象套接字上的,在手机上,用adb shell cat /proc/net/unix 凡是名字前面有’@’的都是抽象套接字
抽象套接字不需要创建一个文件节点,所以免去了linux权限。创建抽象套接字,只需要在套接字名字的第一个字符指定为 ‘\0’即可。

如何在不指定本地端口号的情况下,直接连接远程的unix socket呢?
这个方法是和shell的方法类似,
需要先发送: 0012host:transport-any
收到 ‘OKAY’
继续发送’003blocalabstract:…..’
收到’OKAY’后, 不要关闭socket,继续发送消息即可

用python实现的模拟发送

import socketimport timeunix_name='you_name'def query(s, msgs):    for msg in msgs:        pro_msg = "%04x%s"%(len(msg),msg)        print("send:",pro_msg)        s.send(pro_msg)        time.sleep(0.2)        reply = s.recv(1024*1024)        print('recv:', reply)def adb_query(*msgs):    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM);    s.connect((socket.gethostbyname('localhost'), 5037))    query(s, msgs)    s.close()def forward(unixname, func):    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM);    s.connect((socket.gethostbyname('localhost'), 5037))    msg = "localabstract:%s" % unixname    query(s,('host:transport-any', msg))    func(s)    s.close()def http_request(s):    s.send('GET / HTTP/1.1\r\n\r\n')    res = s.recv(1024)    print(res)adb_query('host:devices')adb_query('host:transport-any', 'shell:ls\ncat /proc/net/unix')forward(unix_name, http_request)
阅读全文
0 0
原创粉丝点击