Debian SSH自动化运维实战指南
一 基础准备与免密登录
sudo apt-get update && sudo apt-get install -y openssh-client openssh-serversudo systemctl enable --now sshssh-keygen -t ed25519 -C "ops@debian" 或 ssh-keygen -t rsa -b 4096 -C "ops@debian"ssh-copy-id user@hostssh user@host 'mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys' < ~/.ssh/id_ed25519.pubchmod 700 ~/.ssh && chmod 600 ~/.ssh/authorized_keyschown -R user:user ~user/.sshssh user@host,看到 ECDSA/RSA 指纹提示输入 yes 保存echo "UseDNS no" | sudo tee -a /etc/ssh/sshd_config && sudo systemctl restart ssh二 批量执行与文件分发
sudo apt-get install -y parallelcat > hosts.txt <<EOF 192.0.2.11 192.0.2.12 192.0.2.13 EOFparallel -i -j 10 ssh {} 'sudo apt-get update && sudo apt-get -y upgrade' :::: hosts.txtscp deploy.sh user@host:/tmp/ && ssh user@host 'chmod +x /tmp/deploy.sh && sudo /tmp/deploy.sh'rsync -avz -e ssh /opt/app/ user@host:/opt/app/~/.ssh/config 示例:Host web*.example.com
User deploy
IdentityFile ~/.ssh/id_ed25519_web
Port 22
ForwardAgent yes
Host bastion
HostName bastion.example.com
User jump
IdentityFile ~/.ssh/id_ed25519_bastion
Host internal-*.example.com
User app
ProxyJump bastion
ssh web01.example.com、rsync -avz -e ssh internal-01.example.com:/data/ ./data/chmod 600 ~/.ssh/id_*StrictHostKeyChecking=no、UserKnownHostsFile=/dev/null(CI/脚本中临时使用)三 进阶场景 隧道与交互自动化
ssh -L 127.0.0.1:3306:db.internal:3306 user@gatewayssh -R 8080:localhost:80 user@gatewayssh -D 1080 user@gatewayssh -J bastion user@internal~/.ssh/config 的 ProxyJump#!/usr/bin/expect -f
set timeout 30
set user [lindex $argv 0]
set host [lindex $argv 1]
spawn ssh $user@$host
expect {
"password:" { send "YourPass\r"; exp_continue }
"$ " { send "sudo systemctl restart nginx\r" }
timeout { puts "timeout"; exit 1 }
}
expect "$ "
send "exit\r"
sudo apt-get install -y expect四 安全加固与合规审计
/etc/ssh/sshd_config:PermitRootLogin no
PasswordAuthentication no
PubkeyAuthentication yes
KbdInteractiveAuthentication no
X11Forwarding no
AllowUsers deploy admin
Ciphers aes256-gcm@openssh.com,aes128-gcm@openssh.com,aes256-ctr,aes128-ctr
MACs hmac-sha2-512,hmac-sha2-256
sudo systemctl restart sshcd /etc/ssh
chmod 600 ssh_host_*
chmod 644 *.pub
sudo journalctl -f -u sshgrep "Accepted" /var/log/auth.loggrep "Failed\|authentication failure" /var/log/auth.log/var/log/auth.log {
daily
rotate 7
compress
missingok
notifempty
create 640 root adm
}
五 规模化自动化工具 Ansible
安装:sudo apt-get install -y ansible
清单:`cat > inventory.ini <<EOF [web] 192.0.2.11 192.0.2.12
[db] 192.0.2.13 EOF`
Ad-Hoc:ansible web -i inventory.ini -m apt -a "name=nginx state=latest" --become
Playbook(示例):
- hosts: web
become: yes
tasks:
- name: Install Nginx
apt: name=nginx state=latest
- name: Ensure service running
service: name=nginx state=started enabled=yes
执行:ansible-playbook -i inventory.ini web.yml