【shell指令碼】修改ssh埠
阿新 • • 發佈:2020-12-10
技術標籤:Linux
#!/bin/bash
#說明:SSHD服務預設監聽埠是22,如果你不強制說明別的埠,”Port 22”注不註釋都是開放22訪問埠
portset=$1
if [ ! -z "$portset" ];then
inputportlen=`echo "$portset"|sed 's/[0-9]//g'`
#$portlen為空,說明輸入的是一個整數
if [ "$inputportlen" == "" ] && [ "$portset" -gt "1" ] && [ "$portset" -lt "65535" ];then #判斷使用者輸入是否是1-65535之間個一個整數
echo "--> 埠號輸入正確"
backup_sshd_config ()
{
#獲取當前日期和時間
dateAndTime=`date +"%Y%m%d%H%M%S"`
echo "--> 開始備份/etc/ssh/sshd_config檔案"
/bin/cp /etc/ssh/sshd_config /etc/ssh/sshd_config.bak.$dateAndTime && echo "--> /etc/ssh/sshd_config檔案備份成功" || { echo "--> /etc/ssh/sshd_config檔案備份失敗"; ExitCode=1; }
bakfile=`/bin/ls /etc/ssh | grep $dateAndTime`
echo "--> /etc/ssh/sshd_config檔案備份結束,檔名為:$bakfile"
}
sshd_service_restart ()
{
systemver=`cat /etc/redhat-release| sed -r 's/.* ([0-9]+)\..*/\1/'`
if [[ $systemver = "6" ]];then
service sshd restart && echo "--> sshd服務重啟完成" || { echo "--> sshd服務重啟失敗"; ExitCode=1; }
else
systemctl restart sshd.service && echo "--> sshd服務重啟完成" || { echo "--> sshd服務重啟失敗"; ExitCode=1; }
fi
}
#獲取sshd執行程序ID
getSSHProcessID=`ps -ef | grep sshd | awk '{if($3=="1" && $8=="/usr/sbin/sshd")print $2}'`
if [ "$getSSHProcessID" != "" ];then #$getSSHProcessID不為空說明sshd服務啟動正常
#獲取sshd開啟的埠列表
getSSHOpenPortList=`netstat -anop | grep $getSSHProcessID | grep ^tcp | grep LISTEN | grep -v ::: | grep sshd | awk '{print $4}' | awk -F ":" '{print $2}' | uniq | xargs echo`
#計算sshd開啟的埠數量
getSSHOpenPortCount=`netstat -anop | grep $getSSHProcessID | grep -v ::: | grep sshd | grep LISTEN | awk '{print $4}' | awk -F ":" '{print $2}' | uniq | wc -l`
if [ "$getSSHOpenPortCount" == "1" ] && [ "$getSSHOpenPortList" == "$portset" ];then #如果當前只打開了一個埠,且與希望設定的埠相同,無需做任何配置
echo "sshd服務執行埠為$portset,無需修改!!!"
exit 0
elif [ "$getSSHOpenPortCount" == "1" ] && [ "$getSSHOpenPortList" == "22" ];then #如果埠為22說明使用的是預設的#Port 22設定,則增加Port設定
listenportlent=`netstat -ano | grep -w LISTEN | grep -w $portset`
if [ "$listenportlent" == "" ];then #判斷埠是否被佔用
#備份配置檔案
backup_sshd_config
echo "Port $portset" >> /etc/ssh/sshd_config && echo "--> 修改sshd執行埠為$runport成功" || { echo "--> 修改sshd執行埠為$runport失敗"; ExitCode=1; }
#重啟sshd服務
sshd_service_restart
else
echo "埠已經被佔用,請重新輸入"
exit 1
fi
else #當打開了一個或多個非22,且與設定的埠不同時
listenportlent=`netstat -ano | grep -w LISTEN | grep -w $portset`
if [ "$listenportlent" == "" ];then #判斷埠是否被佔用
#備份sshd配置檔案
backup_sshd_config
for sshport in $getSSHOpenPortList
do
/bin/sed -i "s/$sshport/$portset/g" /etc/ssh/sshd_config
done
#重啟sshd服務
sshd_service_restart
else
echo "埠已經被佔用,請重新輸入"
exit 1
fi
fi
else
echo "--> sshd服務未啟動"
exit 1
#嘗試重啟sshd服務
sshd_service_restart
fi
else
echo "--> 請輸入1-65535之間的一個整數"
exit 1
fi
else
echo "--> 請輸入埠號"
exit 1
fi
將程式碼儲存到test.sh,賦權,即可執行