本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
設定遠端裝置並使用 IoT 代理程式
IoT 代理程式用於接收包含用戶端存取權杖MQTT的訊息,並在遠端裝置上啟動本機代理。如果您想要安全通道使用 傳遞用戶端存取權杖,則必須在遠端裝置上安裝和執行 IoT 代理程式MQTT。IoT 代理程式必須訂閱下列預留的 IoT MQTT主題:
注意
如果您想要透過訂閱預留MQTT主題以外的方法,將目的地用戶端存取權杖傳遞給遠端裝置,您可能需要目的地用戶端存取權杖 (CAT) 接聽程式和本機代理。CAT 接聽程式必須使用您選擇的用戶端存取權杖交付機制,並能夠在目的地模式下啟動本機代理。
IoT Agent Snippet
IoT 代理程式必須訂閱下列預留的 IoT MQTT主題,才能接收MQTT訊息並啟動本機代理:
$aws/things/
thing-name
/tunnels/notify
其中 thing-name
是與遠端裝置相關聯的 AWS IoT 物件名稱。
以下是MQTT訊息承載的範例:
{ "clientAccessToken": "
destination-client-access-token
", "clientMode": "destination", "region": "aws-region
", "services": ["destination-service
"] }
收到MQTT訊息後,IoT 代理程式必須在具有適當參數的遠端裝置上啟動本機代理。
下列 Java 程式碼示範如何使用 AWS IoT 裝置SDK
// Find the IoT device endpoint for your AWS 帳戶 final String endpoint = iotClient.describeEndpoint(new DescribeEndpointRequest().withEndpointType("iot:Data-ATS")).getEndpointAddress(); // Instantiate the IoT Agent with your AWS credentials final String thingName = "RemoteDeviceA"; final String tunnelNotificationTopic = String.format("$aws/things/%s/tunnels/notify", thingName); final AWSIotMqttClient mqttClient = new AWSIotMqttClient(endpoint, thingName, "your_aws_access_key", "your_aws_secret_key"); try { mqttClient.connect(); final TunnelNotificationListener listener = new TunnelNotificationListener(tunnelNotificationTopic); mqttClient.subscribe(listener, true); } finally { mqttClient.disconnect(); } private static class TunnelNotificationListener extends AWSIotTopic { public TunnelNotificationListener(String topic) { super(topic); } @Override public void onMessage(AWSIotMessage message) { try { // Deserialize the MQTT message final JSONObject json = new JSONObject(message.getStringPayload()); final String accessToken = json.getString("clientAccessToken"); final String region = json.getString("region"); final String clientMode = json.getString("clientMode"); if (!clientMode.equals("destination")) { throw new RuntimeException("Client mode " + clientMode + " in the MQTT message is not expected"); } final JSONArray servicesArray = json.getJSONArray("services"); if (servicesArray.length() > 1) { throw new RuntimeException("Services in the MQTT message has more than 1 service"); } final String service = servicesArray.get(0).toString(); if (!service.equals("SSH")) { throw new RuntimeException("Service " + service + " is not supported"); } // Start the destination local proxy in a separate process to connect to the SSH Daemon listening port 22 final ProcessBuilder pb = new ProcessBuilder("localproxy", "-t", accessToken, "-r", region, "-d", "localhost:22"); pb.start(); } catch (Exception e) { log.error("Failed to start the local proxy", e); } } }