跳到主要内容
方的代码随记
返回

云服务器 SSH 配置与自动登录

更新于:

保持 SSH 长连接

云服务器上的 SSH 会话一段时间无操作就会断开,修改 /etc/ssh/sshd_config:

#ClientAliveInterval 0
#ClientAliveCountMax 3

# 客户端每隔多少秒向服务发送一个心跳数据
ClientAliveInterval 30
# 客户端多少秒没有响应,服务器自动断掉连接
ClientAliveCountMax 86400

重启 sshd 生效:

service sshd restart

用 expect 脚本自动登录(密码方式)

保存为 ~/.ssh/local-centos,内容如下:

#!/usr/bin/expect -f

# 文件一定要以 #!/usr/bin/expect -f 开头
# 设置 ip 地址、用户名、端口号、密码等
set host xxx.xxx.xxx.xxx
set user root
set port 22
set password xxxxx
set timeout -1

# 一系列自动化登录的命令
spawn ssh $user@$host
expect "*password:*"
send "$password\r"
interact
expect eof

配置到 iTerm2:Profiles → 常规 → 命令 填 expect ~/.ssh/local-centos。

明文保存密码有安全风险,仅在受控环境使用;能配密钥登录时优先用密钥。

密钥登录报权限过宽

Permissions 0444 for '~/.ssh/id_rsa' are too open.
It is recommended that your private key files are NOT accessible by others.
This private key will be ignored.

修复:

chmod 600 ~/.ssh/id_rsa

分享这篇文章:

上一篇
SSL/TLS 证书全景指南
下一篇
SSH 公钥免密码登录