不重启 ssh 服务并加载新的配置
After updated /etc/ssh/sshd_config
, using below command to reload the sshd_config
without restart sshd daemon service.
systemctl reload sshd
# 或
sudo kill -SIGHUP $(pgrep -f "sshd -D")
SSH 免密登录设置
chmod 755 ~/.ssh
chmod 600 ~/.ssh/authorized_keys
SSH 通过私钥生成公钥
ssh-keygen -y -f id_rsa > id_rsa.pub
生成 sshd 所需 host keys
启动 sshd
服务时如果没有 host keys,会报如下错误
sshd: no hostkeys available -- exiting.
执行以下命令生成所需的 host keys
ssh-keygen -A
SSH known host update
TARGET_HOST=[hostname or IP]
# Remove the old key(s) from known_hosts
ssh-keygen -R $TARGET_HOST
# Add the new key(s) to known_hosts (and also hash the hostname/address)
ssh-keyscan -H $TARGET_HOST >> ~/.ssh/known_hosts
Autossh
语法
autossh [-V] [-M port[:echo_port]] [-f] [SSH_OPTIONS]
远程登录
autossh -M 12345 -i .ssh/id_rsa remote-server
端口转发
autossh -M 12345 -o ServerAliveInterval=60 -o ServerAliveCountMax=10 -NT -L 0.0.0.0:8080:remote-server:8080 jump-server
查看 autossh 日志
# 使用环境变量将日志输出到指定文件路径,然后启动 autossh 后查看日志
export AUTOSSH_LOGFILE="$HOME/autossh.log"
autossh -M 10090 -D 10080 jump-server
SSH supported escape sequences
~. - terminate connection (and any multiplexed sessions)
~B - send a BREAK to the remote system
~C - open a command line
~R - request rekey
~V/v - decrease/increase verbosity (LogLevel)
~^Z - suspend ssh
~# - list forwarded connections
~& - background ssh (when waiting for connections to terminate)
~? - this message
~~ - send the escape character by typing it twice
(Note that escapes are only recognized immediately after newline.)
使用 PSSH 并行访问多台远程主机
-h HOST_FILE, --hosts=HOST_FILE
hosts file (each line "[user@]host[:port]")
-l USER, --user=USER username (OPTIONAL)
-p PAR, --par=PAR max number of parallel threads (OPTIONAL)
-A, --askpass Ask for a password (OPTIONAL)
-x ARGS, --extra-args=ARGS
Extra command-line arguments, with processing for
spaces, quotes, and backslashes
-i, --inline inline aggregated output and error for each server
pssh -x -q -i -h server-list -l root -A echo 'hello world.'
使用 SSH + TAR 实现远程备份或远程复制
将远程数据压缩后复制到本地
# 压缩remote-server上的/opt/app目录到标准输出,排除/opt/app目录下的logs目录和*.log文件
ssh user@remote-server 'tar czf - --exclude="logs" --exclude="*.log" /opt/app' > app.tar.gz
# 只打包应用所在目录
ssh user@remote-server 'tar czf - -C /opt --exclude="logs" --exclude="*.log" app' > app.tar.gz
将远程压缩文件解压到本地
ssh user@remote-server 'cd /opt; cat app.tar.gz' | tar xzvf - -C /opt
将本地数据压缩后备份到远程服务器
tar cvzf - -C /opt app | ssh user@remote-server 'cat > /opt/app.tar.gz'
scp
命令在进行远程复制时不会压缩数据,须使用 -C
选项开启压缩模式.