OS + Rocky 10 / sshd_config / ssh_config / sshd / sshd.service / ssh / 22222

s

- 问题2 防火墙和SELinux的作用

防火墙决定“能否进入端口”,而 SELinux 决定“能做什么应用”

- 问题1 rocky10开启ssh端口22222问题

root@rocky10:~# systemctl status sshd.service
● sshd.service - OpenSSH server daemon
     Loaded: loaded (/usr/lib/systemd/system/sshd.service; enabled; preset: enabled)
     Active: active (running) since Mon 2025-09-08 22:21:54 CST; 17s ago
 Invocation: e1cf69a9aaf345199111dfe2ddcdeae6
       Docs: man:sshd(8)
             man:sshd_config(5)
   Main PID: 8937 (sshd)
      Tasks: 1 (limit: 48756)
     Memory: 1M (peak: 1.5M)
        CPU: 9ms
     CGroup: /system.slice/sshd.service
             └─8937 "sshd: /usr/sbin/sshd -D [listener] 0 of 10-100 startups"

Sep 08 22:21:54 rocky10.xianhemen.cn systemd[1]: Starting sshd.service - OpenSSH server daemon...
Sep 08 22:21:54 rocky10.xianhemen.cn (sshd)[8937]: sshd.service: Referenced but unset environment variable evaluates to an empty string: OPTIONS
Sep 08 22:21:54 rocky10.xianhemen.cn sshd[8937]: error: Bind to port 22222 on 0.0.0.0 failed: Permission denied.
Sep 08 22:21:54 rocky10.xianhemen.cn sshd[8937]: error: Bind to port 22222 on :: failed: Permission denied.
Sep 08 22:21:54 rocky10.xianhemen.cn sshd[8937]: Server listening on 0.0.0.0 port 22.
Sep 08 22:21:54 rocky10.xianhemen.cn sshd[8937]: Server listening on :: port 22.
Sep 08 22:21:54 rocky10.xianhemen.cn systemd[1]: Started sshd.service - OpenSSH server daemon.

解决1

可能原因:
SELinux 限制
RHEL / Rocky Linux 默认启用 SELinux,非标准端口(≠22)的 sshd 会被 SELinux 拒绝。

端口权限问题
Linux 普通进程绑定 1024 以下的端口需要 root 权限,但 22222 > 1024,按理不会有问题,所以大概率是 SELinux。

配置文件里多端口冲突
你可能在 /etc/ssh/sshd_config 里写了:

1、检查 SELinux 是否拦截
getenforce

2、允许 sshd 使用 22222 端口
sudo semanage port -a -t ssh_port_t -p tcp 22222
# 如果端口已存在则用 -m 修改
sudo semanage port -m -t ssh_port_t -p tcp 22222

3、防火墙放行端口
sudo firewall-cmd --permanent --add-port=22222/tcp
sudo firewall-cmd --reload

4、重启 sshd
sudo systemctl restart sshd

 

一:只修改/etc/ssh/sshd_config配置

1:查看ssh的默认端口号

root@rocky1:~# netstat -atpln | grep ssh  # 查看ssh开放端口号

2:修改/etc/ssh/sshd_config配置文件

root@rocky1:~# sed '/^# Port 22/a Port 22222' /etc/ssh/sshd_config   # 先确认,在原注释行下面新增一行是否有效
root@rocky1:~# sed -i '/^# Port 22/a Port 22222' /etc/ssh/sshd_config # 再加i参数修改,(是sshd_config,而不是ssh_config)
root@rocky1:~# grep Port /etc/ssh/sshd_config
# Port 22
Port 22222

二:防火墙配置

root@rocky1:~# sudo firewall-cmd --permanent --add-port=22222/tcp
root@rocky1:~# sudo firewall-cmd --reload
root@rocky1:~# sudo firewall-cmd --permanent --zone=public --list-all  # 查看开放了哪些端口+协议
public (default)
  target: default
  ingress-priority: 0
  egress-priority: 0
  icmp-block-inversion: no
  interfaces: 
  sources: 
  services: cockpit dhcpv6-client ssh
  ports: 22222/tcp 33333/tcp
  protocols: 
  forward: yes
  masquerade: no
  forward-ports: 
  source-ports: 
  icmp-blocks: 
  rich rules: 
root@rocky1:~# 查询永久配置中public区域的端口,仅重启后生效。
root@rocky1:~# firewall-cmd --permanent --zone=public --list-ports
22222/tcp 33333/tcp
root@rocky1:~# 查询运行时配置中public区域的端口,包括临时添加。
root@rocky1:~# firewall-cmd --zone=public --list-ports    # 查看开放了哪些端口
22222/tcp 33333/tcp
root@rocky1:~# 查询永久配置中默认区域的端口。
root@rocky1:~# firewall-cmd --permanent --list-ports    # 查看开放了哪些端口
22222/tcp 33333/tcp

