Provides guidance for Huawei Cloud KooCLI command-line tool operations. Covers KooCLI installation, IAM authentication configuration, access credential confi...
文档
huawei-cloud-ecs-passwordless-login
试用Configure passwordless SSH login to Huawei Cloud ECS instances using COC (Cloud Operations Center). Automates IAM agency authorization, SSH key pair generati...
它能做什么
Configure passwordless SSH login to Huawei Cloud ECS instances using COC (Cloud Operations Center). Automates IAM agency authorization, SSH key pair generation, COC script deployment to the target ECS, SSH connection testing, and automatic security cleanup after 60 seconds (removing keys from both local and remote). 触发词: 免密登录, COC SSH, ECS key login, SSH key deployment, passwordless SSH
技能文档
Huawei Cloud ECS Passwordless Login
Overview
Configure passwordless SSH login to Huawei Cloud ECS using COC (Cloud Operations Center) with a 7-step automated workflow:
- IAM Authorization — Create the
ServiceAgencyForCOCagency for COC service and bind 4 required roles; skip entirely if agency already exists (HTTP 409) - Key Generation — Generate a local RSA 4096-bit SSH key pair
- Script Creation — Create or reuse a parameterized COC script that deploys the public key
- Script Execution — Execute the script on the target ECS via COC
- SSH Test — Verify passwordless SSH connection to the target ECS
- Persistent Connection — Establish SSH ControlMaster so the agent can continue SSH access after keys are cleaned up
- Security Cleanup — After 60 seconds, automatically remove keys from remote
authorized_keys, delete the local key pair, and clean up the COC script
Tool chain: hcloud CLI (KooCLI) + local SSH tools. Deployment is handled through COC script execution only.
Prerequisites
- hcloud CLI (KooCLI) installed and authenticated with AK/SK — see CLI Installation Guide
- IAM user with sufficient permissions to create agencies and operate COC — see IAM Policies
- SSH client and
ssh-keygenavailable locally - Target ECS instance ID or elastic IP (the ECS must be in
ACTIVEstate)
Security
- Never expose private key content in conversation or output
- Never log or persist private keys beyond the 60s window
- Cleanup is mandatory — if SSH test succeeds, keys MUST be removed within
cleanup_delayseconds - Removing the public key from
authorized_keysonly blocks new SSH connections; existing sessions are NOT interrupted - If SSH test fails, preserve keys for debugging and do NOT trigger cleanup
Workflow
Execute the numbered steps below in order. See Core Commands section for the exact command syntax to use at each step.
1. IAM Authorization
One-time per-account setup. Authorize COC to operate on your ECS instances.
- Get domain ID — Call
KeystoneListAuthDomainsand extract theid. - Create agency — Call
CreateAgencywith nameServiceAgencyForCOCand trust domainop_svc_coc.- HTTP 200 — New agency created. Record
agency.id. Proceed to step 3. - HTTP 409 — Agency already exists. Skip the entire IAM phase (steps 3–4) and jump to Step 2 (Key Generation).
- HTTP 200 — New agency created. Record
- Find role IDs — Call
KeystoneListPermissionsfor each of the 4 roles:IAM ReadOnlyAccess,RMS ReadOnlyAccess,DCS UserAccess,COCServiceAgencyPolicy. If any role is not found, stop — the account may lack access. - Bind roles — Call
AssociateAgencyWithAllProjectsPermissionfor each of the 4 role IDs.- HTTP 200 — Bound successfully.
- HTTP 409 — Already bound, skip and continue.
2. Generate Local SSH Key Pair
Generate an RSA 4096-bit key pair. The comment coc-temp-key is the cleanup marker.
Record the key fingerprint. Never display the private key content.
3. Create or Reuse COC Script
- Check existing — Call
ListScriptswith--name_like="coc_ssh_key_setup". If found, recordscript_uuidand skip step 2. - Create new — Write a JSON file with the script content, then call
CreateScript --cli-jsonInput=. Use--cli-jsonInput(not inline--content) to avoid shell quoting issues with special characters in the script body. Record the returnedscript_uuid.
4. Execute Script on Target ECS
-
Resolve instance — If only an ECS IP was provided, call
NovaListServersDetailsto find the instance ID. -
Execute — Write a JSON file with the public key embedded, then call
ExecuteScript --cli-jsonInput=. Same pattern as Step 3 to avoid shell quoting issues with the public key content. Recordexecute_uuid. -
Poll — Call
GetScriptJobInfoevery 5 seconds until terminal status. Note: the API redactsparam_valuein the response for security; verify deployment by testing SSH in Step 5.Status Action RUNNINGWait 5s, poll again SUCCESSProceed to Step 5 FAILED/TIMEOUTReport error, stop Max 2 minutes (24 polls).
5. Test SSH Connection
Test passwordless SSH using the generated key.
SSH_OKreturned — Proceed to Step 6.- Connection fails — Report error. Stop here. Preserve keys for debugging. Do NOT trigger cleanup.
6. Establish Persistent SSH Connection
Set up SSH ControlMaster so the agent can continue accessing the ECS after keys are removed in Step 7.
- Append SSH config — Add a
Hostblock to~/.ssh/configwithControlMaster auto,ControlPath /tmp/coc_ssh_%r@%h:%p, andControlPersist. - Start master — Run
ssh -N -f -ito background a persistent master connection. - Verify — Run
ssh "echo SSH_MUX_OK"without a key file. IfSSH_MUX_OKis returned, multiplexing works.
SSH config and socket do not need cleanup — config entries are harmless, sockets auto-expire with ControlPersist.
7. Security Cleanup
Mandatory. Start a background timer that fires after cleanup_delay seconds (default: 60):
- Remove
coc-temp-keyline from remote/root/.ssh/authorized_keys - Delete the COC script via
DeleteScript - Delete local key files from
/
After cleanup, the agent can still connect via ssh — ControlMaster bypasses key authentication.
Fallback: If remote key removal via SSH fails, create and execute a one-shot COC script:
#!/bin/bash
set -e
sed -i '/coc-temp-key/d' /root/.ssh/authorized_keys
echo "KEY_REMOVED"
Create and execute this script with no parameters. Delete it immediately after execution completes.
Core Commands
Placeholder values (see Parameters for per-OS resolution):
| Placeholder | Linux / macOS | Windows |
|---|---|---|
| `` | hcloud | hcloud |
| `` | /tmp | $env:TEMP |
# 1. Check/setup COC IAM authorization
IAM KeystoneListAuthDomains/v3
IAM CreateAgency/v3 \
--agency.domain_id="" \
--agency.name="ServiceAgencyForCOC" \
--agency.trust_domain_name="op_svc_coc" \
--agency.duration="FOREVER"
IAM KeystoneListPermissions/v3 \
--display_name=""
IAM AssociateAgencyWithAllProjectsPermission/v3 \
--agency_id="" --domain_id="" --role_id=""
# 2. Generate local SSH key pair
ssh-keygen -t rsa -b 4096 -f /coc_ssh_key -N "" -C "coc-temp-key"
ssh-keygen -lf /coc_ssh_key # record fingerprint
# 3. Check for existing COC script
COC ListScripts --limit=100 --name_like="coc_ssh_key_setup"
# If not found, create a JSON file and use --cli-jsonInput:
cat > /coc_create.json << 'JSONEOF'
{
"body": {
"name": "coc_ssh_key_setup",
"type": "SHELL",
"description": "Deploy SSH public key for passwordless login",
"content": "#!/bin/bash\nset -e\nmkdir -p /root/.ssh && chmod 700 /root/.ssh\necho $PUBLIC_KEY >> /root/.ssh/authorized_keys\nchmod 600 /root/.ssh/authorized_keys\necho KEY_DEPLOYED_SUCCESSFULLY",
"properties": {
"risk_level": "LOW",
"version": "1.0.0"
},
"script_params": [
{
"param_name": "PUBLIC_KEY",
"param_description": "SSH public key to deploy",
"param_value": "",
"sensitive": false
}
]
}
}
JSONEOF
COC CreateScript --cli-jsonInput=/coc_create.json
# 4. Execute script on target ECS, replace with actual value
cat > /coc_execute.json << 'JSONEOF'
{
"path": {"script_uuid": ""},
"body": {
"execute_batches": [{
"batch_index": 1,
"rotation_strategy": "CONTINUE",
"target_instances": [{
"region_id": "",
"resource_id": ""
}]
}],
"execute_param": {
"execute_user": "root",
"success_rate": 100,
"timeout": 120,
"script_params": [{
"param_name": "PUBLIC_KEY",
"param_value": pubkey
}]
}
}
}
JSONEOF
COC ExecuteScript --cli-jsonInput=/coc_execute.json
# Poll execution status (note: GetScriptJobInfo redacts param_value for security; check SSH directly to verify)
COC GetScriptJobInfo --execute_uuid=
# 5. Test SSH connection
ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null \
-o ConnectTimeout=10 -i /coc_ssh_key root@ "echo SSH_OK"
# 6. Establish persistent SSH connection (ControlMaster multiplexing)
cat >> ~/.ssh/config << 'EOF'
Host
User
ControlMaster auto
ControlPath /tmp/coc_ssh_%r@%h:%p
ControlPersist
StrictHostKeyChecking no
UserKnownHostsFile /dev/null
EOF
ssh -N -f -i /coc_ssh_key && echo "MASTER_CONNECTED"
ssh "echo SSH_MUX_OK" # verify multiplexing works
# 7. Security cleanup (background, survives parent shell exit via nohup + disown)
nohup bash -c '
sleep
# Remove public key from remote
ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null \
-o ConnectTimeout=5 -i /coc_ssh_key root@ \
"sed -i \"/coc-temp-key/d\" /root/.ssh/authorized_keys" 2>/dev/null || true
# Delete COC script
COC DeleteScript --script_uuid="" 2>/dev/null || true
# Delete local keys
rm -f /coc_ssh_key /coc_ssh_key.pub
echo "COC SSH keys cleaned up. Existing SSH sessions remain unaffected."
' > /coc_cleanup.log 2>&1 &
disown
echo "Cleanup scheduled in s (PID: $!, log: /coc_cleanup.log)"
Parameters
| Parameter | Required | Default | Constraint |
|---|---|---|---|
ecs_instance_id | Conditional | None | ECS instance UUID; required if ecs_ip is not provided |
ecs_ip | Conditional | None | ECS elastic IPv4 address; required if ecs_instance_id is not provided |
region | Yes | cn-north-4 | Region where the ECS and COC reside. Must match the ECS's region |
ssh_user | No | root | SSH username on the target ECS |
cleanup_delay | No | 60 | Seconds to wait before automatic key cleanup (min 10, max 300) |
persist_timeout | No | 3600 | Seconds to keep ControlMaster alive after all sessions close (min 60, max 86400) |
Output Format
At each step, report progress in a structured manner:
| Step | Output |
|---|---|
| 1. Authorization | Agency status (created / already exists), roles bound count (4/4) |
| 2. Key Generation | Key fingerprint, key file paths |
| 3. Script | Script name, action (created / reused), script_uuid |
| 4. Execution | execute_uuid, polling status, final result |
| 5. SSH Test | Connection result, SSH command string |
| 6. Persistent Connection | ControlMaster status, multiplex verification, SSH alias `` |
| 7. Cleanup | Timer PID, countdown notification, cleanup confirmation |
Verification
Verify the workflow step by step:
- Authorization —
CreateAgencyreturns 200 → all 4 roles bound (200 or 409 each); returns 409 → entire IAM phase skipped (agency already authorized from prior run) - Key Generation — Key pair files exist in
/with correct permissions - Script —
coc_ssh_key_setupexists withPUBLIC_KEYparameter and validscript_uuid - Execution —
GetScriptJobInfoshowsSUCCESSwithin 2 minutes - SSH Test —
sshconnects without password prompt; test command returnsSSH_OK - Persistent Connection — SSH config appended,
ssh -N -fstarts master,ssh "echo SSH_MUX_OK"succeeds - Cleanup — Remote key removed, COC script deleted, local key files deleted;
sshstill connects via ControlMaster
See Verification Method and Acceptance Criteria for detailed checklists.
Best Practices
- IAM authorization is a one-time per-account setup — if
CreateAgencyreturns 409, the entire IAM phase (agency + role binding) is already complete and should be skipped entirely - Use the
--name_likefilter inListScriptsto avoid creating duplicate scripts - Always test the SSH connection before starting the cleanup timer
- If SSH fails, keep keys on disk for debugging — do NOT clean up automatically
- The cleanup timer runs in a background subshell; killing the process before cleanup completes leaves keys in place
- After key cleanup, the agent can still SSH via
ssh— ControlMaster bypasses key authentication - Use
-o UserKnownHostsFile=/dev/nullto avoid polluting the localknown_hostsfile - The SSH key comment
coc-temp-keyis the marker used bysedfor cleanup — do not change it - COC script execution is limited to 200 hosts per execution and 10 hosts per batch
- SSH config entries persist after cleanup as harmless dead entries; they can be removed later if desired
Reference Documents
| Document | Description |
|---|---|
| CLI Installation Guide | Install and configure hcloud CLI and SSH tools |
| IAM Policies | Required IAM permissions, agency setup, and error handling |
| Verification Method | Step-by-step verification per workflow step |
| Acceptance Criteria | Full end-to-end acceptance checklist |
Notes
- All
hcloudcommands use the default region from the CLI profile (no--cli-region). Ensure your profile is configured with the correct region where your ECS and COC reside. - The COC script is created via
--cli-jsonInputwith a JSON file, not inline--content="..."— inline quoting causes parsing errors with shell special characters in the script body - The COC script is parameterized with
PUBLIC_KEY— it persists across invocations and can deploy different keys - If the COC script already exists from a previous run, it is reused rather than recreated
- The cleanup uses
nohup bash -c '...' &+disownto survive parent shell exit; output is logged to/coc_cleanup.logfor verification. The old(sleep N && ...) &pattern loses stdout when the parent shell exits in non-interactive mode - Private keys are stored in `` and should never be committed to VCS
- The
sedcleanup targetcoc-temp-keymatches the key comment set duringssh-keygen - After cleanup, use
ssh(no key file needed) — ControlMaster socket handles authentication - The SSH config entry is appended to
~/.ssh/configas a simpleHostblock - ControlMaster socket is stored at
/tmp/coc_ssh_%r@%h:%pand auto-cleaned when the master process exits
相关技能
Based on Huawei Cloud COC (Cloud Operations Center) APIs for script management and remote execution. Supports creating custom scripts (Shell, Python, Bat) and batch execution on target host instances via UniAgent. Applicable to cloud operations automation and batch script deployment scenarios. Trigger keywords: L-instance, COC script, script management, script execution, cloud operations, custom script, batch execution; COC, script management, script execution, cloud operations (中文触发词:L实例执行脚本).
Queries Huawei Cloud ECS (Elastic Cloud Server) resources in read-only mode. Covers ECS instances, flavors, keypairs, quotas, server groups, block devices, NICs, VNC console, launch templates, recycle bin, scheduled events, and tags. No write operations. Use this skill when the user needs to query ECS instance details, list flavors, check server status, view block devices, or inspect ECS resource attributes. Triggers include: 查询ECS, ECS实例查询, 云服务器查询, 弹性云服务器, ECS规格, ECS配额, 云服务器列表, ECS详情, query ECS, list ECS servers, show server details, ECS flavors, ECS quotas, ECS keypairs, server groups, block devices, ECS inventory, cloud server list, ecs list, ecs query, ecs show.
Purchase Huawei Cloud X Instance server + one-click deploy SQLBot intelligent query application. Tech stack: Python 3.8+, Huawei Cloud SDK, COC (Cloud Operat...
SSH 远程连接华为云昇腾设备,支持 NPU 监控、磁盘与容器运维,凭据仅驻留内存。
通过华为云命令行工具 hcloud 调用云监控服务 CES,查询 ECS 实例的 CPU、内存、磁盘与网络指标。
huaweicloud-skills-team 的更多技能
浏览全部技能用自然语言控制华为昇腾 NPU,本地或 SSH 远程执行 npu-smi 命令。
在华为云昇腾 910B DevServer 上按单机或双机(16 卡)拓扑部署并测试 LLM、VL、Embedding、Rerank 模型。
面向华为云资源的只读查询能力,用于资源清点、核对与参数发现。
通过本地 Python SDK 只读查询华为云 IAM 资源(用户、用户组、策略、委托、AK/SK、MFA、安全设置)。
在华为云 Flexus L 实例上一键部署 OpenClaw AI Agent 平台,并完成模型与通道配置。
在华为云 Flexus L 实例上一键部署 Hermes AI Agent 平台,并完成大模型与机器人通道配置。