перенаправить bash вывод скрипта в файл журнала, исключая меню - PullRequest
0 голосов
/ 20 июня 2020

сначала спасибо за помощь очень ценю, у меня есть сценарий bash простой, он читает список серверов, список команд и список команд отката, скрипт работает нормально,

но моя проблема связана с журналом, поэтому я хочу записывать вывод на консоли в файл журнала. проблема в том, что когда я открываю файл журнала, я вижу там меню с журналом, любую помощь для исключения меню из файла журнала,

для экспорта журнала с использованием

exec > >(tee -a ${log_file} )
exec 2> >(tee -a ${log_file} >&2)

после выполнения сценария (код ниже) вот что я вижу:

**************************************************************
              test script
**************************************************************
** 1) Test ip connectivity for all the servers.             **
** 2) Display the default config before apply the hardening.** 
** 3) Executing the hardening changes.                      **
** 4) Display the new values after the hardening applied.   **
** 5) Rollback to the default config.                       **
**************************************************************
Please enter a menu option and enter or x to exit. 3
Option 3 : Executing config.

Когда я проверяю журнал, я вижу хороший журнал, но с меню: (

[root@host1 newscript]# 
[root@host1 newscript]# 
[root@host1 newscript]# cat Hardening_log.txt 

**************************************************************
              test script
**************************************************************
** 1) Test ip connectivity for all the servers.             **
** 2) Display the default config before apply the hardening.** 
** 3) Executing the hardening changes.                      **
** 4) Display the new values after the hardening applied.   **
** 5) Rollback to the default config.                       **
**************************************************************
Please enter a menu option and enter or x to exit. 
Option 1 : Test ip connectivity for all the servers.

[ UP ] Server : 192.168.0.182 
 
[ UP ] Server : 192.168.0.183 
 
**************************************************************
              test script
**************************************************************
** 1) Test ip connectivity for all the servers.             **
** 2) Display the default config before apply the hardening.** 
** 3) Executing the hardening changes.                      **
** 4) Display the new values after the hardening applied.   **
** 5) Rollback to the default config.                       **
**************************************************************
Please enter a menu option and enter or x to exit. 
Option 2 : Display the config.
___________________________________________________________________________________________________________________________________________________________________________

Starting executing commands for : 192.168.0.182 
___________________________________________________________________________________________________________________________________________________________________________


[ PASSED ] Command executed : cat /etc/ssh/sshd_config | grep MaxAuthTries
Printing commands result : #MaxAuthTries 6

[ PASSED ] Command executed : chage -l sofiane | grep "Account expires"
Printing commands result : Account expires                                              : Dec 31, 2022

___________________________________________________________________________________________________________________________________________________________________________

Starting executing commands for : 192.168.0.183 
___________________________________________________________________________________________________________________________________________________________________________


[ PASSED ] Command executed : cat /etc/ssh/sshd_config | grep MaxAuthTries
Printing commands result : #MaxAuthTries 6

[ PASSED ] Command executed : chage -l sofiane | grep "Account expires"
Printing commands result : Account expires                                              : Dec 31, 2022


**************************************************************
              test script
**************************************************************
** 1) Test ip connectivity for all the servers.             **
** 2) Display the default config before apply the hardening.** 
** 3) Executing the hardening changes.                      **
** 4) Display the new values after the hardening applied.   **
** 5) Rollback to the default config.                       **
**************************************************************
Please enter a menu option and enter or x to exit. 
Option 3 : Executing config.
___________________________________________________________________________________________________________________________________________________________________________

Starting executing commands for : 192.168.0.182 
___________________________________________________________________________________________________________________________________________________________________________


[ PASSED ] Command executed : sed -i '/^#MaxAuthTries/s/6/2/' /etc/ssh/sshd_config

[ PASSED ] Command executed : /usr/bin/chage -E 2021-12-31 sofiane

___________________________________________________________________________________________________________________________________________________________________________

Starting executing commands for : 192.168.0.183 
___________________________________________________________________________________________________________________________________________________________________________


[ PASSED ] Command executed : sed -i '/^#MaxAuthTries/s/6/2/' /etc/ssh/sshd_config

[ PASSED ] Command executed : /usr/bin/chage -E 2021-12-31 sofiane


**************************************************************
              test script