root@rocky1:~# 关闭多余端口命令参考
root@rocky1:~# firewall-cmd --zone=public --remove-port=44444/tcp --remove-port=55555/tcp --permanent
root@rocky1:~# firewall-cmd --reload  # 必须执行后生效

三:向SELinux中添加修改的SSH端口

RHEL / Rocky Linux 默认启用 SELinux,非标准端口(≠22)的 sshd 会被 SELinux 拒绝。

root@rocky2:~# dnf install -y policycoreutils-python-utils # 安装依赖
root@rocky2:~# yum provides semanage    # 查看semanage
Extra Packages for Enterprise Linux 10 - x86_64                             2.0 MB/s |  13 MB     00:06    
Rocky Linux 10 - BaseOS                                                      11 MB/s |  17 MB     00:01    
Rocky Linux 10 - AppStream                                                   13 MB/s |  11 MB     00:00    
Rocky Linux 10 - Extras                                                     8.4 kB/s | 8.0 kB     00:00    
policycoreutils-python-utils-3.8-1.el10.noarch : SELinux policy core python utilities
Repo        : @System
Matched from:
Filename    : /usr/sbin/semanage

policycoreutils-python-utils-3.8-1.el10.noarch : SELinux policy core python utilities
Repo        : appstream
Matched from:
Filename    : /usr/sbin/semanage
root@rocky2:~# semanage port -l |grep ssh    # ssh端口配置前,环境查看
ssh_port_t                     tcp      22
root@rocky2:~# semanage port -a -t ssh_port_t -p tcp 22222  # 向 SELinux 中添加指定放行端口  
root@rocky2:~# systemctl restart sshd.service # 重启服务
root@rocky2:~# semanage port -l | grep ssh   # 查看指定应用端口是否放行
ssh_port_t                     tcp      22222, 22

四:查看SELinux允许服务监听端口大全

root@rocky1:~# netstat -ntpln
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name    
tcp        0      0 127.0.0.1:631           0.0.0.0:*               LISTEN      1118/cupsd          
tcp        0      0 0.0.0.0:33333           0.0.0.0:*               LISTEN      1120/sshd: /usr/sbi 
tcp6       0      0 ::1:631                 :::*                    LISTEN      1118/cupsd          
tcp6       0      0 :::9090                 :::*                    LISTEN      1/systemd           
tcp6       0      0 :::33333                :::*                    LISTEN      1120/sshd: /usr/sbi 
root@rocky1:~# sudo ss -lntp  # 要用sudo执行
State                    Recv-Q                   Send-Q                                      Local Address:Port                                        Peer Address:Port                   Process                                            
LISTEN                   0                        4096                                            127.0.0.1:631                                              0.0.0.0:*                       users:(("cupsd",pid=1118,fd=8))                   
LISTEN                   0                        128                                               0.0.0.0:33333                                            0.0.0.0:*                       users:(("sshd",pid=1120,fd=7))                    
LISTEN                   0                        4096                                                [::1]:631                                                 [::]:*                       users:(("cupsd",pid=1118,fd=7))                   
LISTEN                   0                        4096                                                    *:9090                                                   *:*                       users:(("systemd",pid=1,fd=80))                   
LISTEN                   0                        128                                                  [::]:33333                                               [::]:*                       users:(("sshd",pid=1120,fd=8))                    
root@rocky1:~# sudo semanage port -l
SELinux Port Type              Proto    Port Number

