Server-A免密码登录Server-B

1.Server-A生成密钥文件

[root@instance-1 ~]# ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa): 输入密钥文件(可回车跳过)
Created directory '/root/.ssh'.
Enter passphrase (empty for no passphrase): 输入密码(可回车跳过)
Enter same passphrase again: 再次输入密码(可回车跳过)
Your identification has been saved in /root/.ssh/id_rsa. 密钥文件路径
Your public key has been saved in /root/.ssh/id_rsa.pub. 公钥文件路径
The key fingerprint is:
SHA256:NWnIvWKQQJaAJF3ZMgso2rqSrndxLJyvwdHlOVMgKgg root@instance-1
The key's randomart image is:
+---[RSA 2048]----+
|E=.+=+. .        |
|*.o.=o.+ + .     |
|+....+o + B      |
|. .... + = o     |
| . ..o. S .      |
|.  .=.o. +       |
| o  o=           |
|+ . ...          |
|=o ...           |
+----[SHA256]-----+

2.将秘钥写到Server-B的 ~/.ssh/authorized_keys文件中

  • 方式1:ssh-copy-id 命令
    ssh-copy-id -i /root/.ssh/id_rsa.pub 用户名@主机IP/域名
  • 方式2:
    cat ~/.ssh/id_rsa.pub | ssh 用户名@主机IP/域名 “mkdir ~/.ssh; cat >> ~/.ssh/authorized_keys”

修改配置

vi /etc/ssh/ssh_config
PasswordAuthentication no #禁用密码验证
PubkeyAuthentication yes #启用密钥验证

指定用户或IP登陆

vi /etc/ssh/ssh_config
AllowUsers root #允许用户
AllowUsers *@192.168.68.1 #允许用户及IP
AllowUsers *@192.168.68.1 *@127.0.0.1 #一行允许多个
AllowUsers *@* #允许所有
AllowUsers root@192.168.68.0/24 #允许IP段
AllowUsers root@host #允许主机名

SSH隧道介绍

SSH: Port Forwarding
1.正向隧道-隧道映射远程端口到监听本地端口,为普通活动提供安全连接
ssh -qTfnN -L localport:host:hostport -l user remote_ip
ssh -N -L 3307:localhost:3306 root@1.1.1.1 -i /Volumes/LocalDisk/home
2.反向隧道-隧道映射本地端口到监听远程端口,突破防火墙提供服务
ssh -qTfnN -R port:host:hostport -l user remote_ip

参数说明
-q Quiet mode. 安静模式,忽略一切对话和错误提示。
-T Disable pseudo-tty allocation. 不占用 shell 了。
-f Requests ssh to go to background just before command execution. 后台运行,并推荐加上 -n 参数。
-n Redirects stdin from /dev/null (actually, prevents reading from stdin). -f 推荐的,不加这条参数应该也行。
-N Do not execute a remote command. 不执行远程命令,专为端口转发度身打造。
例子开启服务器的80端口到本地主机2001端口的隧道
ssh -N -L 2001:localhost:80 服务器IP

SSH连接后运行

1.创建sshrc,并将需要运行的命令写入
vi /etc/ssh/sshrc
例子:ssh登陆后发送消息到钉钉

#!/bin/bash
#获取登录者的用户名
user=$USER
#获取登录者的IP地址
ip=${SSH_CLIENT%% *}
#获取登录的时间
time=$(date "+%Y-%m-%d %H:%M:%S")
#服务器的IP地址
server='47.114.43.70'
#发送预警,当然你也可以不发送,直接记录下日志即可
CURL="/usr/bin/curl"
body="###  远程登录服务器\n\n登陆IP:$ip\n\n服务器:$server\n\n用户:$user\n\n$time"
${CURL}  'https://oapi.dingtalk.com/robot/send?access_token=8ab4ec29615e4e90a4f60464957ea0a6b68786bd6d11dd98b9c4eac2eeeb54f3' \
   -H 'Content-Type: application/json' \
   -d """
 {
     \"msgtype\": \"markdown\",
     \"markdown\": {
         \"title\":\"服务器预警\",
         \"text\": \"${body}\"
     },
    \"at\": {
        \"atMobiles\": [
        ], 
        \"isAtAll\": false
    }
 }""" >/dev/null 2>&1