How to achieve a SysAdmin Terminal applying Shell Scripting

El Shell scripting, It refers to the execution of complex orders about him GNU / Linux Terminal (Console), it is very useful to automate routine and important activities within our GNU / Linux Operating System, which allows us to optimize our Resources and Time.

Selection_007

Therefore, its use from the terminal allows us to execute complex command commands manually or automatically through scripts or as programmed routines within automatically loaded files or scheduled tasks within the Operating System. GNU / Linux. And for a Medium User, Advanced or SysAdmin el schedule (automate) tasks, alerts and / or notices on a Host (PC / Server) to save Hours / Labor Of manual or face-to-face execution, it is something basic and essential for the good performance of your work as a high-level professional.

Next, we will show how a data (value / parameter) previously stored in a variable by a command Bash shell or compatible, it can be displayed in the terminal of your GNU / linux Operating System, in a practical and simple way. In addition to tuning the Terminal prompt.

First Step: Edit your user's .bashrc

With the editor of your choice (vi, nano, etc.) edit the .bashrc file of your user that must be located within the home of the same, that is, in for example: "/ Home / my_user".

Insert the content of each one of the following lines and all those additional ones that you consider convenient to show to the user when executing a user terminal:

sleep 3

clear

########################### PARÁMETROS DE MONITOREO ###########################

