포트 상태를 확인하는 셸 스크립트가 있습니다. 포트가 사용 중인지 확인한 후 종료됩니다.
#check port and kill
checkPort(){
check=$(sudo netstat -nlpt | grep 2020 | awk '{print $6}')
word="LISTEN"
killProcess=$(sudo netstat -nlpt | grep 2020 | awk '{print $7}' |
sed 's/.\{5\}$//' | sort -u | xargs -t kill -9)
if [[ "$check" == "$word" ]];
then
echo "killing the port 2020"
$killProcess
else
echo "Not Listen"
fi
}
$killProcess
변수를 실행할 때 오류가 발생합니다. 그러나 조건 sudo netstat -nlpt | grep 2020 | awk '{print $7}' | sed 's/.\{5\}$//' | sort -u | xargs -t kill -9
내부에 전체 명령을 넣으면 if
정상적으로 작동합니다. 여기서 실수는 무엇입니까?
내가 얻는 오류 :
kill -9
Usage:
kill [options] <pid|name> [...]
Options:
-a, --all do not restrict the name-to-pid conversion to processes
with the same uid as the present process
-s, --signal <sig> send specified signal
-q, --queue <sig> use sigqueue(2) rather than kill(2)
-p, --pid print pids without signaling them
-l, --list [=<signal>] list signal names, or convert one to a name
-L, --table list signal names and numbers
-h, --help display this help and exit
-V, --version output version information and exit
나는 넣어 xargs -i kill -kill {}
대신 xargs kill -9
. 잘 작동합니다. 좋은 습관입니까?
구문 var=$(command)
이 실행 command
되고 출력이 변수에 할당 됩니다 $var
. 이것은 스크립트에서 다음 줄을 의미합니다.
killProcess=$(sudo netstat -nlpt | grep 2020 | awk '{print $7}' |
sed 's/.\{5\}$//' | sort -u | xargs -t kill -9)
것입니다 항상 이 파이프 라인 끝 실행 kill
명령을하고, 그 출력을 지정합니다 $killprocess
. 때문에 kill
명령이 더 출력이 없습니다,이 라인은 나중에 아무것도하지 않을 것입니다 :
$killProcess
당신이 원하는 것은 killProcess="sudo netstat ... | xargs -t kill -9
. 그러나 명령과 관련된 다른 문제도 있습니다. 우선 2020을 포함하는 모든 라인과 일치하지만 2020
포트가있는 경우 만 원합니다 . 대신 PID라면 어떨까요?
다음은 몇 가지 변경 사항이있는 함수의 작동 버전입니다.
checkPort(){
## Get the target port. If none is given, default to 2020
targetPort=${1:-2020}
## Collect the PID(s) that are listening on the port in the
# array 'pids'.
pids=( $(sudo netstat -nlpt | awk "\$4~/:$targetPort\$/{print \$7}" |
sed 's|/.*||'))
## If no processes were listening, move on
if [[ -z ${pids[0]} ]];
then
echo "No process listening on port $targetPort"
## If any processes were listening, kill them.
else
echo "killing process(es) listening on port $targetPort"
## First, try to kill the process gracefully
kill "${pids[@]}"
## Check if any are still running
for pid in "${pids[@]}"; do
## If it is still running
if kill -0 "$pid"; then
## Kill it with fire
kill -9 "$pid"
fi
done
fi
}
이제 매개 변수를 사용할 수 있으므로 checkport
포트 2020을 확인하기 위해 실행하고 checkport 22
포트 22를 확인합니다. 또한 먼저 정상적으로 종료하려고 시도하고 ( kill -9
절대적으로 필요한 경우가 아니면 항상 피해야 함 ) kill -9
실패한 경우 에만 사용 합니다.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다