12th. Shell script writing and common face Test (III.)

Source: Internet
Author: User
Tags ftp transfer

Directory of this chapter:

650) this.width=650; "src=" Https://s2.51cto.com/wyfs02/M02/97/5E/wKiom1kuG2Dij8H6AAAuNhrwFhc739.png "title=" QQ picture 20170531092359.png "alt=" Wkiom1kug2dij8h6aaaunhrwfhc739.png "/>

12.21 ftp Download file

#!/bin/bashif [$#-ne 1]; Then echo "Usage: $ filename" fidir=$ (dirname $) file=$ (basename $) ftp-n-v << EOF #-N Auto Login Open 192.168.1.10 User admin Adminpassbinary # Set FTP transfer mode to binary, avoid MD5 value different or. tar.gz Compressed package format error CD $dirget "$file" EOF

12.22 input five characters within 100 numbers, statistics and Minimum and maximum

count=1sum=0min=0max=100while [  $COUNT  -le 5 ];  do    read -p  "Please enter 1-10 integers:"  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++doneecho  "sum:  $SUM" echo  "min:  $MIN" echo  "max:  $MAX" 

650) this.width=650; "src=" Https://s2.51cto.com/wyfs02/M01/97/60/wKioL1kuHZCQQNrOAAAloooYaNM429.png "title=" QQ picture 20170531093357.png "alt=" Wkiol1kuhzcqqnroaaaloooyanm429.png "/>

12.23 assigning the result to the variable separately

Method 1:for I in $ (echo "4 5 6");    Do eval a$i= $idoneecho $a 4 $a 5 $a 6 Method 2: Split position parameter 192.168.18.1{1,2} into each variable num=0for i in $ (eval echo $*);d o #eval将 {} decomposed to 1 2 Let Num+=1 eval node${num}= "$i" Doneecho $node 1 $node 2 $node 3# bash a.sh 192.168.18.1{1,2}192.168.18.11 192.168.18.12 Party FA 3:arr= (4 5 6) index1=$ (Echo ${arr[0]}) index2=$ (Echo ${arr[1]}) index3=$ (Echo ${arr[2]})

12.24 Batch modification of file names

# Touch article_{1..3}.html# lsarticle_1.html article_2.html article_3.html now want 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

12.25 Statistics The total size of files in the current directory ending in. html

Method 1:# Find. -name "*.html"-maxdepth 1-exec du-b {} \; |awk ' {Sum+=$1}end{print sum} ' method 2:for size in $ (ls-l *.html |awk ' {print $} ‘); Do sum=$ (($sum + $size)) Doneecho $sum Recursive statistics: # Find. -name "*.html"-exec du-k {} \; |awk ' {Sum+=$1}end{print sum} '

12.26 Scan Host Port status

#!/bin/bashhost=$1port= "8080" for PORT in $PORT; Do if echo &>/dev/null >/dev/tcp/$HOST/$PORT; Then echo "$PORT open" else echo "$PORT Close" Fidone

650) this.width=650; "src=" Https://s4.51cto.com/wyfs02/M02/97/60/wKiom1kuIdyj5UkEAAAONQjBJ3c657.png "title=" Qq20170531095147.png "alt=" Wkiom1kuidyj5ukeaaaonqjbj3c657.png "/>

12.27 expect implements SSH-free interactive execution commands

The expect tool needs to be installed first.

Expect involves usage notes:

Command Description

The set can set the timeout, or you can set the variable

Timeout time-out wait, default 10s

Spawn Execute a command

Expect "" matches the contents of the output

Exp_continue continue to perform the following match

\ R Enter

$ARGC Statistics number of positional parameters

[lindex $ARGV 0] Position Parameters

Puts print string, similar to echo

Expect{...} Enter multiple lines of records

Method 1:eof standard output as expect standard input

#!/bin/bashuser=rootpass=123.comip=192.168.1.120expect << eofset timeout 30spawn ssh [email protected] $IP expect {"(yes/no)" {send "yes\r"; exp_continue} "password:" {send "$PASS \ r"}}expect "[email protected]*" {send "$1\r"}exp ECT "[email protected]*" {send "exit\r"}expect EOF EOF

Method 2:

#!/bin/bashuser=rootpass=123.comip=192.168.1.120expect-c "Spawn ssh [email protected] $IP expect {\" (yes/no ) \ "{Send \" yes\r\ "; exp_continue} \" Password:\ " {Send \ "$PASS \r\"; exp_continue} \ "[email protected]*\" {send \ "df-h\r exit\r\"; Exp_continue}} "