**************************************************************
** 1) Test ip connectivity for all the servers.             **
** 2) Display the default config before apply the hardening.** 
** 3) Executing the hardening changes.                      **
** 4) Display the new values after the hardening applied.   **
** 5) Rollback to the default config.                       **
**************************************************************
Please enter a menu option and enter or x to exit.

большое спасибо sh за помощь

он мой код:

#!/bin/bash
clear
#Echo with colors*****************
normal=`echo "\033[m"`
menu=`echo "\033[36m"` #Blue
number=`echo "\033[33m"` #yellow
bgred=`echo "\033[41m"`
fgred=`echo "\033[31m"`
PASSED=$'\e[32mPASSED\e[0m'
#*********************************

servers="servers.txt"
commands="commands.txt"
log_file="log.txt"
now=$(date +"%F_%H-%M")





exec > >(tee -a ${log_file} )
exec 2> >(tee -a ${log_file} >&2)

while read server; do
            #Title
            printf '%*s\n'  "${COLUMNS:-$(tput cols)}" '' | tr ' ' _
            printf "\n"
            printf  "Starting executing commands for : $server \n" 
            printf '%*s\n'  "${COLUMNS:-$(tput cols)}" '' | tr ' ' _
            printf "\n"
            #Commands BEGIN.========================================================
            #'ssh $server "hostname" < /dev/null;'
            printf "\n"
                while read command; do
                    printf '[ %s ] Command executed : %s\n' "$PASSED" "$command"
                    printf "Printing commands result : " & ssh $server $command  < /dev/null;
                    printf "\n"
                done < $commands
 done < $servers

mv log.txt $now"-log.txt"

            #Commands END.==========================================================




#!/bin/bash
clear
#Colors*****************
normal=`echo "\033[m"`
menu=`echo "\033[36m"` #Blue
number=`echo "\033[33m"` #yellow
bgred=`echo "\033[41m"`
fgred=`echo "\033[31m"`
PASSED=$'\e[32mPASSED\e[0m'
UP=$'\e[32mUP\e[0m'
DOWN=$'\e[31mDOWN\e[m'
#*********************************
#Files needed*****************
servers="servers.txt"
commands="execute.txt"
default_config="check_default.txt"
rollback="roll_back.txt"
log_file="log.txt"
now=$(date +"%F_%H-%M")
#*****************************

#To log the output*****************
log_file=Hardening_log.txt
exec > >(tee -a ${log_file} )
exec 2> >(tee -a ${log_file} >&2)
#*****************************

show_menu(){
    normal=`echo "\033[m"`
    menu=`echo "\033[36m"` #Blue
    number=`echo "\033[33m"` #yellow
    bgred=`echo "\033[41m"`
    fgred=`echo "\033[31m"`
    printf "\n${menu}**************************************************************${normal}\n"
    printf "              test script"
    printf "\n${menu}**************************************************************${normal}\n"
    printf "${menu}**${number} 1)${menu} Test ip connectivity for all the servers.             **${normal}\n"
    printf "${menu}**${number} 2)${menu} Display the default config before apply the hardening.** ${normal}\n"
    printf "${menu}**${number} 3)${menu} Executing the hardening changes.                      **${normal}\n"
    printf "${menu}**${number} 4)${menu} Display the new values after the hardening applied.   **${normal}\n"
    printf "${menu}**${number} 5)${menu} Rollback to the default config.                       **${normal}\n"
    printf "${menu}**************************************************************${normal}\n"
    printf "Please enter a menu option and enter or ${fgred}x to exit. ${normal}"
    read opt
}

option_picked(){
    msgcolor=`echo "\033[01;31m"` # bold red
    normal=`echo "\033[00;00m"` # normal white
    message=${@:-"${normal}Error: No message passed"}
    printf "${msgcolor}${message}${normal}\n"
}

