ssh连接远程主机免密登入

核心思想:

1.本地主机生成公钥私钥,私钥自己存着,公钥传到远程主机.ssh文件夹下authorized_keys文件(默认是这个,用追加的方式)

2.本地连接远程主机,公私钥对上就可以免密登入了.


3.authorized_keys的权限要是600

步骤

主机:

1.生成公钥和私钥文件id_rsa和id_rsa.pub (敲三下回车即可)。

  1. [root@bogon ~]# ssh-keygen -t rsa  
  2. Generating public/private rsa key pair.  
  3. Enter file in which to save the key (/root/.ssh/id_rsa):  
  4. Enter passphrase (empty for no passphrase):  
  5. Enter same passphrase again:  
  6. Your identification has been saved in /root/.ssh/id_rsa.  
  7. Your public key has been saved in /root/.ssh/id_rsa.pub.  
  8. The key fingerprint is:  
  9. 67:da:0d:79:e0:d6:2b:cd:7d:22:af:51:7e:9c:75:fe root@bogon  
  10. The key's randomart image is:  
  11. +--[ RSA 2048]----+  
  12. | |  
  13. | |  
  14. | . |  
  15. | . + |  
  16. | S B o . o|  
  17. | * * = o+|  
  18. | . o B +.=|  
  19. | . + +.|  
  20. | ... E|  
  21. +-----------------+ 

2.远程主机上创建~/.ssh目录,权限为700,把~/.ssh/id_rsa.pub从本地追加到远程主机上的~/.ssh/authorized_keys

 authorized_keys的权限要是600

ssh 登录一段时间后断开的解决方案

方法1 和2 就够用了

Method 1:
修改 / etc/ssh/sshd_config 配置文件,设置 ClientAliveCountMax 值大一点,单位是分钟。然后重启 ssh 服务使生效:service sshd reload 


Method 2:
找到所在用户的. ssh 目录, 如 root 用户该目录在:/root/.ssh/
在该目录创建 config 文件 vi /root/.ssh/config
加入下面一句:ServerAliveInterval 60
保存退出,重新开启 root 用户的 shell,则再 ssh 远程服务器的时候,不会因为长时间操作断开。应该是加入这句之后,ssh 客户端会每隔一段时间自动与 ssh 服务器通信一次,所以长时间操作不会断开。


Method 3:
修改 / etc/profile 配置文件
# vi /etc/profile
增加:TMOUT=1800
这样 30 分钟没操作就自动 LOGOUT


Method 4:
利用 expect 模拟键盘动作,在闲置时间之内模拟地给个键盘响应, 将下列代码保存为 xxx,然后用 expect 执行
#!/usr/bin/expect  
set timeout 60  
spawn ssh user@host   
      interact {          
            timeout 300 {send "x20"}  
      } 
expect xxx
接着按提示输入密码就可以了,这样每隔 300 秒就会自动打一个空格 (x20),具体的时间间隔可以根据具体情况设置。


Method 5:
Windows 下 ssh 工具的设置:
secureCRT:选项 --- 终端 --- 反空闲 中设置每隔多少秒发送一个字符串,或者是 NO-OP 协议包
putty:putty -> Connection -> Seconds between keepalives (0 to turn off), 默认为 0, 改为 300.

原文地址:https://www.cnblogs.com/dahu-daqing/p/6865853.html