afs3_callback_port_t           tcp      7001
afs3_callback_port_t           udp      7001
afs_bos_port_t                 udp      7007
afs_fs_port_t                  tcp      2040
afs_fs_port_t                  udp      7000, 7005
afs_ka_port_t                  udp      7004
afs_pt_port_t                  tcp      7002
afs_pt_port_t                  udp      7002
afs_vl_port_t                  udp      7003
agentx_port_t                  tcp      705
agentx_port_t                  udp      705
amanda_port_t                  tcp      10080-10083
amanda_port_t                  udp      10080-10082
amavisd_recv_port_t            tcp      10024
amavisd_send_port_t            tcp      10025
amqp_port_t                    tcp      15672, 5671-5672
amqp_port_t                    udp      5671-5672
aol_port_t                     tcp      5190-5193
aol_port_t                     udp      5190-5193
apc_port_t                     tcp      3052
apc_port_t                     udp      3052
apcupsd_port_t                 tcp      3551
apcupsd_port_t                 udp      3551
apertus_ldp_port_t             tcp      539
apertus_ldp_port_t             udp      539
appswitch_emp_port_t           tcp      2616
appswitch_emp_port_t           udp      2616
asterisk_port_t                tcp      1720
asterisk_port_t                udp      2427, 2727, 4569
audit_port_t                   tcp      60
auth_port_t                    tcp      113
babel_port_t                   udp      6696
bacula_port_t                  tcp      9103
bacula_port_t                  udp      9103
bctp_port_t                    tcp      8999
bctp_port_t                    udp      8999
bfd_control_port_t             tcp      3784
bfd_control_port_t             udp      3784
bfd_echo_port_t                tcp      3785
bfd_echo_port_t                udp      3785
bfd_multi_port_t               tcp      4784
bfd_multi_port_t               udp      4784
bgp_port_t                     tcp      179, 2605
bgp_port_t                     udp      179, 2605
boinc_client_port_t            tcp      1043
boinc_client_port_t            udp      1034
boinc_port_t                   tcp      31416
boothd_port_t                  tcp      9929
boothd_port_t                  udp      9929
brlp_port_t                    tcp      4101
certmaster_port_t              tcp      51235
chronyd_port_t                 udp      323
clamd_port_t                   tcp      3310
clockspeed_port_t              udp      4041
cluster_port_t                 tcp      5149, 40040, 50006-50008
cluster_port_t                 udp      5149, 50006-50008
cma_port_t                     tcp      1050
cma_port_t                     udp      1050
cmadmin_port_t                 tcp      2617
cmadmin_port_t                 udp      2617
cobbler_port_t                 tcp      25151
collectd_port_t                udp      25826
commplex_link_port_t           tcp      4331, 5001
commplex_link_port_t           udp      5001
commplex_main_port_t           tcp      5000
commplex_main_port_t           udp      5000
comsat_port_t                  udp      512
condor_port_t                  tcp      9618
condor_port_t                  udp      9618
conman_port_t                  tcp      7890
conman_port_t                  udp      7890
connlcli_port_t                tcp      1358
connlcli_port_t                udp      1358
conntrackd_port_t              udp      3780
couchdb_port_t                 tcp      5984, 6984
couchdb_port_t                 udp      5984, 6984
ctdb_port_t                    tcp      4379
ctdb_port_t                    udp      4379
cvs_port_t                     tcp      2401
cvs_port_t                     udp      2401
cyphesis_port_t                tcp      6767, 6769, 6780-6799
cyphesis_port_t                udp      32771
cyrus_imapd_port_t             tcp      2005
daap_port_t                    tcp      3689
daap_port_t                    udp      3689
dbskkd_port_t                  tcp      1178
dcc_port_t                     udp      6276, 6277
dccm_port_t                    tcp      5679
dccm_port_t                    udp      5679
dey_keyneg_port_t              tcp      8750
dey_keyneg_port_t              udp      8750
dey_sapi_port_t                tcp      4330
dhcpc_port_t                   tcp      68, 546, 5546
dhcpc_port_t                   udp      68, 546, 5546
dhcpd_port_t                   tcp      547, 548, 647, 847, 7911
dhcpd_port_t                   udp      67, 547, 548, 647, 847
dict_port_t                    tcp      2628
distccd_port_t                 tcp      3632
dns_port_t                     tcp      53, 853
dns_port_t                     udp      53, 853
dnssec_port_t                  tcp      8955
dogtag_port_t                  tcp      7390
echo_port_t                    tcp      7
echo_port_t                    udp      7
efs_port_t                     tcp      520
embrace_dp_c_port_t            tcp      3198
embrace_dp_c_port_t            udp      3198
ephemeral_port_t               tcp      32768-60999
ephemeral_port_t               udp      32768-60999
epmap_port_t                   tcp      135
epmap_port_t                   udp      135
epmd_port_t                    tcp      4369
epmd_port_t                    udp      4369
fac_restore_port_t             tcp      5582
fac_restore_port_t             udp      5582
fingerd_port_t                 tcp      79
firepower_port_t               tcp      2615
firepower_port_t               udp      2615
flash_port_t                   tcp      843, 1935
flash_port_t                   udp      1935
fmpro_internal_port_t          tcp      5003
fmpro_internal_port_t          udp      5003
freeipmi_port_t                tcp      9225
freeipmi_port_t                udp      9225
ftp_data_port_t                tcp      20
ftp_port_t                     tcp      21, 989, 990
ftp_port_t                     udp      989, 990
gatekeeper_port_t              tcp      1721, 7000
gatekeeper_port_t              udp      1718, 1719
gdomap_port_t                  tcp      538
gdomap_port_t                  udp      538
gds_db_port_t                  tcp      3050
gds_db_port_t                  udp      3050
gear_port_t                    tcp      43273
gear_port_t                    udp      43273
geneve_port_t                  tcp      6080
giftd_port_t                   tcp      1213
git_port_t                     tcp      9418
git_port_t                     udp      9418
glance_port_t                  tcp      9292
glance_port_t                  udp      9292
glance_registry_port_t         tcp      9191
glance_registry_port_t         udp      9191
gluster_port_t                 tcp      38465-38469, 24007-24027
gnome_remote_desktop_port_t    tcp      3389-3399
gopher_port_t                  tcp      70
gopher_port_t                  udp      70
gpsd_port_t                    tcp      2947
hadoop_datanode_port_t         tcp      50010
hadoop_namenode_port_t         tcp      8020
hddtemp_port_t                 tcp      7634
hi_reserved_port_t             sctp     512-1023
hi_reserved_port_t             tcp      512-1023
hi_reserved_port_t             udp      512-1023
howl_port_t                    tcp      5335
howl_port_t                    udp      5353
hplip_port_t                   tcp      1782, 2207, 2208, 8290, 8292, 9100, 9101, 9102, 9220, 9221, 9222, 9280, 9281, 9282, 9290, 9291, 50000, 50002
http_cache_port_t              tcp      8080, 8118, 8123, 10001-10010
http_cache_port_t              udp      3130
http_port_t                    tcp      80, 81, 443, 488, 8008, 8009, 8443, 9000
i18n_input_port_t              tcp      9010
ibm_dt_2_port_t                tcp      1792
ibm_dt_2_port_t                udp      1792
imaze_port_t                   tcp      5323
imaze_port_t                   udp      5323
inetd_child_port_t             tcp      1, 9, 13, 19, 512, 544, 891, 892, 5666
inetd_child_port_t             udp      1, 9, 13, 19, 891, 892
innd_port_t                    tcp      119
intermapper_port_t             tcp      8181
interwise_port_t               tcp      7778
interwise_port_t               udp      7778
ionixnetmon_port_t             tcp      7410
ionixnetmon_port_t             udp      7410
ipmi_port_t                    udp      623, 664
ipp_port_t                     tcp      631, 8610-8614
ipp_port_t                     udp      631, 8610-8614
ipsecnat_port_t                tcp      4500
ipsecnat_port_t                udp      4500
ircd_port_t                    tcp      6667, 6697
isakmp_port_t                  udp      500
iscsi_port_t                   tcp      3260
isns_port_t                    tcp      3205, 51954
isns_port_t                    udp      3205
jabber_client_port_t           tcp      5222, 5223
jabber_interserver_port_t      tcp      5269, 5280
jabber_router_port_t           tcp      5347
jacorb_port_t                  tcp      3528, 3529
jboss_debug_port_t             tcp      8787
jboss_debug_port_t             udp      8787
jboss_management_port_t        tcp      4447, 4712, 7600, 9123, 9990, 9999, 18001
jboss_management_port_t        udp      4712, 9123
jboss_messaging_port_t         tcp      5445, 5455
journal_remote_port_t          tcp      19532
kerberos_admin_port_t          tcp      749
kerberos_password_port_t       tcp      464
kerberos_password_port_t       udp      464
kerberos_port_t                tcp      88, 750, 4444
kerberos_port_t                udp      88, 750, 4444
keylime_port_t                 tcp      8881, 8892, 9002
keystone_port_t                tcp      35357
keystone_port_t                udp      35357
kprop_port_t                   tcp      754
ktalkd_port_t                  udp      517, 518
kubernetes_port_t              tcp      4001, 4194, 10250
l2tp_port_t                    tcp      1701
l2tp_port_t                    udp      1701
ldap_port_t                    tcp      389, 636, 3268, 3269, 7389
ldap_port_t                    udp      389, 636
lirc_port_t                    tcp      8765
llmnr_port_t                   tcp      5355
llmnr_port_t                   udp      5355
lltng_port_t                   tcp      5345
lmtp_port_t                    tcp      24, 2003
lmtp_port_t                    udp      24
lsm_plugin_port_t              tcp      18700
luci_port_t                    tcp      8084
mail_port_t                    tcp      2000, 3905
mailbox_port_t                 tcp      2004
matahari_port_t                tcp      49000
matahari_port_t                udp      49000
memcache_port_t                tcp      11211
memcache_port_t                udp      11211
milter_port_t                  tcp      8890, 8891, 8893
mmcc_port_t                    tcp      5050
mmcc_port_t                    udp      5050
mongod_port_t                  tcp      27017-27019, 28017-28019
monopd_port_t                  tcp      1234
mountd_port_t                  tcp      20048
mountd_port_t                  udp      20048
movaz_ssc_port_t               tcp      5252
movaz_ssc_port_t               udp      5252
mpd_port_t                     tcp      6600
ms_streaming_port_t            tcp      1755
ms_streaming_port_t            udp      1755
msnp_port_t                    tcp      1863
msnp_port_t                    udp      1863
mssql_port_t                   tcp      1433-1434
mssql_port_t                   udp      1433-1434
munin_port_t                   tcp      4949
munin_port_t                   udp      4949
mxi_port_t                     tcp      8005
mxi_port_t                     udp      8005
mysqld_port_t                  tcp      1186, 3306, 63132-63164
mysqlmanagerd_port_t           tcp      2273
mythtv_port_t                  tcp      6543-6544
nessus_port_t                  tcp      1241
netport_port_t                 tcp      3129
netport_port_t                 udp      3129
netsupport_port_t              tcp      5404, 5405
netsupport_port_t              udp      5404, 5405
neutron_port_t                 tcp      8775, 9696, 9697
nfs_port_t                     tcp      2049, 20048-20049
nfs_port_t                     udp      2049, 20048-20049
nmbd_port_t                    udp      137, 138
nmea_port_t                    tcp      10110
nmea_port_t                    udp      10110
nodejs_debug_port_t            tcp      5858
nodejs_debug_port_t            udp      5858
nsca_port_t                    tcp      5667
nsd_control_port_t             tcp      8952
ntop_port_t                    tcp      3000-3001
ntop_port_t                    udp      3000-3001
ntp_port_t                     udp      123
ntske_port_t                   tcp      4460
oa_system_port_t               tcp      8022
oa_system_port_t               udp      8022
ocsp_port_t                    tcp      9080
opendnssec_port_t              tcp      15354
opendnssec_port_t              udp      15354
openflow_port_t                tcp      6633, 6653
openhpid_port_t                tcp      4743
openhpid_port_t                udp      4743
openqa_liveview_port_t         tcp      9528
openqa_port_t                  tcp      9526
openqa_websockets_port_t       tcp      9527
openvpn_port_t                 tcp      1194
openvpn_port_t                 udp      1194
openvswitch_port_t             tcp      6634
oracle_port_t                  tcp      1521, 2483, 2484
oracle_port_t                  udp      1521, 2483, 2484
osapi_compute_port_t           tcp      8774
ovsdb_port_t                   tcp      6640
pdps_port_t                    tcp      1314
pdps_port_t                    udp      1314
pegasus_http_port_t            tcp      5988
pegasus_https_port_t           tcp      5989
pgpkeyserver_port_t            tcp      11371
pgpkeyserver_port_t            udp      11371
pingd_port_t                   tcp      9125
pki_ca_port_t                  tcp      829, 9180, 9701, 9443-9447
pki_kra_port_t                 tcp      10180, 10701, 10443-10446
pki_ocsp_port_t                tcp      11180, 11701, 11443-11446
pki_ra_port_t                  tcp      12888-12889
pki_tks_port_t                 tcp      13180, 13701, 13443-13446
pki_tps_port_t                 tcp      7888-7889
pktcable_cops_port_t           tcp      2126
pktcable_cops_port_t           udp      2126
pop_port_t                     tcp      106, 109, 110, 143, 220, 993, 995, 1109, 10993
portmap_port_t                 tcp      111
portmap_port_t                 udp      111
postfix_policyd_port_t         tcp      10031
postgresql_port_t              tcp      5432, 9898
postgrey_port_t                tcp      60000
pptp_port_t                    tcp      1723
pptp_port_t                    udp      1723
prelude_port_t                 tcp      4690
prelude_port_t                 udp      4690
presence_port_t                tcp      5298-5299
presence_port_t                udp      5298-5299
preupgrade_port_t              tcp      8099
printer_port_t                 tcp      515
priority_e_com_port_t          tcp      2618
priority_e_com_port_t          udp      2618
prosody_port_t                 tcp      5280-5281
ptal_port_t                    tcp      5703
ptp_event_port_t               udp      319
pulp_port_t                    tcp      24816, 24817
pulseaudio_port_t              tcp      4713
pulseaudio_port_t              udp      4713
puppet_port_t                  tcp      8140
pxe_port_t                     udp      4011
pyzor_port_t                   udp      24441
qpasa_agent_port_t             tcp      2611, 2612
qpasa_agent_port_t             udp      2611, 2612
rabbitmq_port_t                tcp      25672
radacct_port_t                 tcp      1646, 1813
radacct_port_t                 udp      1646, 1813
radius_port_t                  tcp      1645, 1812, 18120-18121
radius_port_t                  udp      1645, 1812, 18120-18121
radsec_port_t                  tcp      2083
razor_port_t                   tcp      2703
redis_port_t                   tcp      6379, 16379, 26379
repository_port_t              tcp      6363
reserved_port_t                sctp     1-511
reserved_port_t                tcp      1-511
reserved_port_t                udp      1-511
ricci_modcluster_port_t        tcp      16851
ricci_modcluster_port_t        udp      16851
ricci_port_t                   tcp      11111
ricci_port_t                   udp      11111
rkt_port_t                     tcp      18112
rlogin_port_t                  tcp      543, 2105
rlogind_port_t                 tcp      513
rndc_port_t                    tcp      953, 8953
rndc_port_t                    udp      953
router_port_t                  tcp      521
router_port_t                  udp      520, 521
rsh_port_t                     tcp      514
rsync_port_t                   tcp      873
rsync_port_t                   udp      873
rtp_media_port_t               tcp      5004-5005
rtp_media_port_t               udp      5004-5005
rtsclient_port_t               tcp      2501
rtsp_port_t                    tcp      554, 8554
rtsp_port_t                    udp      554, 8554
rwho_port_t                    udp      513
salt_port_t                    tcp      4505, 4506
sap_port_t                     tcp      9875
sap_port_t                     udp      9875
saphostctrl_port_t             tcp      1128, 1129
servistaitsm_port_t            tcp      3636
servistaitsm_port_t            udp      3636
sge_port_t                     tcp      6444, 6445
shellinaboxd_port_t            tcp      4200
sieve_port_t                   tcp      4190
sip_port_t                     tcp      5060, 5061
sip_port_t                     udp      5060, 5061
sixxsconfig_port_t             tcp      3874
sixxsconfig_port_t             udp      3874
smbd_port_t                    tcp      445, 137-139
smntubootstrap_port_t          tcp      2613
smntubootstrap_port_t          udp      2613
smtp_port_t                    tcp      25, 465, 587
snmp_port_t                    tcp      199, 1161, 161-162, 10161-10162
snmp_port_t                    udp      161-162, 10161-10162
soundd_port_t                  tcp      8000, 9433, 16001
spamd_port_t                   tcp      783, 10026, 10027
speech_port_t                  tcp      8036
squid_port_t                   tcp      3128, 3401, 4827
squid_port_t                   udp      3401, 4827
ssdp_port_t                    tcp      1900
ssdp_port_t                    udp      1900
ssh_port_t                     tcp      22222, 22
statsd_port_t                  udp      8125
svn_port_t                     tcp      3690
svn_port_t                     udp      3690
svrloc_port_t                  tcp      427
svrloc_port_t                  udp      427
swat_port_t                    tcp      901
swift_port_t                   tcp      6200-6203
sype_transport_port_t          tcp      9911
sype_transport_port_t          udp      9911
syslog_tls_port_t              tcp      6514, 10514
syslog_tls_port_t              udp      6514, 10514
syslogd_port_t                 tcp      601, 20514
syslogd_port_t                 udp      514, 601, 20514
tangd_port_t                   tcp      7406
tcs_port_t                     tcp      30003
telnetd_port_t                 tcp      23
tftp_port_t                    udp      69
time_port_t                    tcp      37
time_port_t                    udp      37
tor_port_t                     tcp      6969, 9001, 9030, 9050, 9051, 9150
traceroute_port_t              udp      64000-64010
tram_port_t                    tcp      4567
transproxy_port_t              tcp      8081
trisoap_port_t                 tcp      10200
trisoap_port_t                 udp      10200
trivnet1_port_t                tcp      8200
trivnet1_port_t                udp      8200
unreserved_port_t              sctp     1024-65535
unreserved_port_t              tcp      61000-65535, 1024-32767
unreserved_port_t              udp      61000-65535, 1024-32767
ups_port_t                     tcp      3493
us_cli_port_t                  tcp      8082, 8083
us_cli_port_t                  udp      8082, 8083
uucpd_port_t                   tcp      540
varnishd_port_t                tcp      6081-6082
versa_tek_port_t               tcp      2610
versa_tek_port_t               udp      2610
virt_migration_port_t          tcp      49152-49216
virt_port_t                    tcp      16509, 16514
virt_port_t                    udp      16509, 16514
virtual_places_port_t          tcp      1533
virtual_places_port_t          udp      1533
vnc_port_t                     tcp      5985-5999, 5900-5983
vqp_port_t                     tcp      1589
vqp_port_t                     udp      1589
wap_wsp_port_t                 tcp      9200
wap_wsp_port_t                 udp      9200
wccp_port_t                    udp      2048
websm_port_t                   tcp      9090
websm_port_t                   udp      9090
whois_port_t                   tcp      43, 4321
whois_port_t                   udp      43, 4321
winshadow_port_t               tcp      3161
winshadow_port_t               udp      3261
wsdapi_port_t                  tcp      5357
wsdapi_port_t                  udp      5357
wsicopy_port_t                 tcp      3378
wsicopy_port_t                 udp      3378
xdmcp_port_t                   tcp      177
xdmcp_port_t                   udp      177
xen_port_t                     tcp      8002
xfs_port_t                     tcp      7100
xinuexpansion3_port_t          tcp      2023
xinuexpansion3_port_t          udp      2023
xinuexpansion4_port_t          tcp      2024
xinuexpansion4_port_t          udp      2024
xmsg_port_t                    tcp      1716
xmsg_port_t                    udp      1716
xodbc_connect_port_t           tcp      6632
xserver_port_t                 tcp      6000-6020
zabbix_agent_port_t            tcp      10050
zabbix_port_t                  tcp      10051
zarafa_port_t                  tcp      236, 237
zebra_port_t                   tcp      2606, 2608-2609, 2600-2604
zebra_port_t                   udp      2606, 2608-2609, 2600-2604
zented_port_t                  tcp      1229
zented_port_t                  udp      1229
zookeeper_client_port_t        tcp      2181
zookeeper_election_port_t      tcp      3888
zookeeper_leader_port_t        tcp      2888
zope_port_t                    tcp      8021
root@rocky1:~# 

