ssh

运维工具箱-ssh

key 密钥管理

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22

# 生成新的密钥
ssh-keygen -t ed25519 -C "chenwx716@163.com" -f chenwx_ed25519

# 上传公钥
ssh-copy-id -i chenwx_ed25519 user1@192.168.0.204
ssh-copy-id -f -i chenwx_ed25519 user1@192.168.0.204    # 强制上传, 目标可能会出现多行

# 移除旧 key
sed -i '/chenwx716@gmail.com/d' .ssh/authorized_keys

# 扫描和获取目标服务器的指纹
ssh-keyscan 192.168.5.9

# 查看本地是否有添加目标主机的公钥指纹
ssh-keygen -F 192.168.5.9

# del host 公钥指纹
ssh-keygen -R 192.168.5.9

# 从私钥导出公钥
ssh-keygen -y -f cwx-xg-tmp1-ed25519

访问目标服务器

1
2
3
4
5
6
7

# 忽略指纹验证, 首次ssh连接不提示yes
-o StrictHostKeyChecking=no


# 远程su执行命令 Cmd="\"/sbin/ifconfig eth0\""
ssh -t -p 22 $user@$Ip /bin/su - root -c {$Cmd};

远程脚本执行

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
# 方法一
ssh user@server bash < /local/script.sh

# 启动远程主机的shell
# -t 标志用于强制分配伪终端
# -l 表示为登陆shell
ssh -t user1@10.2.1.67 'cd /tmp/; bash'
ssh -t user1@10.2.1.67 'cd /tmp/; bash -l'

# 先切换目录,再执行命令,然后启动shell, $SHELL 使用系统默认shell
ssh -t user1@10.2.1.67 'cd /tmp && uname -a && exec $SHELL -l'

文件管理

1
2
# 用DIFF对比远程文件跟本地文件
ssh user@host cat /path/to/remotefile | diff /path/to/localfile -

隧道

1
2
3

## 正向隧道 - 本地监听地址:最终目标地址
ssh -Nf -L 0.0.0.0:8080:172.31.2.1:8080 server -o ServerAliveInterval=60 -o ServerAliveCountMax=5

跳板机

1
2
3
4

# 使用跳板机登录目标服务器
ssh -J server1 server2
ssh -J server1 server2 server3  # 多级跳

sshd 管理

1
2
3
# sshd_config
Port 2022
ListenAddress 10.2.1.5

selinux

1
2
# 修改默认端口号之后
semanage port -a -t ssh_port_t -p tcp 2022
Licensed under CC BY-NC-SA 4.0
转载或引用本文时请遵守许可协议,知会作者并注明出处
不得用于商业用途!
最后更新于 2025-02-10 00:00 UTC