Shell脚本:在用户主目录中运行命令
时间:2020-03-05 15:31:47 来源:igfitidea点击:
在所有用户的主目录中运行Linux命令并输出其结果的Shell脚本。
脚本接受用户名和命令作为参数。
用于运行命令用户主目录的Shell脚本
#Next line tell with shell to use #!/bin/bash #we store in variable path to file UserListFile=/tmp/user.list #We create function with name Usage Usage () { #printing help echo "./exec_home.sh ls Please enter users, type exit to exit sshd yevhen exit Runnig ls inside /var/run/sshd Runnig ls inside /home/yevhen Desktop Downloads examples.desktop Pictures Templates Documents Dropbox Music Public Videos- execute command in all HOME directories usage: ##代码## [-a] command [arg ...] -a: process HOME directories of all users The given command will be executed with the arguments specified in the home directory of users. " #exit from program exit 1 #end of function } #we check if there less than 1 parameter if [ $# -lt 1 ] then #if less – print help Usage #in other case else #we check passed parameters, starting from first case "" in #if parameter -a then we write to All variable value true -a) All=true #removing parameter shift ;; #if parameter starting with -, and not -a, we print help -*) Usage ;; #exit from case esac #exit from fi loop fi #we check if user pass -a as parameter if [ "$All" = true ] #if -a passed then #we get list of all users cat /etc/passwd | cut -d':' -f1 | sed -e 's/://g' > $UserListFile # in other case else #print message echo "Please enter users, type [ to exit" #cleaning file with userlist echo -n > $UserListFile #starting while loop to read users while read UserName Rest do #if user print [ to exit loop if [ $UserName = "[" ]; then #exit from loop break #if user print other data else #we check if user put any symbol test -z "$UserName" && continue #we check if user exist grep "^$UserName" /etc/passwd > /dev/null || { #if not exist print message to user echo "Can't find user ${UserName}; ignored." #we continue loop continue } #if user exist – we store it to userfile echo $UserName >> $UserListFile #exit of if loop fi #exit from reading user input done #exit from if loop fi #just print empty line echo "" #stop all other parameters as command we need to run Command="$@" #getting list of users UserList=`cat $UserListFile` #getting user one by one from list for user in ${UserList} do #one more empty line echo "" #getting user home directory HomeDir=`grep "^$user" /etc/passwd | cut -d":" -f6` # we check if we have read and execute permissions to cd and run command [ -r "$HomeDir" -a -x "$HomeDir" ] || { # if not just warn user echo "Read or execute of folder $HomeDir denied" continue #exit of check } #we telling user about what command we run and inside what directory echo "Runnig $Command inside $HomeDir" #entering home cd $HomeDir #running command $Command done #cleaning, removing temp files rm -rf $UserListFile
脚本输出
##代码##