Linux、MacOS本地调用STF远程设备(stf.sh、stf-connect.js、stf-disconnect.js)

本文档介绍了如何使用shell脚本(stf.sh)和Node.js脚本(stf-connect.js, stf-disconnect.js)连接并管理远程Android设备。在过程中遇到了设备状态错误和依赖缺失的问题,通过检查设备状态和安装缺失模块得以解决。
摘要由CSDN通过智能技术生成

本次安装红色部分
在这里插入图片描述

前提条件
远程服务器STF已连接手机
官方脚本地址

方式1:使用sh脚本(本地为Linux或MacOS系统)

官方脚本

stf.sh

#!/usr/bin/env bash

set -euxo pipefail

if [ "$DEVICE_SERIAL" == "" ]; then
    echo "Please specify device serial using ENV['DEVICE_SERIAL']"
    exit 1
fi

if [ "$STF_URL" == "" ]; then
    echo "Please specify stf url using ENV['STF_URL']"
    exit 1
fi

if [ "$STF_TOKEN" == "" ]; then
    echo "Please specify stf token using using ENV['STF_TOKEN']"
    exit 1
fi

function add_device
{
    response=$(curl -X POST -H "Content-Type: application/json" \
                 -H "Authorization: Bearer $STF_TOKEN" \
                 --data "{\"serial\": \"$DEVICE_SERIAL\"}" $STF_URL/api/v1/user/devices)

    success=$(echo "$response" | jq .success | tr -d '"')
    description=$(echo "$response" | jq .description | tr -d '"')

    if [ "$success" != "true" ]; then
        echo "Failed because $description"
        exit 1
    fi

    echo "Device $DEVICE_SERIAL added successfully"
}

function remote_connect
{
    response=$(curl -X POST \
                 -H "Authorization: Bearer $STF_TOKEN" \
                $STF_URL/api/v1/user/devices/$DEVICE_SERIAL/remoteConnect)

    success=$(echo "$response" | jq .success | tr -d '"')
    description=$(echo "$response" | jq .description | tr -d '"')

    if [ "$success" != "true" ]; then
        echo "Failed because $description"
        exit 1
    fi
    remote_connect_url=$(echo "$response" | jq .remoteConnectUrl | tr -d '"')

    adb connect $remote_connect_url

    echo "Device $DEVICE_SERIAL remote connected successfully"
}

function remove_device
{
    response=$(curl -X DELETE \
                 -H "Authorization: Bearer $STF_TOKEN" \
                $STF_URL/api/v1/user/devices/$DEVICE_SERIAL)

    success=$(echo "$response" | jq .success | tr -d '"')
    description=$(echo "$response" | jq .description | tr -d '"')

    if [ "$success" != "true" ]; then
        echo "Failed because $description"
        exit 1
    fi

    echo "Device $DEVICE_SERIAL removed successfully"
}

登录STF创建访问令牌

在这里插入图片描述
在这里插入图片描述

将地址复制到stf.sh脚本STF_URL的值
将生产的令牌复制到脚本STF_TOKEN的值

修改脚本

修改stf.sh

#!/usr/bin/env bash

set -euxo pipefail

# 默认设备serial序列号device
DEVICE_SERIAL=device
STF_URL=http://192.168.111.129:7100
STF_TOKEN=c6d87223ba024acaa6a9ab031d9cfb9ba108abf2d9ed40ca98e2f737e1714b25

#if [ "$DEVICE_SERIAL" == "" ]; then
#    echo "Please specify device serial using ENV['DEVICE_SERIAL']"
#    exit 1
#fi
#
#if [ "$STF_URL" == "" ]; then
#    echo "Please specify stf url using ENV['STF_URL']"
#    exit 1
#fi
#
#if [ "$STF_TOKEN" == "" ]; then
#    echo "Please specify stf token using using ENV['STF_TOKEN']"
#    exit 1
#fi

function add_device
{
    response=$(curl -X POST -H "Content-Type: application/json" \
                 -H "Authorization: Bearer $STF_TOKEN" \
                 --data "{\"serial\": \"$DEVICE_SERIAL\"}" $STF_URL/api/v1/user/devices)

    success=$(echo "$response" | jq .success | tr -d '"')
    description=$(echo "$response" | jq .description | tr -d '"')

    if [ "$success" != "true" ]; then
        echo "Failed because $description"
        exit 1
    fi

    echo "Device $DEVICE_SERIAL added successfully"
}