Method 3: Separate the expect script

Login.exp Login File:

#!/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 30spawn ssh [email protected] $ipexpect { "(yes/no)" {send "yes\r"; exp_continue} "password:" {send "$passwd \ r"}}expect "[email protected]*" {send "$cmd \ r"}expe CT "[email protected]*" {send "exit\r"}expect EOF

Execute command script:

#!/bin/bashhost_info=user_infofor IP in $ (awk ' {print $} ' $HOST _info) do user=$ (awk-v i= "$ip" ' I==$1{print $} ' $HOST _ INFO) pass=$ (awk-v i= "$ip" ' I==$1{print $ $} ' $HOST _info) expect login.exp $ip $user $pass $1done

SSH connection Information file:

# Cat User_info

192.168.1.120 Root 123456

12.28 Batch Modify server user password

Old password SSH host information Old_info file:

# IP user passwd port

#--------------------------------------

192.168.18.217 Root 123456 22

192.168.18.218 Root 123456 22

To modify the password script:

#!/bin/bashold_info=old_infonew_info=new_infofor 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)     echo  "$IP    $ user    $NEW _pass    $PORT " >>  $NEW _info     expect -c  "    spawn ssh -p$port [email protected" $IP      set timeout 2    expect {         \ "(yes/no) \"  {send \ "Yes\r\";exp_continue}         \ "Password:\"  {Send \ "$PASS \r\"; exp_continue}        \ "[Email protected]*\"  {send \ "echo \ ' $NEW _pass\ '  |passwd --stdin  $USER \r exit\r\"; Exp_continue}     } "done

Generate a new password New_info file:

192.168.18.217 Root n8wx3mu% 22

192.168.18.218 root c87; ZNNL 22

12.29 Printing multiplication Formulas

Method 1:# awk ' Begin{for (n=0;n++<9;) {for (i=0;i++<n;) printf i "x" n "=" I*n "";p Rint ""}} ' 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 Echodone

650) this.width=650; "Src=" https://s1.51cto.com/wyfs02/M02/97/60/wKioL1kuHgrQ_XPxAABhsSZCEJg877.png-wh_500x0-wm_ 3-wmp_4-s_1515635873.png "title=" Qq20170531093546.png "alt=" Wkiol1kuhgrq_xpxaabhsszcejg877.png-wh_50 "/>

12.30 getopts Tool Perfecting script command line arguments

Getopts is a tool that parses the parameters of a script option.

Command format: getopts optstring name [ARG]

The first use you should pay attention to these points:

1) The script location parameter matches individual letters in the optstring, and assigns a value to name if it matches, otherwise the assignment name is a question mark;

2) A single letter in the optstring is an option if the letter is followed by a colon, indicating that the option is followed by a parameter, and the value of the parameter is assigned to the OPTARG variable;

3) The first of the optstring is a colon, which indicates a shielded system error (test.sh:illegal option-h);

4) allow the option to be put together, e.g.-ab

Here's a simple example of a print file specifying a line to guide your thinking, Expand your scripting options feature:

#!/bin/bashwhile getopts :f:n: option; do    case  $option  in &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;F)              file= $OPTARG     [ ! -f  $FILE  ] &&  echo  "$FILE  file not exist!"  && exit            ;;         n)              sed -n  "${optarg}p"   $FILE              ;;         ?)             echo  "Usage: $0 -f  <file_path> -n <line_number> "             echo  "-f, --file           specified file"             echo  "-n, --line-number     print specified line "             exit 1        ;;     esacdone

650) this.width=650; "src=" Https://s2.51cto.com/wyfs02/M00/97/60/wKioL1kuID3zfLJWAAAeiazGKzY694.png "title=" Qq20170531094515.png "alt=" Wkiol1kuid3zfljwaaaeiazgkzy694.png "/>

Idea Extension: Define the script parameters, save the arguments, and then call the variables to continue the operation.


This chapter is written in the shell script examples are more practical, in the interview also often appear, I hope you practice more hands-on, do not copy and paste to take to run, so it is not learning! If you have any questions, please dabigatran Exchange:323779636 (Shell/python devops Development Group)


This article is from the "Li Zhenliang Technology Blog" blog, make sure to keep this source http://lizhenliang.blog.51cto.com/7876557/1930804

12th. Shell script writing and common face Test (III.)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.