Linux中关闭一个端口对应的所有程序

有时,我们在服务器上开启了一个Django或其它任务,占用了服务器的一个端口,而当我们想将其关闭的时候,发现其对应着许多进程,这时,要将其一个一个地找出来并且kill掉还是比较麻烦的,所以写了下面这个python脚本来处理这样的任务。

import commands
import os


def kill_all_django_processes(port = 90):
    result = os.popen('ps aux | grep python')

    pid_list = []

    print "-" * 60 + "\nInformation for all processes corresponding to port %d" % port

    for line in result:
        line = line.replace("\n", "")
        strs = line.split()
        # if strs[-2] == "runserver" and strs[-3] == "manage.py":
        if strs[-1] == ("0.0.0.0:%d" % port):
            print line
            pid_list.append(strs[1])
    
    print "-" * 60 + "\nall pid to kill:"
    print pid_list
    print "-" * 60

    for pid in pid_list:
        os.popen('kill -9 %s' % str(pid))


if __name__ == "__main__":
    kill_all_django_processes(90)

输出:

------------------------------------------------------------
Information for all processes corresponding to port 90
root     25120  0.0  0.1 431956 33464 pts/4    Sl   15:54   0:00 python manage.py runserver 0.0.0.0:90
root     25129  2.9  0.2 1598932 55804 pts/4   Sl   15:54   0:17 /root/DjangoEnv/bin/python manage.py runserver 0.0.0.0:90
root     25155  0.0  0.2 1213144 44396 pts/4   Sl   15:54   0:00 /root/DjangoEnv/bin/python manage.py runserver 0.0.0.0:90
root     25156  0.2  0.2 1344984 45684 pts/4   Sl   15:54   0:01 /root/DjangoEnv/bin/python manage.py runserver 0.0.0.0:90
root     25157  0.1  0.2 1346264 47432 pts/4   Sl   15:54   0:00 /root/DjangoEnv/bin/python manage.py runserver 0.0.0.0:90
------------------------------------------------------------
all pid to kill:
['25120', '25129', '25155', '25156', '25157']
------------------------------------------------------------

注意,程序要在需要处理的服务器上直接运行,其中主函数输入的参数是要kill掉的程序所占用的端口号,比如,笔者这里是要kill掉90端口的所有python程序,所以输入的参数是90,然后程序发现有5个进程在占用90端口,并将其详细输出,之后将其对应的进程kill掉。

posted @ 2019-05-22 16:08  点点爱梦  阅读(809)  评论(0编辑  收藏  举报