function remote_connect
{
    response=$(curl -X POST \
                 -H "Authorization: Bearer $STF_TOKEN" \
                $STF_URL/api/v1/user/devices/$DEVICE_SERIAL/remoteConnect)

    success=$(echo "$response" | jq .success | tr -d '"')
    description=$(echo "$response" | jq .description | tr -d '"')

    if [ "$success" != "true" ]; then
        echo "Failed because $description"
        exit 1
    fi
    remote_connect_url=$(echo "$response" | jq .remoteConnectUrl | tr -d '"')

    adb connect $remote_connect_url

    echo "Device $DEVICE_SERIAL remote connected successfully"
}

function remove_device
{
    response=$(curl -X DELETE \
                 -H "Authorization: Bearer $STF_TOKEN" \
                $STF_URL/api/v1/user/devices/$DEVICE_SERIAL)

    success=$(echo "$response" | jq .success | tr -d '"')
    description=$(echo "$response" | jq .description | tr -d '"')

    if [ "$success" != "true" ]; then
        echo "Failed because $description"
        exit 1
    fi

    echo "Device $DEVICE_SERIAL removed successfully"
}

执行脚本

[root@WzcWyt demo]# ll
-rw-r--r-- 1 root root 2143 Nov 15 14:33 stf.sh
# 如果报错可以查看执行命令的过程
# [root@WzcWyt demo]# bash -x
[root@WzcWyt demo]# . stf.sh 

申请要用的设备,复制Serial序列号

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
申请要用的设备

[root@WzcWyt demo]# DEVICE_SERIAL=P7CDU18929008778

将远程设备添加到本地,报错找问题1