五:安全设置 Fail2ban

说明:Fail2ban 默认配置在 /etc/fail2ban/jail.conf,但官方推荐不要直接改它,而是写在 /etc/fail2ban/jail.local

1、安装 fail2ban 应用

root@rocky2:~# sudo dnf install -y epel-release
root@rocky2:~# sudo dnf install -y fail2ban fail2ban-firewalld
root@rocky2:~# sudo systemctl enable --now fail2ban
root@rocky2:~# sudo systemctl status fail2ban

2、定义脚本

root@rocky2:~# sudo cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local

3、新增内容 /etc/fail2ban/jail.local。ini文件不能在-有效配置行后面加注释,容易启动不了

#===========================================================
# Fail2ban 本地配置文件 (jail.local)
# 作用:防护 SSH 爆破攻击
# 注意:
#   1. 注释必须单独占一行
#   2. filter 文件使用 sshd.local,覆盖默认规则
#===========================================================
[sshd]
# 是否启用此 jail
enabled = true
# 监听端口,可以写多个
port = 22,33333
# 使用自定义 filter 文件
filter = sshd
# 日志路径
logpath = /var/log/secure
# 最大尝试次数 (maxretry 次失败封禁 IP)
maxretry = 5
# 封禁时间 (秒)
bantime = 3600
# 查找失败次数的时间窗口 (秒)
findtime = 600
# 后端类型,auto 即自动选择 systemd/journald 等
backend = auto

