想了解更多关于开源的体方提供内容,请访问:
51CTO 开源基础软件社区
https://ost.51cto.com
之前在《OpenHarmony设备直装hap脱离电脑hdc的案开两种实现思路》一文中,我提到了两种实现直装hap的发S服务思路,上篇文章已经讲过了第一种思路(包管理API)的设备实现细节了,那这次再来分享一下第二种思路(另辟蹊径)的端直的具调用实现细节。
第二种思路是体方提供:开发一个shell命令服务放到系统内,用于操作bm/aa等本地shell命令去安装和打开应用,案开并提供http或其他协议的发S服务接口给上层应用调用。很明显这种方式违背了OpenHarmony的访问控制权限机制,只需要申请一个基本的INTERNET权限用于调用本机接口即可,这种方式很不安全,只是探索研究和尝试。
这里以go语言为例。
myshell.go:
package mainimport ( "fmt" "log" "net/http" "os/exec" "strings")func main() { http.HandleFunc("/execCommand", ExecCommand) err := http.ListenAndServe("0.0.0.0:23333", nil) if err != nil { log.Fatal("ListenAndServe: ", err) }}func ExecCommand(w http.ResponseWriter, r *http.Request) { name := r.FormValue("name") args := r.FormValue("args") argsArr := strings.Split(args, " ") cmd := exec.Command(name, argsArr...) out, err := cmd.CombinedOutput() if err != nil { _, err := fmt.Fprintf(w, err.Error()) if err != nil { return } return } _, err = fmt.Fprintf(w, string(out)) if err != nil { return }}
在 windows 平台上交叉编译生成 linux arm64 平台的的可执行程序。
SET CGO_ENABLED=0SET GOOS=linuxSET GOARCH=arm64go build -o myshell myshell.go
编写一个 myshell.cfg 文件,用于描述开机自启shell服务的信息。
{ "import" : [], "jobs" : [{ "name" : "init", "cmds" : [ "start myshell" ] } ], "services" : [{ "name" : "myshell", "path" : ["/system/bin/myshell"] } ]}
推送 myshell 和 myshell.cfg 到系统目录,然后重启设备,此服务将开机自启。
hdc shell mount -o remount,rw /hdc file send myshell /system/bin/myshellhdc file send myshell.cfg /system/etc/init/myshell.cfghdc shell chmod 777 /system/bin/myshellhdc shell reboot
entry/src/main/module.json5:
{ "name": "ohos.permission.INTERNET",},
调用刚才开发的shell服务提供的htpp接口,传递两个参数,第一个name是调用本地shell的绝对路径,第二个args是要执行命令的参数
import http from '@ohos.net.http';function installAppByMyShell() { let httpRequest = http.createHttp(); httpRequest.request("http://127.0.0.1:23333/execCommand", { method: http.RequestMethod.POST, header: { 'Content-Type': 'application/x-www-form-urlencoded' }, extraData: "name=/bin/bm&args=install -r -p /data/local/tmp/testapp.hap", }, (err, data) => { if (!err) { if (data.responseCode == 200) { if (data.result.toString().startsWith("install bundle successfully.")) { promptAction.showToast({ message: '安装成功', duration: ToastDuration}); } else { promptAction.showToast({ message: '安装失败', duration: ToastDuration}); } } } else { console.info('error:' + JSON.stringify(err)); httpRequest.destroy(); } } );}
由于这种实现方法的特殊性,你可以通过http接口调用任何本地的shell命令,因此,你可以调用bm/aa等本地shell去实现打开应用、卸载应用,甚至是其他的任何操作。
想了解更多关于开源的内容,请访问:
51CTO 开源基础软件社区
https://ost.51cto.com
责任编辑:jianghua 来源: 51CTO 开源基础软件社区 发Shell服务鸿蒙(责任编辑:热点)
“双11”全国快件量达47.76亿件 11日当天共处理快件6.96亿件
V观财报|信披存瑕疵或误导投资者,汉马科技及时任董秘被监管警示
Remedy与R星陷入商标纠纷 / 微星新显示器搭载“物理外挂”