【Linux基础服务教程】SSH远程连接服务
一、关于SSH
-
SSH 应用层协议
- 实现Linux主机加密、远程连接
- 适用于Linux服务器远程管理
-
telnet
- 远程连接,不加密
- 适用于局域网网络设备的远程连接
二、SSH的使用
1.确保sshd服务正常开启
[root@localhost ~]# ps -elf | grep ssh
4 S root 6541 1 0 80 0 - 28189 poll_s 09:55 ? 00:00:00 /usr/sbin/sshd -D
4 S root 6806 6541 0 80 0 - 39288 poll_s 09:56 ? 00:00:00 sshd: root@pts/0
0 S root 6851 6808 0 80 0 - 28177 pipe_w 10:20 pts/0 00:00:00 grep --color=auto ssh
[root@localhost ~]# netstat -tunlp | grep "sshd"
tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN 6541/sshd
tcp6 0 0 :::22 :::* LISTEN 6541/sshd #ssh默认使用22号端口
- ssh服务端口: 22/tcp
2.ssh对应的软件包
[root@localhost ~]# rpm -qf /usr/sbin/sshd
openssh-server-7.4p1-16.el7.x86_64
3.ssh命令
# ssh 用户命@主机地址
[root@localhost ~]# ssh root@192.168.140.10 uptime
root@192.168.140.10's password:
10:33:44 up 38 min, 1 user, load average: 0.00, 0.01, 0.02
三、远程拷贝文件
- scp
- 全量拷贝工具
- rsync
- 增量拷贝工具
1.scp命令
特点
- 依靠SSH协议
- 多文件的时候直接拷贝全部文件
# scp 源文件 用户名@服务器地址:目录
- -r 拷贝目录
[root@node01 ~]# scp /opt/file01.txt root@192.168.140.11:/tmp #拷贝本机文件到对方主机
[root@node01 ~]# scp root@192.168.140.11:/etc/passwd /tmp/ #拷贝对方主机文件到本机
[root@node01 ~]# scp -r /opt/linux/ root@192.168.140.11:/tmp/ #拷贝本机目录到对方主机
2.rsync命令
特点
- 依靠SSH协议
- 多文件的时候只会拷贝近期修改过的文件
- 重复文件和未修改文件不会拷贝
# rsync -av 源文件 用户名@主机地址:目录
四、配置免密登录
1.生成秘钥文件
# ssh-keygen -t 加密类型
[root@node01 ~]# ssh-keygen -t rsa #使用RSA算法生成秘钥文件
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa): #默认目录即可
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:SWcLrku9sR+q5j5KgGP6vyhJeS/3LwZxzSs9hbKOecw root@node01.linux.com
The key's randomart image is:
+---[RSA 2048]----+
| |
| |
| = + |
| . . = O o |
|o.o o S + |
|o+ o . = + |
|o.. o X + o |
|o. + *oE = . |
| .o.**O+*o. |
+----[SHA256]-----+
[root@node01 ~]# ls /root/.ssh/
id_rsa id_rsa.pub known_hosts
- id_rsa 私钥文件
- id_rsa.pub 公钥文件
2.拷贝公钥到目标服务器
# ssh-copy-id 用户@主机地址
[root@node01 ~]# ssh-copy-id root@192.168.140.11
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
root@192.168.140.11's password:
Number of key(s) added: 1
Now try logging into the machine, with: "ssh 'root@192.168.140.11'"
and check to make sure that only the key(s) you wanted were added.
- 自动将公钥拷贝到对方服务器用户家目录
- /root/.ssh/authorized_keys
注意事项
- 免密SSH基于用户
- 免密SSH是单向的
五、ssh服务配置文件
1.配置文件目录
- /etc/ssh/sshd_config
2.常用修改配置项
修改服务默认端口
Port 54321 #默认端口是22
[root@localhost ~]# systemctl restart sshd
禁用密码认证
- 请提前配置好免密!!!
PasswordAuthentication no #默认是yes参数
禁止root用户远程登录
PermitRootLogin no
禁用DNS反解,加快SSH登录速度
UseDNS no