clear
show_menu
while [ $opt != '' ]
    do
    if [ $opt = '' ]; then
      exit;
    else
      case $opt in
        1) clear;
            option_picked "Option 1 : Test ip connectivity for all the servers.";
                cat servers.txt |  while read output
                do
                        ping -c 2 "$output" > /dev/null
                            if [ $? -eq 0 ]; then
                        printf '\n'
                        printf '[ %s ] Server : %s\n ' "$UP" "$output "
                            else
                        printf '\n'
                        printf '[ %s ] Server : %s\n ' "$DOWN" "$output "
                        fi
                done
            show_menu;
        ;;
        2) clear;
            option_picked "Option 2 : Display the config.";
                while read server; do
            #Title
            printf '%*s\n'  "${COLUMNS:-$(tput cols)}" '' | tr ' ' _
            printf "\n"
            printf  "Starting executing commands for : $server \n" 
            printf '%*s\n'  "${COLUMNS:-$(tput cols)}" '' | tr ' ' _
            printf "\n"
            #Commands BEGIN.========================================================
            #'ssh $server "hostname" < /dev/null;'
            printf "\n"
                    while read command; do
                        printf '[ %s ] Command executed : %s\n' "$PASSED" "$command"
                        printf "Printing commands result : " & ssh $server $command  < /dev/null;
                        printf "\n"
                    done < $default_config
                done < $servers
            show_menu;
        ;;
        3) clear;
            option_picked "Option 3 : Executing config.";
                while read server; do
            #Title
            printf '%*s\n'  "${COLUMNS:-$(tput cols)}" '' | tr ' ' _
            printf "\n"
            printf  "Starting executing commands for : $server \n" 
            printf '%*s\n'  "${COLUMNS:-$(tput cols)}" '' | tr ' ' _
            printf "\n"
            #Commands BEGIN.========================================================
            #'ssh $server "hostname" < /dev/null;'
            printf "\n"
                    while read command; do
                        printf '[ %s ] Command executed : %s\n' "$PASSED" "$command"
                        #printf "Printing commands result : " & ssh $server $command  < /dev/null;
                        ssh $server $command  < /dev/null;
                        printf "\n"
                    done < $commands
                done < $servers
            show_menu;
        ;;
        4) clear;
            option_picked "Option 4 : Display the new config after the hardening applied.";
                while read server; do
            #Title
            printf '%*s\n'  "${COLUMNS:-$(tput cols)}" '' | tr ' ' _
            printf "\n"
            printf  "Starting executing commands for : $server \n" 
            printf '%*s\n'  "${COLUMNS:-$(tput cols)}" '' | tr ' ' _
            printf "\n"
            #Commands BEGIN.========================================================
            #'ssh $server "hostname" < /dev/null;'
            printf "\n"
                    while read command; do
                        printf '[ %s ] Command executed : %s\n' "$PASSED" "$command"
                        printf "Printing commands result : " & ssh $server $command  < /dev/null;
                        printf "\n"
                    done < $default_config
                done < $servers
            show_menu;
        ;;
        5) clear;
            option_picked "Option 5 : Rollback to the default config.";
                while read server; do
            #Title
            printf '%*s\n'  "${COLUMNS:-$(tput cols)}" '' | tr ' ' _
            printf "\n"
            printf  "Starting executing commands for : $server \n" 
            printf '%*s\n'  "${COLUMNS:-$(tput cols)}" '' | tr ' ' _
            printf "\n"
            #Commands BEGIN.========================================================
            #'ssh $server "hostname" < /dev/null;'
            printf "\n"
                    while read command; do
                        printf '[ %s ] Command executed : %s\n' "$PASSED" "$command"
                        #printf "Printing commands result : " &
                        ssh $server $command  < /dev/null;
                        printf "\n"
                    done < $rollback
                done < $servers
            show_menu;
        ;;
        x)exit;
        ;;
        \n)exit;
        ;;
        *)clear;
            option_picked "Pick an option from the menu";
            show_menu;
        ;;
      esac
    fi
done

1 Ответ

0 голосов
/ 20 июня 2020

Возможно дублировать начальный стандартный вывод в другой дескриптор файла (например, 3) и отправить меню на этот дескриптор. После настройки (exec 3>&1) добавьте> & 3 к любой команде, вывод которой НЕ должен go в файл журнала.

...

  # Keep handle to original stdout on fd 3
exec 3>&1
  # capture stdout/stderr to log file
exec > >(tee -a ${log_file} )
exec 2> >(tee -a ${log_file} >&2)

...
function show_menu {
}

...
  # Output the clear seq and the menu to terminal only
clear >&3
show_menu >&3

  # Rest of the code
while [ $opt != '' ] 
...
done
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...