# 可选:如果使用 firewalld 封禁
# action = firewallcmd-ipset
# 默认 action 是 iptables-multiport,可自行修改

3.2 新增文件 /etc/fail2ban/filter.d/sshd.local ,添加如下内容:

- 写法1,简易规则

[INCLUDES]
before = common.conf

[Definition]
failregex = ^%(__prefix_line)sFailed password for .* from <HOST> port \d+ ssh2$
            ^%(__prefix_line)sConnection closed by authenticating user .* <HOST> port \d+ \[preauth\]$
ignoreregex =

- 写法2,多种规则,如加注释异常,可以去掉

[INCLUDES]
# 继承 common.conf 中的通用前缀(如 %(__prefix_line)s)和日期模式,确保兼容系统日志格式
before = common.conf

[Definition]
# SSH 登录失败常见日志匹配 - 这些规则用于检测各种 SSH 认证失败事件
# 每个规则用 | 分隔,Fail2Ban 会逐一尝试匹配日志行(OR 逻辑)
failregex = ^%(__prefix_line)sFailed password for .* from <HOST> port \d+ ssh2$
          # 匹配普通密码认证失败日志,例如:Failed password for invalid from 192.168.1.1 port 22 ssh2

          | ^%(__prefix_line)sInvalid user .* from <HOST>( port \d+)?$
          # 匹配无效用户名登录尝试,例如:Invalid user fakeuser from 192.168.1.1

          | ^%(__prefix_line)s pam_unix\(sshd:auth\): authentication failure; .* rhost=<HOST> .*$
          # 匹配 PAM 认证失败(修正:添加 sshd[pam] 前缀以匹配标准格式),例如:pam_unix(sshd:auth): authentication failure; logname= uid=0 euid=0 tty= ruser= rhost=192.168.1.1

          | ^%(__prefix_line)sFailed publickey for .* from <HOST> port \d+ ssh2$
          # 匹配 SSH 密钥认证失败,例如:Failed publickey for user from 192.168.1.1 port 22 ssh2

          | ^%(__prefix_line)sConnection closed by authenticating user .* <HOST> port \d+ \[preauth\]$
          # 匹配预认证阶段连接关闭(可疑行为),例如:Connection closed by authenticating user root 192.168.1.1 port 22 [preauth]

          | ^%(__prefix_line)sDisconnected from <HOST> port \d+.*
          # 匹配远程断开连接(可选:如果匹配正常用户,可能移到 ignoreregex 避免误判),例如:Disconnected from invalid user 192.168.1.1 port 22

          | ^%(__prefix_line)serror: maximum authentication attempts exceeded for .* from <HOST> port \d+ ssh2$
          # 匹配最大认证尝试超限,例如:error: maximum authentication attempts exceeded for invalid from 192.168.1.1 port 22 ssh2