NOMBRE_SISTEMA=$(cat /etc/os-release | grep NAME | grep -v "VERSION" | sed -n '2p' | cut -f2 -d\")
VERSION_SISTEMA=$(cat /etc/os-release | grep VERSION= | sed -n '1p' | sed 's/VERSION=//' | sed 's/"//g')

FABRICANTE_CPU=$(grep "vendor_id" /proc/cpuinfo | sed q | awk '{print $3}')
MODELO_CPU=$(grep "model name" /proc/cpuinfo | sed q | cut -d ":" -f 2 | awk '{print $0}')
NUM_CPU=$(grep "processor" /proc/cpuinfo | sort -r | sed q | awk '{print $3}' | echo `expr $NUM_CPU + 1`)
NUCLEO_CPU=$(grep "cpu cores" /proc/cpuinfo | sed q | awk '{print $4}')
CACHE_CPU=$(grep "cache size" /proc/cpuinfo | sed q | cut -d ":" -f 2 | awk '{print $0}')

clear

printf %80s |tr " " "="
echo ""
echo "      ADVERTENCIA - USTED HA INICIADO SESIÓN EN EL EQUIPO SERVIDOR DE LA      "
echo "                             EMPRESA INSTITUCIÓN XYZ                                "
echo "       RECUERDE TENER EXTREMO CUIDADO CON CUALQUIER CAMBIO A REALIZAR        "
printf %80s |tr " " "="
echo ""
printf %80s |tr " " "="
echo ""
echo "                         ESTE EQUIPO TIENE INSTALADO                         "
echo "                                                                             "
echo "TIPO DE S.O.: <"`uname -o`">                                                 "
echo "NOMBRE / VERSIÓN DEL S.O.: &lt;"$NOMBRE_SISTEMA"&gt; / &lt;"$VERSION_SISTEMA"&gt;        "
echo "KERNEL / ARQUITECTURA: <"`uname -r`"> / <"`uname -m`">                       "
echo "INFO DEL CPU: ("$FABRICANTE_CPU") / ("$MODELO_CPU") / ("$NUM_CPU") / ("$NUCLEO_CPU") / ("$CACHE_CPU")"
printf %80s |tr " " "="
echo ""
echo ""

PS1="\[\e[33;1m\]┌─( \[\e[34;1m\]\u@\h\[\e[37;1m\] ) * * * * \d - \t * * * * { \[\e[31;1m\]\w\[\e[33;1m\] }\n└──┤ \[\e[32m\]# "

`

Second Step: Edit the root .bashrc

Again with the editor already used edit the .bashrc file of the superuser root which must be located within the path / root of it.

Insert the content of each one of the following lines and all those additional ones that you consider convenient to show to the user when executing a user terminal:

########################### PARÁMETROS DE MONITOREO ###########################

alias cc='clear'

PROXY=$(route -n | sed -n '3p' | awk '{print $2}')

IP_SERVIDOR_DNS=$(cat /etc/resolv.conf | sed '1 d' | grep nameserver | sed -n '1p' | awk '{print $2}')
DOMINIO=$(cat /etc/resolv.conf | sed '1 d' | grep search | sed -n '1p' | awk '{print $2}')

DATA_USUARIO1=$(du -sh /home/ | sort -r | awk '{print $1}')
DATA_ROOT=$(du -sh /root | awk '{print $1}')
DATA_VAR=$(du -sh /var | awk '{print $1}')

MEM_TOTAL=$(free -h | sed '1 d' | grep Mem: | awk '{print $2}')
MEM_USADA=$(free -h | sed '1 d' | grep Mem: | awk '{print $3}')
MEM_LIBRE=$(free -h | sed '1 d' | grep Mem: | awk '{print $4}')
MEM_COMPARTIDA=$(free -h | sed '1 d' | grep Mem: | awk '{print $5}')
MEM_ALMACENADA=$(free -h | sed '1 d' | grep Mem: | awk '{print $6}')
MEM_CACHEADA=$(free -h | sed '1 d' | grep Mem: | awk '{print $7}')

PART1_TOTAL=$(df -h | sed '1 d' | grep disk | awk '{print $2}')
PART1_USADO=$(df -h | sed '1 d' | grep disk | awk '{print $3}')
PART1_DISPONIBLE=$(df -h | sed '1 d' | grep disk | awk '{print $4}')
PART1_PORCENTAJE=$(df -h | sed '1 d' | grep disk | awk '{print $5}')
PART1_PUNTOMONTAJE=$(df -h | sed '1 d' | grep disk | awk '{print $6}')

CARGA_1MIN=$(top -n 1 -b | grep "load average:" | awk '{print $12}' | sed 's/,//2')

CARGA_5MIN=$(top -n 1 -b | grep "load average:" | awk '{print $13}' | sed 's/,//2')
CARGA_15MIN=$(top -n 1 -b | grep "load average:" | awk '{print $14}' | sed 's/,//2')

USER_ONLINE=$(top -n 1 -b | grep "load average:" | awk '{print $8}')
PROC_ZOMBIE=$(top -n 1 -b | grep "zombie" | awk '{print $10}')

TIEMPO_ENCENDIDO=$(uptime | awk '{print $3,$4}' | cut -f1 -d,)

FABRICANTE_CPU=$(grep "vendor_id" /proc/cpuinfo | sed q | awk '{print $3}')
MODELO_CPU=$(grep "model name" /proc/cpuinfo | sed q | cut -d ":" -f 2 | awk '{print $0}')
NUM_CPU=$(grep "processor" /proc/cpuinfo | sort -r | sed q | awk '{print $3}' | echo `expr $NUM_CPU + 1`)
NUCLEO_CPU=$(grep "cpu cores" /proc/cpuinfo | sed q | awk '{print $4}')
CACHE_CPU=$(grep "cache size" /proc/cpuinfo | sed q | cut -d ":" -f 2 | awk '{print $0}')

IP_ETH0=$(ifconfig eth0 | grep inet | grep -v inet6 | cut -d ":" -f 2 | cut -d " " -f 1)
MAC_ETH0=$(ifconfig eth0 | sed -n '1p' | awk '{print $5}')

###############################################################################

if ping -c 1 8.8.8.8 &amp;&gt; /dev/null; then CONEXION_INTERNET=Habilitado; else CONEXION_INTERNET=Deshabilitado; fi

set -o vi

printf %80s |tr " " "="
echo ""
echo "      ADVERTENCIA - USTED HA INICIADO SESIÓN EN EL EQUIPO SERVIDOR DE LA      "
echo "                             EMPRESA INSTITUCIÓN XYZ                                "
echo "       RECUERDE TENER EXTREMO CUIDADO CON CUALQUIER CAMBIO A REALIZAR        "
printf %80s |tr " " "="
echo ""
printf %80s |tr " " "="
echo ""
echo "                    PARÁMETROS ACTUALES DE FUNCIONAMIENTO                    "
echo "                                                                             "
echo "MEMORIA TOTAL: ("$MEM_TOTAL") - MEMORIA USADA: ("$MEM_USADA") - MEMORIA LIBRE: ("$MEM_LIBRE")"
echo "DISCO PRINCIPAL: ("$PART1_TOTAL") - ESPACIO USADO: ("$PART1_USADO") - ESPACIO LIBRE: ("$PART1_DISPONIBLE") - %: ("$PART1_PORCENTAJE") - PARTICION: ("$PART1_PUNTOMONTAJE")"
echo "CARGA PROMEDIO DEL SISTEMA: 1 MIN ("$CARGA_1MIN") -  5 MIN ("$CARGA_5MIN") - 15 MIN ("$CARGA_15MIN")"
echo "USUARIOS CONECTADOS: ("$USER_ONLINE") -  PROCESOS ZOMBIES: ("$PROC_ZOMBIE")"
echo "TIEMPO ARRANQUE/ENCENDIDO: ("$TIEMPO_ENCENDIDO")                             "
echo "ESPACIO USADO: /home = ("$DATA_USUARIO1") /root = ("$DATA_ROOT") /var = ("$DATA_VAR")"
printf %80s |tr " " "="
echo ""
echo ""
PS1="\[\e[33;1m\]┌─( \[\e[34;1m\]\u@\h\[\e[37;1m\] ) * * * * \d - \t * * * * { \[\e[31;1m\]\w\[\e[33;1m\] }\n└──┤ \[\e[32m\]$ "

Third Step: Edit the root .bashrc

Log out and the terminal. Start it again and experience the changes. It should look similar to the one shown below, in the following images:

Step 1: Terminal startup

Step 2: Edit user .bashrc

Step 3: Content embedded in user .bashrc

Step 4: Root login

Step 5: Root login

Step 6: Edit root .bashrc file

Step 7: Edit root .bashrc file

Step 8: Edit root .bashrc file

Step 9: Demonstration example of a new Client Terminal

Step 10: Demonstration example of a new Client Terminal

Step 11: Demonstration example of a new Client Terminal

Step Four (optional): Tuning Aliases

Remember that the use of aliases within the .bashrc It can also save you a lot of writing time. Uncomment the ones that come by default within the .bashrc, such as:

alias ls='ls $LS_OPTIONS'
<strong>alias ll='ls $LS_OPTIONS -l'
<strong>alias l='ls $LS_OPTIONS -lA'

alias rm='rm -i'

And add the ones you consider necessary, as they are frequently used commands, such as:

alias cc='clear'

It is important, to know more in a self-taught way about variables, aliases, the .bashrc and the language bash-shell for a more advanced level of the terminal. The same can be achieved when starting remote sessions via ssh, which we can see later in other future publications.

I hope these little ones "Tips" make it easy for them to perform basic but useful optimizations, which are generally only reserved for experts in Technology, Computing, Free Software and GNU / Linux.

REMINDER: If any command line fails to execute or displays the correct value, be sure to manually test each section of the command prompt to try and adjust the values ​​or syntax of some variables.


Leave a Comment

Your email address will not be published. Required fields are marked with *

*

*

  1. Responsible for the data: Miguel Ángel Gatón
  2. Purpose of the data: Control SPAM, comment management.
  3. Legitimation: Your consent
  4. Communication of the data: The data will not be communicated to third parties except by legal obligation.
  5. Data storage: Database hosted by Occentus Networks (EU)
  6. Rights: At any time you can limit, recover and delete your information.

  1.   yippekay said

    Aliasing is the best. I do not think bad about some that include by default in bashrc: la (ls -a) and ll (ls -l). At the last I add the parameter -h.

    Other practical aliases:
    s = 'sudo'
    cd1 = 'cd ..'
    cd2 = 'cd ../ ..'
    rmd = 'rm -r' (I use it to remove directories with files)
    shutdown = 'sudo shutdown -h now'
    del = 'trash-put' (move files to trash, trash-cli package command)

  2.   toño said

    Since I saw this alias last year on Reddit it has been my favorite:
    alias fuck = 'sudo $ (history -p !!)'

  3.   Martin said

    The article and the appearance that it gives to the console is very good. Some contributions:
    - In Ubuntu the aliases can be placed in a separate file (.bash_aliases) in the rest of the distributions I don't know but it does it by adding the following lines in .bashrc:
    if [-f ~ / .bash_aliases]; then
    . ~ / .bash_aliases
    fi
    This allows to have the aliases more ordered and for the forgetful like me you can add this alias that shows the file listing the aliases:
    alias lsalias = 'more ~ ​​/ .bash_aliases'
    - I also have an infrequently used command text file (which I don't usually remember) called command_utiles.txt and that ready with the following alias: alias cutil = 'more ~ ​​/ command_utiles.txt'
    - More aliases I use:
    alias cdu = 'cd ~'
    alias lof = 'ls -lSr | more' # Shows files in detail ordered by size
    alias lod = 'du -sk * | sort -rn '# Show directories sorted by size
    alias deo = 'du -sh' # Estimate the space occupied by the indicated dir
    alias psa = 'ps -eafw | more '# Show all processes with more
    alias psg = 'ps -eafw | grep '# Show the indicated process
    - Finally, an alternative for users that I did:
    SYSTEM_NAME = $ (cat / etc / os-release | grep NAME | grep -v "VERSION" | sed -n '1p' | cut -f2 -d \ »)
    SYSTEM_VERSION = $ (cat / etc / os-release | grep VERSION = | sed -n '1p' | sed 's / VERSION = //' | sed 's / »// g')
    MANUFACTURER_CPU = $ (grep "vendor_id" / proc / cpuinfo | sed q | awk '{print $ 3}')
    CPU_MODEL = $ (grep "model name" / proc / cpuinfo | sed q | cut -d ":" -f 2 | awk '{print $ 0}')
    NUM_CPU = $ (grep "processor" / proc / cpuinfo | sort -r | sed q | awk '{print $ 3}' | echo expr $NUM_CPU + 1)
    NUCLEO_CPU = $ (grep "cpu cores" / proc / cpuinfo | sed q | awk '{print $ 4}')
    CACHE_CPU = $ (grep "cache size" / proc / cpuinfo | sed q | cut -d ":" -f 2 | awk '{print $ 0}')
    USER_Data = $ (du -sh ~ | sort -r | awk '{print $ 1}')

    clear
    printf% 130s | tr »» «=»
    threw out ""
    echo «DATE:«date +%c --date='+1 year'
    echo «KERNEL:«uname -o»<«uname -r«> <«uname -m«>»
    echo "DISTRIBUTION:" $ SYSTEM_NAME "" $ SYSTEM_VERSION ""
    echo "CPU:" $ MODEL_CPU "," $ NUCLEO_CPU "Nuclei," $ CACHE_CPU "Cache"
    echo «USED SPACE:« $ DATA_USUARIO
    printf% 130s | tr »» «=»
    threw out ""
    ############################
    echo "USEFUL COMMANDS:"
    echo »- Install RPM in DEB package system: alien -c -i package.rpm»
    echo »- Change user and file group recursively: chown -hR user: group [file or dir]»
    echo »- Copy keeping the permissions: cp -ax source destination»
    echo »- Show active repositories: grep -i ppa.launchpad.net /etc/apt/sources.list.d/*.list»
    echo »- Add a repository: apt-add-repository ppa: repository»
    echo »- TO SEE MORE Cutil COMMANDS»
    echo »- TO SHOW THE ALIAS lsalias»
    printf% 130s | tr »» «=»
    threw out ""
    threw out ""
    # PS1 = »[\ e [33; 1m] ┌─ ([\ e [34; 1m] \ u @ \ h [\ e [37; 1m]) * * * * \ d - \ t * * * * {[\ e [31; 1m] \ w [\ e [33; 1m]} \ n└──┤ [\ e [32m] # »
    PS1=»[\e[33;1m]┌─([\e[34;1m]\u@\h[\e[37;1m])>{ [\e[31;1m]\w[\e[33;1m] }\n└──┤ [\e[32m]# «

    1.    abaddon s said

      why better not write your own article?

  4.   abaddon s said

    THESE ARE THE TUTORIALS THAT I LIKE !!!!!!!!!

  5.   Jose Albert said

    Well, I am very glad that you liked and served it!

    Tomorrow I hope to publish another article! Slopes.

  6.   user-arch said

    Greetings and infinite gratitude for sharing that information.
    I do not have much knowledge about the administration of GNU / Linux (I am just an empirical and curious user without academic training), but I remember reading on some website about security problems with privilege escalation; some commands and pipes in the .bashrc script, it seems to me they could facilitate the work of a hacker or cracker.
    Respectfully and very grateful.

  7.   Jose Albert said

    With Shell Scripting optimizing the terminal is simple, see how far you can go by doing a good Shell Scripting.

    LPI-SB8 Test ScreenCast (LINUX POST INSTALL - SCRIPT BICENTENARIO 8.0.0)
    (lpi_sb8_adaptation-audiovisual_2016.sh / 43Kb)

    See Screencast: https://www.youtube.com/watch?v=cWpVQcbgCyY

  8.   Lea said

    Great tutorial! Any book you recommend on linux to learn shell scripting, configurations, server security? Thank you