--- name: linux-ssh-operator description: 通过 SSH 连接并操作 Linux 服务器:执行远程命令、查看日志、管理 systemd 服务、传输文件(scp/rsync/tar/sftp)、排障。用户提到 ssh/scp/rsync、远程服务器 IP:端口、systemctl/journalctl、部署到服务器、在服务器上运行命令、远程拷贝文件 等场景时使用。 --- # Linux SSH Operator ## Goal Use SSH for safe, repeatable Linux server operations. ## Fast Decision 1. Remote command or service check -> `scripts/ssh_run.sh` 2. Single file copy -> `scripts/ssh_copy.sh --method scp` 3. Directory sync or exclusions -> `scripts/ssh_copy.sh --method rsync -r` 4. Many small files -> `scripts/ssh_copy.sh --method tar` 5. If sudo may prompt -> add `--tty --sudo` Prefer explicit method selection when the shape is already known. It is faster and avoids bad auto guesses. ## Before Acting 1. Confirm `host`, `port`, `user`, and auth method. 2. Prefer SSH keys and `~/.ssh/config` aliases. 3. Start with read-only checks, then change, then verify. 4. For first-connect automation, prefer `--accept-new` only when appropriate. 5. On flaky links, set `--connect-timeout` so failed attempts return fast. ## Command Runs Use `ssh_run.sh` for non-interactive commands: ```bash ssh_run.sh my-server -- uname -a ssh_run.sh --tty --sudo my-server -- systemctl restart nginx ssh_run.sh --sudo-non-interactive my-server -- systemctl status nginx --no-pager ``` Notes: - `--sudo` is for commands that may prompt. - `--sudo-non-interactive` is only for passwordless sudo paths. ## File Transfer Use `ssh_copy.sh` for transfers: ```bash ssh_copy.sh --method scp push my-server ./local.txt /tmp/local.txt ssh_copy.sh --method rsync -r push my-server ./dir /tmp/dir ssh_copy.sh --method tar push my-server ./many-small-files/ /tmp/ ``` Rules: - `--tar` is a packaging mode, not something to mix with `--method rsync/scp/sftp`. - Use `--exclude` only with `rsync`. - Use `--delete` only when you really want destination cleanup. ## Common Ops - Disk: `df -h`, `du -sh /path/* | sort -h` - Memory/CPU: `free -h`, `top`, `ps aux --sort=-%mem | head` - Logs: `journalctl -u SERVICE -n 200 --no-pager` - Services: `systemctl status|restart|stop SERVICE` - Networking: `ss -lntp`, `ip a`, `ip r` ## Safety - Never store passwords in repo files or chat logs. - Avoid `StrictHostKeyChecking=no`. - For destructive commands, ask for explicit confirmation and show the exact command first. ## References - SSH security + troubleshooting: `references/ssh-playbook.md` ## Scripts - `scripts/ssh_run.sh`: remote command execution with consistent options. - `scripts/ssh_copy.sh`: file transfer via scp/rsync/tar/sftp with consistent options.