Ansible Playbook自动配置SSH
---
- name: 16_PRO_SSHConfig.yml
hosts: all
gather_facts: yes
vars:
allow_root: True
allow_password: False
ssh_port: 34522
ssh_change_port: True
tasks:
- name: Delete GSS
lineinfile: dest=/etc/ssh/sshd_config state=absent regexp=".*GSS.*"
- name: Set UseDNS no
lineinfile: dest=/etc/ssh/sshd_config regexp=".*UseDNS.*" line="UseDNS no"
- name: if permit root login via publickey
lineinfile: dest=/etc/ssh/sshd_config regexp="^PermitRootLogin " insertafter="^#PermitRootLogin " line="PermitRootLogin without-password"
when: allow_root == 'True'
- name: if not allow rootlogin
lineinfile: dest=/etc/ssh/sshd_config regexp="^PermitRootLogin " insertafter="^#PermitRootLogin " line="PermitRootLogin no"
when: allow_root == 'False'
- lineinfile: dest=/etc/ssh/sshd_config regexp="^PasswordAuthentication" line="PasswordAuthentication yes"
when: allow_password == 'True'
- lineinfile: dest=/etc/ssh/sshd_config regexp="^PasswordAuthentication " line="PasswordAuthentication no"
when: allow_password == 'False'
- lineinfile: dest=/etc/ssh/sshd_config regexp="^RSAAuthentication " line="RSAAuthentication yes"
when: allow_password == 'False'
- lineinfile: dest=/etc/ssh/sshd_config regexp="^PubkeyAuthentication " line="PubkeyAuthentication yes"
when: allow_password == 'False'
- lineinfile: dest=/etc/ssh/sshd_config regexp="^AuthorizedKeysFile " line="AuthorizedKeysFile .ssh/authorized_keys"
when: allow_password == 'False'
- lineinfile: dest=/etc/ssh/sshd_config regexp=".*Port.*" line="Port {{ssh_port}}"
when: ssh_change_port == 'True'
- name: restart sshd service
service: name=sshd state=restarted
「长期更新」OpenSSH Client Config Tips
~/.ssh/config 配置文件详解
# 全局配置
Host *
# 启用会话重用("持久化连接")功能
# 会话重用意味着其他人也能登录你正在连接的服务器, 除非用户隔离
ControlMaster auto
# 会话存放路径 注意存放路径, 不推荐存放到/tmp目录
# 如果链路端开, 会话已经无效, 需要kill掉ssh进程或删掉会话文件
ControlPath ~/.ssh/sockets/%r@%h-%p
# 会话有效时间 单位分钟
ControlPersist 600
# 允许转发秘钥到远端服务器, 再次跳转其他服务器不用秘钥
ForwardAgent yes
# 转发X11协议
ForwardX11 no
# 转发X11协议到信任服务器
ForwardX11Trusted yes
# SSH 2.0协议
Protocol 2
# 发送心跳包间隔 单位秒
ServerAliveInterval 60
# 服务器断开心跳数量
# 也就是"持久化连接"会在网络断开30*60秒之后自动断开
ServerAliveCountMax 30
# 远端服务器缩写 直接ssh host1连接
Host host1
# 使用加密算法 需要配合远端sshd_config
Ciphers aes256-gcm@openssh.com,chacha20-poly1305@openssh.com
# 服务器IP或域名
HostName x.x.x.x
# 允许转发秘钥到远端服务器, 二次跳转免登陆. 远端使用ssh-add -L查看
ForwardAgent yes
# 登录的用户名
User root
# 服务器SSH端口
port 56722
# 使用跳板机登录 跳板机配置秘钥免登陆
ProxyJump 192.168.1.100
# 使用跳板机NC登录,比ProxyJump麻烦些
ProxyCommand ssh 192.168.1.100 nc %h %p
# 映射本地80端口到远端60080端口
RemoteForward 127.0.0.1:60080 127.0.0.1:80
# 映射远端443端口到本地10443端口
LocalForward 127.0.0.1:10443 127.0.0.1:443
# 认证秘钥
IdentityFile /path/to/your/identify