# 忽略的日志匹配 - 可以为空,或添加正常行为模式(如本地 IP 断开)以避免误禁
ignoreregex =

4. 检查 fail2ban配置

root@rocky2:/etc/fail2ban/filter.d# sudo fail2ban-regex /var/log/secure /etc/fail2ban/filter.d/sshd.local
root@rocky2:/etc/fail2ban/filter.d# sudo systemctl restart fail2ban
root@rocky2:/etc/fail2ban/filter.d# sudo systemctl status fail2ban
root@rocky2:/etc/fail2ban/filter.d# sudo fail2ban-client reload    # 测试加载
root@rocky2:/etc/fail2ban/filter.d# sudo fail2ban-client -d

5 启用 fail2ban

sudo systemctl restart fail2ban
sudo systemctl enable fail2ban

6 查看 sshd jail 状态

root@rocky2:~# sudo fail2ban-client status
root@rocky2:~# sudo fail2ban-client status sshd # 监测到并禁止IP
Status for the jail: sshd
|- Filter
|  |- Currently failed: 1
|  |- Total failed:     9
|  `- File list:        /var/log/secure
`- Actions
   |- Currently banned: 1
   |- Total banned:     1
   `- Banned IP list:   122.192.15.8

7. 手动解封 IP(如果需要)

sudo fail2ban-client unban <IP_ADDRESS>

8. 观察日志

root@rocky1:~# tail -f /var/log/secure /var/log/fail2ban.log

- 9. 一键化脚本

#!/usr/bin/env python3
import os
import subprocess
from textwrap import dedent

def run(cmd):
    print(f"\n[执行] {cmd}")
    subprocess.run(cmd, shell=True, check=True, executable="/bin/bash")

def main():
    # 1. 修改 SSH 配置文件端口
    sshd_config = "/etc/ssh/sshd_config"
    run(f"sudo sed -i 's/^#Port 22/Port 22\\nPort 22222/' {sshd_config}")

    # 2. SELinux 添加端口规则 (只针对 SSH 新端口 22222)
    run("sudo dnf install -y policycoreutils-python-utils")
    run("sudo semanage port -a -t ssh_port_t -p tcp 22222 || sudo semanage port -m -t ssh_port_t -p tcp 22222")

    # 3. 防火墙放行 SSH 新端口
    run("sudo firewall-cmd --permanent --add-port=22222/tcp")

    # 3.1 防火墙放行其他应用端口 (33333, 44444, 55555)
    for port in [33333, 44444, 55555]:
        run(f"sudo firewall-cmd --permanent --add-port={port}/tcp")

    # 4. 重载防火墙规则
    run("sudo firewall-cmd --reload")

    # 5. 重启 sshd 并设置开机自启
    run("sudo systemctl restart sshd")
    run("sudo systemctl enable sshd")

    # 6. 安装 Fail2ban
    run("sudo dnf install -y epel-release")
    run("sudo dnf install -y fail2ban fail2ban-firewalld")
    run("sudo systemctl enable --now fail2ban")

    # 7. 配置 Fail2ban jail.local
    jail_local = dedent("""
    [sshd]
    enabled = true
    port = 22,22222
    filter = sshd
    logpath = /var/log/secure
    maxretry = 5
    bantime = 3600
    findtime = 600
    backend = auto
    action = firewallcmd-ipset
    """).strip()
    with open("/tmp/jail.local", "w") as f:
        f.write(jail_local)
    run("sudo cp /tmp/jail.local /etc/fail2ban/jail.local")

    # 8. 配置 Fail2ban 自定义过滤规则
    sshd_local = dedent("""
    [INCLUDES]
    before = common.conf

    [Definition]
    failregex = ^%(__prefix_line)sFailed password for .* from <HOST> port \\d+ ssh2$
                ^%(__prefix_line)sInvalid user .* from <HOST>( port \\d+)?$
                ^%(__prefix_line)s pam_unix\\(sshd:auth\\): authentication failure; .* rhost=<HOST>.*$
                ^%(__prefix_line)sFailed publickey for .* from <HOST> port \\d+ ssh2$
                ^%(__prefix_line)sConnection closed by authenticating user .* <HOST> port \\d+ \\[preauth\\]$
                ^%(__prefix_line)sDisconnected from <HOST> port \\d+.*
                ^%(__prefix_line)serror: maximum authentication attempts exceeded for .* from <HOST> port \\d+ ssh2$
    ignoreregex =
    """).strip()
    with open("/tmp/sshd.local", "w") as f:
        f.write(sshd_local)
    run("sudo cp /tmp/sshd.local /etc/fail2ban/filter.d/sshd.local")

    # 9. 重启 Fail2ban
    run("sudo systemctl restart fail2ban")

    # 10. 添加 alias 和 history 设置
    lindows_sh = dedent("""
    alias tt='ps -ef | grep http'
    alias jj='ps -ef | grep java'
    alias nn='netstat -atpln | grep : | sort'
    alias ss='ss -ntpln | grep :  |sort '
    alias pp='netstat -aptln | grep php'
    alias mm='netstat -atpln | grep mysql'
    HISTTIMEFORMAT="%F %T "
    HISTFILESIZE=10000
    HISTSIZE=10000
    """).strip()
    with open("/tmp/lindows.sh", "w") as f:
        f.write(lindows_sh)
    run("sudo cp /tmp/lindows.sh /etc/profile.d/lindows.sh")

    # 11. 立刻生效 alias / history 配置
    run("source /etc/profile.d/lindows.sh")

    print("\n✅ 全部操作完成!")
    print("➡️ 使用 `ssh -p 22222 user@IP` 测试新端口连接")
    print("➡️ Fail2ban 已启用,可用 `sudo fail2ban-client status sshd` 查看")
    print("➡️ alias 已写入 /etc/profile.d/lindows.sh 并已生效")
    print("➡️ 额外端口 33333, 44444, 55555 已对外开放(非 SSH)")

if __name__ == "__main__":
    main()

 

end

posted @ 2022-06-09 23:45  siemens800  阅读(191)  评论(0)    收藏  举报