Linux操作系统设置通过密钥登录,修改默认的22号端口

一、Linux操作系统设置通过密钥登录的方法:

1、登录Linux服务器来生成公钥和私钥:

[root@llill ~]# ssh-keygen                             <== 生成密钥对
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa): <== 密钥对默认路径,直接Enter即可
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:
2b:28:25:b6:62:2f:34:ee:f3:3:5e:76:68:37:d9:6e root@llill
The key's randomart image is:
+--[ RSA 2048]----+

2、进入刚刚生成密钥对的默认路径,然后将生成的公钥安装到操作系统上:

[root@llill ~]# cd /root/.ssh                         <== 进入密钥对所在目录
[root@llill .ssh]# cat id_rsa.pub >> authorized_keys <== 安装公钥文件至系统

3、键入以下命令对公钥和目录设置权限:

[root@llill .ssh]# chmod 600 authorized_keys          <== 设置600权限
[root@llill .ssh]# chmod 700 ~/.ssh <== 将目录设置700权限

4、编辑SSH配置文件(/etc/ssh/sshd_config

请将以下四项内容前的#号删除(#号为注释符、即不生效),如果对应项后面默认的是No则改成Yes

注意:如果你本身并不是使用Root账户登录的那么不要修改PermitRootLogin选项包括前面的#号。

    PasswordAuthentication前面的#删除并将后面的Yes改成No即可禁止使用密码来登录SSH和SFTP。

5、重启SSH服务:

[root@llill .ssh]# service sshd restart       <== 重启SSH服务
Redirecting to /bin/systemctl restart sshd.service

6、将私钥/root/.ssh/id_rsa下载到本地,以XShell为例在管理中把验证方法改成Key:

注意: 测试OK后请及时删除服务器上生成的私钥文件。

 

二、linux服务器修改ssh默认22端口方法

 

1、登录服务器,打开sshd_config文件

 

# vim /etc/ssh/sshd_config

 

2、找到#Port 22,默认是注释掉的,先把前面的#号去掉,再插入一行设置成你想要的端口号,注意不要跟现有端口号重复

 

复制代码

# The strategy used for options in the default sshd_config shipped with
# OpenSSH is to specify options with their default value where
# possible, but leave them commented. Uncommented options change a
# default value.

Port 22
Port 23456

复制代码

 

3、保存后退出,执行重启命令

 

# /etc/init.d/sshd restart

 

4、新开一个终端窗口测试23456端口是否可以正常连接服务器,如果成功则将Port 22删除,之所以先设置成两个端口,测试成功后再关闭一个端口,是为了方式在修改conf的过程中,万一出现掉线、断网、误操作等未知情况时候,还能通过另外一个端口连接上去调试以免发生连接不上必须派人去机房,导致问题更加复杂麻烦。

 

三、INUX 如何开放端口和关闭端口

 

1. 查看哪些端口被打开 netstat -anp
2. 关闭端口号:iptables -A INPUT -p tcp --drop 端口号-j DROP
  iptables -A OUTPUT -p tcp --dport 端口号-j DROP
3. 打开端口号:iptables -A INPUT -ptcp --dport 端口号-j ACCEPT
4. 以下是linux打开端口命令的使用方法。
  nc -lp 23 &(打开23端口,即telnet)
  netstat -an | grep 23 (查看是否打开23端口)
5. linux打开端口命令每一个打开的端口,都需要有相应的监听程序才可以

原文地址:https://www.cnblogs.com/zhuntidaoren/p/7921183.html