30 classic cases of Shell Scripting

Keywords: Linux ssh ftp less shell

Contents of this article

Download files from FTP server
 22. Continuous input of 5 numbers less than 100, statistic sum, minimum and maximum
 23. Assign the results to variables, respectively
 24. Batch modification of file names
 25. Statistics of the total number of files in the current directory ending with. html
 26. Scanning host port status
 27. Expect implements SSH execute commands without interaction 28, batch modification of server user password
 29. Print multiplication formula
 30. getopts tool improves script command line parameters

Download files from FTP server

#!/bin/bash
if [ $# -ne 1 ]; then
    echo "Usage: $0 filename"
fi
dir=$(dirname $1)
file=$(basename $1)
ftp -n -v << EOF   #- n. Automatic login
open 192.168.1.10  #ftp server
user admin password
binary   #Set ftp transmission mode to binary to avoid different MD5 values or. tar.gz compressed package format errors
cd $dir
get "$file"
EOF

22. Continuous input of 5 numbers less than 100, statistic sum, minimum and maximum

#!/bin/bash
COUNT=1
SUM=0
MIN=0
MAX=100
while [ $COUNT -le 5 ]; do
    read -p "Please input 1-10 Integer:" INT
    if [[ ! $INT =~ ^[0-9]+$ ]]; then
        echo "Input must be an integer!"
        exit 1
    elif [[ $INT -gt 100 ]]; then
        echo "Input must be within 100!"
        exit 1
    fi
    SUM=$(($SUM+$INT))
    [ $MIN -lt $INT ] && MIN=$INT
    [ $MAX -gt $INT ] && MAX=$INT
    let COUNT++
done
echo "SUM: $SUM"
echo "MIN: $MIN"
echo "MAX: $MAX"

23. Assign the results to variables, respectively

Application scenario: You want to assign execution results or location parameters to variables for subsequent use.

//Method 1:

for i in $(echo "4 5 6"); do
   eval a$i=$i
done
echo $a4 $a5 $a6
//Method 2: The position parameter 192.168.1.1 {1,2} was divided into each variable.

num=0
for i in $(eval echo $*);do   #eval decomposes {1,2} into 1 2
   let num+=1
   eval node${num}="$i"
done
echo $node1 $node2 $node3
# bash a.sh 192.168.1.1{1,2}
192.168.1.11 192.168.1.12
//Method 3:

arr=(4 5 6)
INDEX1=$(echo ${arr[0]})
INDEX2=$(echo ${arr[1]})
INDEX3=$(echo ${arr[2]})

24. Batch modification of file names

Example:

# touch article_{1..3}.html
# ls
article_1.html  article_2.html  article_3.html
//Purpose: To change article to bbs

//Method 1:

for file in $(ls *html); do
    mv $file bbs_${file#*_}
    # mv $file $(echo $file |sed -r 's/.*(_.*)/bbs\1/')
    # mv $file $(echo $file |echo bbs_$(cut -d_ -f2)
done
//Method 2:

for file in $(find . -maxdepth 1 -name "*html"); do
     mv $file bbs_${file#*_}
done
//Method 3:

# rename article bbs *.html

25. Statistics of the total number of files in the current directory ending with. html

Method 1:

# find . -name "*.html" -exec du -k {} \; |awk '{sum+=$1}END{print sum}'

//Method 2:

for size in $(ls -l *.html |awk '{print $5}'); do
    sum=$(($sum+$size))
done
echo $sum

26. Scanning host port status

#!/bin/bash
HOST=$1
PORT="22 25 80 8080"
for PORT in $PORT; do
    if echo &>/dev/null > /dev/tcp/$HOST/$PORT; then
        echo "$PORT open"
    else
        echo "$PORT close"
    fi
done

Expect Implements SSH Execution Command Free of Interaction

Expect Is a tool for automated interactive applications, such as telnet,ftp,passwd And so on.

//The expect package needs to be installed first.

//Method 1: EOF standard output as expect standard input

#!/bin/bash
USER=root
PASS=123.com
IP=192.168.1.120
expect << EOF
set timeout 30
spawn ssh $USER@$IP   
expect {
    "(yes/no)" {send "yes\r"; exp_continue}
    "password:" {send "$PASS\r"}
}
expect "$USER@*"  {send "$1\r"}
expect "$USER@*"  {send "exit\r"}
expect eof
EOF
//Method 2:

#!/bin/bash
USER=root
PASS=123.com
IP=192.168.1.120
expect -c "
    spawn ssh $USER@$IP
    expect {
        \"(yes/no)\" {send \"yes\r\"; exp_continue}
        \"password:\" {send \"$PASS\r\"; exp_continue}
        \"$USER@*\" {send \"df -h\r exit\r\"; exp_continue}
    }"
//Method 3: Separate expect scripts

//Login script:

# cat login.exp
#!/usr/bin/expect
set ip [lindex $argv 0]
set user [lindex $argv 1]
set passwd [lindex $argv 2]
set cmd [lindex $argv 3]
if { $argc != 4 } {
puts "Usage: expect login.exp ip user passwd"
exit 1
}
set timeout 30
spawn ssh $user@$ip
expect {
    "(yes/no)" {send "yes\r"; exp_continue}
    "password:" {send "$passwd\r"}
}
expect "$user@*"  {send "$cmd\r"}
expect "$user@*"  {send "exit\r"}
expect eof
//Execute command scripts: Write a loop that can batch multiple servers

#!/bin/bash
HOST_INFO=user_info.txt
for ip in $(awk '{print $1}' $HOST_INFO)
do
    user=$(awk -v I="$ip" 'I==$1{print $2}' $HOST_INFO)
    pass=$(awk -v I="$ip" 'I==$1{print $3}' $HOST_INFO)
    expect login.exp $ip $user $pass $1
doneLinux Host SSH Connection information:

# cat user_info.txt
192.168.1.120 root 123456

28. Batch modification of server user password

Linux Host SSH Connection information: old password

# cat old_pass.txt 
192.168.18.217  root    123456     22
192.168.18.218  root    123456     22
//Content format: IP User Password Port

SSH Remote password modification script: random generation of new passwords

#!/bin/bash
OLD_INFO=old_pass.txt
NEW_INFO=new_pass.txt
for IP in $(awk '/^[^#]/{print $1}' $OLD_INFO); do
    USER=$(awk -v I=$IP 'I==$1{print $2}' $OLD_INFO)
    PASS=$(awk -v I=$IP 'I==$1{print $3}' $OLD_INFO)
    PORT=$(awk -v I=$IP 'I==$1{print $4}' $OLD_INFO)
    NEW_PASS=$(mkpasswd -l 8)  #Random password
    echo "$IP   $USER   $NEW_PASS   $PORT" >> $NEW_INFO
    expect -c "
    spawn ssh -p$PORT $USER@$IP
    set timeout 2
    expect {
        \"(yes/no)\" {send \"yes\r\";exp_continue}
        \"password:\" {send \"$PASS\r\";exp_continue}
        \"$USER@*\" {send \"echo \'$NEW_PASS\' |passwd --stdin $USER\r exit\r\";exp_continue}
    }"
done
//Generate a new password file:

# cat new_pass.txt 
192.168.18.217  root    n8wX3mU%      22
192.168.18.218  root    c87;ZnnL      22

29. Print multiplication formula

Method 1:

# awk 'BEGIN{for(n=0;n++<9;){for(i=0;i++<n;)printf i"x"n"="i*n" ";print ""}}'
//Method 2:

for ((i=1;i<=9;i++)); do
   for ((j=1;j<=i;j++)); do
     result=$(($i*$j))
     echo -n "$j*$i=$result "
   done
   echo
done

30. getopts tool improves script command line parameters

getopts is a tool for parsing script option parameters.

Command format: getopts optstring name [arg]

When you first use it, you should pay attention to these points:

The script position parameter matches the individual letters in the optstring one by one. If it matches, it assigns name, otherwise assigns name as a question mark.

In optstring, a single letter is an option. If a colon is added after the letter, it means that the option is followed by a parameter, and the parameter value is assigned to the OPTARG variable.

The first one in optstring is a colon, which indicates a shielding system error (test.sh: illegal option -- h);

Allow options to be put together, such as - ab



Here's a simple example of a printed file with a specified line to guide your thinking.

#!/bin/bash
while getopts :f:n: option; do
    case $option in
        f)
            FILE=$OPTARG
      [ ! -f $FILE ] && echo "$FILE File not exist!" && exit
            ;;
        n)
            sed -n "${OPTARG}p" $FILE
            ;;
        ?)
            echo "Usage: $0 -f  -n "
            echo "-f, --file           specified file"
            echo "-n, --line-number    print specified line"
            exit 1
        ;;
    esac
done

30 summaries based on work experience Shell At this point, script cases are more practical, and interview written questions often come out. Hope that your friends can practice more and make your Shell's skill level rise a little bit! ____________


Posted by mihomes on Fri, 13 Sep 2019 23:01:12 -0700