一:端口占用查看进程,终止进程
Centos查看端口占用情况命令,比如查看80端口占用情况使用如下命令:
lsof -i tcp:80
列出所有使用中的端口
netstat -ntlp
检查端口被哪个进程占用
netstat -lnp|grep 8080 #8080为端口号
SSH执行以上命令,可以查看到8080端口正在被哪个进程使用。假设进程号为 1777。
查看进程的详细信息
ps 1777
SSH执行以上命令。查看相应进程号的程序详细路径
需要手动结束进程方法(杀掉进程):
kill -9 1777 #杀掉编号为1777的进程(请根据实际情况输入)
二:Cenots7默认防火墙firewalld关闭,并开启iptables
如果是CentOS7.x系统查看默认防火墙firewalld是否开启:
firewall-cmd --state
running 状态即防火墙已经开启 没开启就显示norunning
停止并屏蔽Centos7自带的防火墙firewalld:
systemctl status firewalld //查看状态
systemctl stop firewalld
systemctl mask firewalld //屏蔽FirewallD服务,如果需要取消屏蔽呢就是用systemctl unmask firewalld
systemctl disable firewalld //删除开机启动
安装iptables-services软件包:
yum install iptables-services
在引导时启用iptables服务:
systemctl enable iptables
启动iptables服务:
systemctl start iptables
增加防火墙规则(这里的20300是我们后面要修改的SSH的新端口)方法一例:
iptables -I INPUT -p tcp -m state --state NEW -m tcp --dport 20300 -j ACCEPT
保存防火墙规则:
service iptables save
或
/usr/libexec/iptables/iptables.init save
查看iptables开放的端口:
iptables -nL --line-number
或查看iptables列表:
iptables -L
管理iptables服务命令:
systemctl stop|start|restart iptables
修改或查看防火墙配置文件方法:
vi /etc/sysconfig/iptables
三:防火墙iptables规则深入教程
打开iptables防火墙:
chkconfig iptables on
关闭iptables防火墙:
chkconfig iptables off
或iptables -nL --line-number
注意:开放端口要加到reject-with icmp-port-unreachable这个规则前面
管理iptables服务命令:
systemctl stop iptables 、 systemctl start iptables 、 systemctl restart iptables
修改或查看防火墙配置文件:
vi /etc/sysconfig/iptables
六:修改SSH端口(默认端口是22,为了安全修改下)
vi /etc/ssh/sshd_config
#Port 22
去掉#,改成
Port 20300
保存
重启sshd服务(重启前要将20300端口加到防火墙中开放):
systemctl restart sshd.service
会报错:
Job for sshd.service failed because the control process exited with error code. See “systemctl status sshd.service” and “journalctl-xe” for details.
原因:
selinux不允许自定义sshd服务设置端口放行
但我们不能把selinux关闭了,会造成服务器安全性能下降
查看selinux状态:
getenforce
如果是Enforcing就是启用,否则请启用selinux:
setenforce 1
查看selinux中sshd服务放行的端口号:
semanage port -l | grep ssh
先安装SELinux的管理工具semanage和依赖包policycoreutils-python:
yum provides semanage
yum install policycoreutils-python
查看selinux中sshd服务放行的端口号:
semanage port -l | grep ssh
添加自定义sshd服务端口至selinux中:
semanage port -a -t ssh_port_t -p tcp 20300
再次查看selinux中sshd服务放行的端口号:
semanage port -l | grep ssh
重启sshd服务:
systemctl restart sshd.service
这样就可以使用新的SSH端口20300