[root@WzcWyt demo]# add_device
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100    88  100    58  100    30     19      9  0:00:03  0:00:03 --:--:--    19
Device P7CDU18929008778 added successfully
[[root@WzcWyt demo]# remote_connect
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   102  100   102    0     0   5415      0 --:--:-- --:--:-- --:--:--  5666
failed to authenticate to 192.168.31.103:7509
Device P7CDU18929008778 remote connected successfully

执行上面命令后,需要到stf页面添加一下指纹
在这里插入图片描述
查看设备

[root@WzcWyt demo]# adb devices
List of devices attached
192.168.31.103:7509     unauthorized

[root@WzcWyt demo]# 

下面就可以用这台设备做自动化了

删除远程设备

[root@WzcWyt demo]# adb disconnect
disconnected everything
[root@WzcWyt demo]# adb devices   
List of devices attached

[root@WzcWyt demo]# remove_device
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100    60  100    60    0     0   1196      0 --:--:-- --:--:-- --:--:--  1224
Device P7CDU18929008778 removed successfully
[root@WzcWyt demo]# adb devices  
List of devices attached

[root@WzcWyt demo]# 

方式2:使用Nodejs

stf-connect.js

var Swagger = require('swagger-client');

var SWAGGER_URL = 'https://stf.example.org/api/v1/swagger.json';
var AUTH_TOKEN  = 'xx-xxxx-xx';

// Using Promise
var client = new Swagger({
  url: SWAGGER_URL
, usePromise: true
, authorizations: {
    accessTokenAuth: new Swagger.ApiKeyAuthorization('Authorization', 'Bearer ' + AUTH_TOKEN, 'header')
  }
})

var serial = process.argv.slice(2)[0]

client.then(function(api) {
  return api.devices.getDeviceBySerial({
    serial: serial
  , fields: 'serial,present,ready,using,owner'
  }).then(function(res) {
      // check if device can be added or not
      var device = res.obj.device
      if (!device.present || !device.ready || device.using || device.owner) {
        console.log('Device is not available')
        return
      }

      // add device to user
      return api.user.addUserDevice({
        device: {
          serial: device.serial
        , timeout: 900000
        }
      }).then(function(res) {
        if (!res.obj.success) {
          console.log('Could not add device')
          return
        }

        // get remote connect url
        return api.user.remoteConnectUserDeviceBySerial({
          serial: device.serial
        }).then(function(res) {
          console.log(res.obj.remoteConnectUrl)
        })
      })
  })
})

执行命令,添加设备,报错找问题3

node stf-connect.js xxxx
# $PROVIDR_IP:16829

stf-disconnect.js

var Swagger = require('swagger-client');

var SWAGGER_URL = 'https://stf.example.org/api/v1/swagger.json';
var AUTH_TOKEN  = 'xx-xxxx-xx';

var client = new Swagger({
  url: SWAGGER_URL
, usePromise: true
, authorizations: {
    accessTokenAuth: new Swagger.ApiKeyAuthorization('Authorization', 'Bearer ' + AUTH_TOKEN, 'header')
  }
})

var serial = process.argv.slice(2)[0]

client.then(function(api) {  
  return api.user.getUserDevices({
    serial: serial
  , fields: 'serial,present,ready,using,owner'
  }).then(function(res) {
      // check if user has that device or not
      var devices = res.obj.devices
      var hasDevice = false

      devices.forEach(function(device) {
        if(device.serial === serial) {
          hasDevice = true;
        }
      })

      if (!hasDevice) {
        console.log('You do not own that device')
        return
      }

      return api.user.deleteUserDeviceBySerial({
        serial: serial
      }).then(function(res) {
        if (!res.obj.success) {
          console.log('Could not disconnect')
          return
        }
        console.log('Device disconnected successfully!')
      })
  })
})

执行命令,断开设备

node stf-disconnect.js xxxx
# Device disconnected successfully!

遇到问题1

[root@localhost ~]# add_device
+ add_device
++ curl -X POST -H 'Content-Type: application/json' -H 'Authorization: Bearer c6d87223ba024acaa6a9ab031d9cfb9ba108abf2d9ed40ca98e2f737e1714b25' --data '{"serial": "P7CDU18929008778"}' http://192.168.31.103:7100/api/v1/user/devices
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   101  100    71  100    30   6184   2613 --:--:-- --:--:-- --:--:--  7888
+ response='{"success":false,"description":"Device is being used or not available"}'
++ echo '{"success":false,"description":"Device is being used or not available"}'
++ jq .success
-bash: jq: 未找到命令
++ tr -d '"'
+ success=

解决办法: 安装jq
点击跳转到安装jq教程

遇到问题2

[root@localhost ~]# add_device
+ add_device
++ curl -X POST -H 'Content-Type: application/json' -H 'Authorization: Bearer c6d87223ba024acaa6a9ab031d9cfb9ba108abf2d9ed40ca98e2f737e1714b25' --data '{"serial": "P7CDU18929008778"}' http://192.168.31.103:7100/api/v1/user/devices
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   101  100    71  100    30     69     29  0:00:01  0:00:01 --:--:--    69
+ response='{"success":false,"description":"Device is being used or not available"}'
++ jq .success
++ tr -d '"'
++ echo '{"success":false,"description":"Device is being used or not available"}'
+ success=false
++ echo '{"success":false,"description":"Device is being used or not available"}'
++ tr -d '"'
++ jq .description
+ description='Device is being used or not available'
+ '[' false '!=' true ']'
+ echo 'Failed because Device is being used or not available'
Failed because Device is being used or not available
+ exit 1
登出

解决办法:设备一定要是未使用状态
在这里插入图片描述

遇到问题3

E:\dome>node stf-disconnect.js 123
internal/modules/cjs/loader.js:796
    throw err;
    ^

Error: Cannot find module 'swagger-client'
Require stack:
- E:\dome\stf-disconnect.js
[90m    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:793:17)[39m
[90m    at Function.Module._load (internal/modules/cjs/loader.js:686:27)[39m
[90m    at Module.require (internal/modules/cjs/loader.js:848:19)[39m
[90m    at require (internal/modules/cjs/helpers.js:74:18)[39m
    at Object.<anonymous> (E:\dome\stf-disconnect.js:1:15)
[90m    at Module._compile (internal/modules/cjs/loader.js:955:30)[39m
[90m    at Object.Module._extensions..js (internal/modules/cjs/loader.js:991:10)[39m
[90m    at Module.load (internal/modules/cjs/loader.js:811:32)[39m
[90m    at Function.Module._load (internal/modules/cjs/loader.js:723:14)[39m
[90m    at Function.Module.runMain (internal/modules/cjs/loader.js:1043:10)[39m {
  code: [32m'MODULE_NOT_FOUND'[39m,
  requireStack: [ [32m'E:\\dome\\stf-disconnect.js'[39m ]
}

解决办法:安装swagger-client

E:\dome>npm install swagger-client
npm WARN EBADENGINE Unsupported engine {
npm WARN EBADENGINE   package: 'formdata-node@4.3.1',
npm WARN EBADENGINE   required: { node: '>= 12.20' },
npm WARN EBADENGINE   current: { node: 'v12.14.1', npm: '8.0.0' }
npm WARN EBADENGINE }
npm WARN deprecated querystring@0.2.0: The querystring API is considered Legacy. new code should use the URLSearchParams API instead.

added 29 packages, and audited 30 packages in 5m

8 packages are looking for funding
  run `npm fund` for details

found 0 vulnerabilities
npm notice
npm notice New minor version of npm available! 8.0.0 -> 8.1.4
npm notice Changelog: https://github.com/npm/cli/releases/tag/v8.1.4
npm notice Run npm install -g npm@8.1.4 to update!
npm notice

E:\dome>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值