[Share Experiences] 杀死占用端口的程序
Tofloor
poster avatar
酷谷的谷子
deepin
2023-07-07 01:10
Author

其它功能脚本:https://note.youdao.com/s/BBlPM7OJ

./lsofPORT 端口 用户密码

使用方法 普通用户下需要输入用户密码
普通用户下 ./lsofPORT 12345 abc123
ROOT用户下 ./lsofPORT 12345


注意事项:

请勿使用 sudo ./lsofPORT 应为在普通用户下密码已经作为第二个参数传递到了脚本内部

该脚本应为涉及到用户密码为了安全一点请使用shc加密处理


把下面代码保存到文本文件

#!/bin/bash
PORT="$1"
MYqassword="$2"
#---------------------------
#./lsofPORT 端口 密码
#普通用户下   ./lsofPORT 12345 abc123
#ROOT用户下  ./lsofPORT 12345
#---------------------------
NAME_ID=`getent passwd ${SUDO_UID:-$(id -u)} | cut -d: -f 6`
MY_USER_DIR="${NAME_ID}"
NAME='root'
if [[ ! X${NAME} = X${MY_USER_DIR} ]];then
   # 普通用户
   mkdir -p /tmp/lsofPORT
   shijian=`date +%Y年%m月%d日%H:%M:%S`
   echo "${MYqassword}" | sudo -S $shijian > /dev/null 2>&1
   sudo lsof -i :${PORT}|grep "${PORT}"|awk '{print $1}' > ${MY_USER_DIR}/占用端口的程序.txt
   sudo lsof -i :${PORT}|grep "${PORT}"|awk '{print $2}' > /tmp/lsofPORT/lsofPORT.log
   kill_X=`cat /tmp/lsofPORT/lsofPORT.log`
   sudo kill -9 ${kill_X}
   sudo rm -rf /tmp/lsofPORT
else
   # root
   lsof -i :${PORT}|grep "${PORT}"|awk '{print $1}' > ${MY_USER_DIR}/占用端口的程序.txt
   kill_X=`lsof -i :${PORT}|grep "${PORT}"|awk '{print $2}'`
   kill -9 ${kill_X}
fi
#清空终端操作记录
#>${MY_USER_DIR}.bash_history
#history -c
exit 0
Reply Favorite View the author
All Replies
阿尼樱奈奈
Moderator
2023-07-07 01:10
#1

like

Reply View the author
enforcee
deepin
2023-07-07 04:11
#2

如果你要直接把密码放到命令里面,那么直接查看shell输入命令的历史记录就有了

doubt

你为什么要这么做呢

Reply View the author
dgmenghuan
deepin
2023-07-07 17:45
#3

kill就行了,这么麻烦干什么

Reply View the author
酷谷的谷子
deepin
2023-07-07 19:15
#4
dgmenghuan

kill就行了,这么麻烦干什么

我写脚本的目的就是不想记住任何命令

不然你要记忆2个命令 才能最后 kill ID 尤其是管道命令一个接一个不好记忆,

Reply View the author
酷谷的谷子
deepin
2023-07-07 19:17
#5
enforcee

如果你要直接把密码放到命令里面,那么直接查看shell输入命令的历史记录就有了

doubt

你为什么要这么做呢

这个有时候脚本考虑不到那么多,在历史记录里 只要把脚本名字改一下就不好判断是做了什么,也可以在脚本后面加上清空命令就没有历史记录了

把密码写在脚本里面也可以,只不过没有必要

Reply View the author
ThinKinG
deepin testing team
2023-07-21 22:35
#6

很久没看到带注释的脚本了,大佬👍

Reply View the author