当前位置:网站首页>Bash shell interaction free
Bash shell interaction free
2022-07-28 08:41:00 【Ouchen Eli】
One 、Here Document No interaction
Use I/O Redirection provides a list of commands to an interactive program or command , such as ftp、cat or read command
Is an alternative to standard input to help script developers build input without using temporary files , But directly on the real estate to produce a “ file ” And used as “ command ” Standard input for .Here Document It can also be used with non interactive programs and commands
Two 、 Grammar format
command << Mark
……
Content —————— Between the tags is the incoming content
……
Mark
matters needing attention :
- Tags can use any legal character ( Usually it is EOF)
- The ending mark must be written in the top case , There can't be any characters in front of it
- There can't be any characters after the tag at the end
- Spaces before and after the opening mark are omitted
3、 ... and 、 example
1、 No interactive way to achieve the number of rows statistics , Put the content to be counted in the tag ”EOF“ Between , Direct the content to wc -l To statistics
> wc -l <EOF
> Line 1
> Line2
> EOF

2、 adopt read Commands receive input and print , The input value is two EOF The part between the marks , As a variable i Value
> read i <<EOF
> Hi
> EOF
> echo $i

3、 adopt passwd Set the password for the user
> passwd lisi <<EOF
> abc1234—————— These two lines are the password entered and the confirmation password
> abc1234
> EOF

4、 Support variable replacement
When you write to a file, you first replace the variable with the actual value , combining cat Command complete write
> #!/bin/bash
> file="EOF1.txt"
> i="school"
> cat > $file <<EOF
> I am going to $i
> EOF
> cat EOF1.txt


5、 Whole assignment to variable , And then through echo The command prints out the value of the variable
> #!/bin/bash
> var="Great! I am going to school!"
> myvar=$(cat <<EOF
> This is Line 1.
> Today is Monday.
> $var
> EOF
> )
> echo $myvar


6、 Turn off the function of variable replacement , Output the characters as they are , Without any modification or replacement
>#!/bin/bash
>var="Great! I am going to school!"
>myvar=$(cat <<'EOF'—————— Put single quotes on the tag , You can turn off variable substitution
>This is Line 1.
>Today is Monday.
>$var
>EOF
>)
>echo $myvar


7、 Remove the front of each line TAB Characters or spaces
> #!/bin/bash
> var="Great! I am going to school!"
> myvar=$(cat <<-'EOF'—————— Put... Before the mark ”-“, You can suppress the first line TAB Or space
> This is Line 1.
> Today is Monday.
> $var
> EOF
> )
> echo -e "$myvar"


8、 Multiline comment
Bash The default comment for is ”#“, This annotation method only supports single line annotations ,Here Document It solves the problem of multi line annotation
":" Represents the empty order that the above does not do , The contents of the middle marked area will not be executed , Will be bash Ignore , So it can achieve the effect of batch annotation
> #!/bin/bash
> var="Great! I am going to school!"
> : <<-‘EOF’—————— Multiline comment ,“:” At the beginning Here Document Tag content will not be executed
> This is Line 1.
> Today is Monday.
> $var
> EOF
> echo myvar


Four 、Expect
Based on the tcl A tool based on language , It is often used for automatic control and testing , solve shell Interaction related issues in scripts
rpm -1 expect
rpm -q tcl
yum -y install expect
1、 Basic commands
(1) Script interpreter
expect The script first introduces the file , Indicate which one is used shell
#!/usr/bin/expect
(2)spawn
spawn Usually followed by a Linux Carry out orders , Open a conversation 、 Start the process , And track subsequent interaction information . example :spawn passwd root
(3)expect
Judge whether the last output result contains the specified string , If so, return immediately , Otherwise, it will wait for the timeout to return
Can only be captured by spawn The output of the started process
Used to receive output after command execution , And then match the expected string
(4)send
Send string to process , The user simulates the user's input ; This command does not automatically enter to wrap lines , Generally, we need to add \r( enter ) perhaps \n
example :
Mode one :
expect “ password ” {send “abc123\r”}———— The same line send There should be {}
Mode two :
expect “ password ”
send ”$abc123\r“———— Line break send Part of it doesn't need to have {}
Mode three :
expect Supports multiple branches
> expect—————— Just match one of the cases , Execute corresponding send Statement to exit the expect sentence
> {
> " password 1" {send "abc123\r"}
> " password 2" {send "123456\r"}
> " password 3" {send "123123\r"}
> }
(5) Terminator
expect eof
Indicates the end of the interaction , Waiting for execution to end , Return to the original user , And spawn Corresponding
For example, switch to root user ,expect The script default is to wait 10s, When the command is finished , Default stay 10s after , Automatically switched back to the original user
interact
Keep interactive after execution , Give control to the console , Will stay at the target terminal without returning to the original terminal , At this time, it can be operated by hand ,interact The last order doesn't work , such as interact Add exit, It's not going to quit root user , And if not interact Will exit after login , Instead of staying on the remote terminal
Use interact Will remain in the terminal and will not return to the original terminal , For example, switch to root user , Will always be root In user state , such as ssh To another server , Will always be on the target server terminal , Instead of switching back to the original server
Be careful :expect eof And interact You can only choose one
(6)set
expect The default timeout is 10 second , adopt set Command to set the session timeout , If the timeout is not limited, it should be set to -1
example :set timeout 30
(7)exp_continue
exp_continue Attached to a expect After the judgment , After the item is matched , Can continue to match the expect Determine other items in the statement ,exp_continue Similar to... In a control statement continue sentence , It means to allow expect Continue down the instruction
For example, the following example will determine whether there is yes/no perhaps *assword. If the match yes/no The output yes And execute judgment again ; If the match *assword The output abc123 And end the paragraph expect sentence
> expect {
> "(yes/no)" {send "yes\r"; exp_continue}
> "\*password" {set timeout 300;send "abc123\r";}
> }
Be careful : Use exp_continue when , If tracking is like passwd This is the command to end the process after entering the password ,expect{} Don't add expect eof, because spawn At the end of the process, it will default to expect send out eof, It will lead to the following expect eof Error report in execution
(8)send_user
send_user Represents the echo command , amount to echo
(9) Receiving parameters
expect Scripts can receive from bash Parameters passed from the command line , Use [lindex $argv n] get , among n from 0 Start , They are the first , the second , Third … Parameters
set hostname [lindex $argv 0]———— amount to hostname=$1
set password [lindex $argv 1]———— amount to password=$2
(10)expect Direct execution
Need to use expect Command execution script
5、 ... and 、 example
su Switching users
> #!/usr/bin/expect ———— Declaration interpreter
> set timeout 5 ———— Set timeout
> set username [lindex $argv 0] ———— Parameters of the incoming
> set password [lindex $argv 1] ———— Parameters of the incoming
> spawn su $username ———— Start tracking the command
> expect " password "
> send "$password\r"
> expect "*]#"
> send_user "ok" No interactive execution , Capture information matching
> interact ———— Give control to the console
> perhaps expect eof
Create user and set password
Embedded execution patterns , take expect Process integration shell among , Easy to execute and handle
> #! /bin/bash
> user=$1
> password=$2
> useradd $user ———— Non interactive commands are placed in expect outside
> /usr/bin/expect <<-EOF ———————— Start exchange free execution , expect Start sign
> spawn passwd $user —— Turn on - A process trace passwd command ,expect Only the process information can be captured
> expect " new *"
> send "$ {password}\r"
> expect " again *"
> send "$ {password} \r"
> expect eof
> EOF
Realization ssh automatic logon
> #! /usr/bin/ expect
> set timeout 5
> set hostname [l index $argv 0 ]
> set password [l index $argv 1]
> spawn ssh $hostname
> expect {
> "Connection refused" exit ———— Connection failure , Like each other ssh Service closing
> "Name or service not known" exit —————— Can't find the server , For example, input IP The address is incorrect
> " (yes/no)" {send "yes\r" ;exp_ continue}
> "password:" {send "$password\r"}
> interact
> exit ———————— interact The last order doesn't work
Create disks interactively
>#!/bin/bash
>/usr/bin/expect <<EOF
>spawn fdisk /dev/$1
>expect " command ( Input m get help )" {send "n\n"}
>expect "Select (default p)" {send "p\n"}
>expect " Zone number " {send "\n"}
>expect " start A sector " {send "\n"}
>expect "Last A sector , + A sector " {send "\n"}
>expect " command ( Input m get help )" {send "w\n"}
>expect eof
>EOF
>fdisk -l
>mkfs.xfs -f /dev/$11 &>/dev/null
>if [ $? -ne 0 ];then
>echo " Unformatted successfully , Please check the script "
>else
>echo " Format successful "
>fi边栏推荐
- When will brain like intelligence, which is popular in academia, land? Let's listen to what the industry masters say - qubits, colliders, x-knowledge Technology
- 第2章-2 计算分段函数[1]
- [Qt5] QT small software release
- ASP. Net core foundation IV
- Vk1620 temperature controller / smart meter LED digital display driver chip 3/4-wire interface with built-in RC oscillator to provide technical support
- Export SQL server query results to excel table
- MySQL how to add users and set permissions?
- Redis 基本知识,快来回顾一下
- (13) Simple temperature alarm device based on 51 single chip microcomputer
- 阿里巴巴内部面试资料
猜你喜欢

招贤纳士,GBASE高端人才招募进行中

Understand the propagation process of EMI electromagnetic interference through five diagrams - the influence of square wave steepness on high-frequency components, the spectrum graph from time sequenc

The cooperation between starfish OS and metabell is just the beginning

Leetcode brushes questions. I recommend this video of the sister Xueba at station B

Recruiting talents, gbase high-end talent recruitment in progress

5张图告诉你:同样是职场人,差距怎么这么大?

Js继承方法
![[Qt5] QT small software release](/img/83/9867bd4513caadac6a056c801abe48.png)
[Qt5] QT small software release

CAT1 4g+ Ethernet development board 232 data is sent to the server through 4G module TCP

Gbase appears in Unicom cloud Tour (Sichuan Station) to professionally empower cloud ecology
随机推荐
【MindSpore易点通机器人-01】你也许见过很多知识问答机器人,但这个有点不一样
pyflink连接iceberg 实践
QT 怎么删除布局里的所有控件?
二维数组及操作
Analysis of model predictive control (MPC) (IX): numerical solution of quadratic programming (II)
2022 Niuke multi school second problem solving Report
‘全局事件总线’&‘消息订阅与发布’
How to import and export Youxuan database
Use of namespaces
Understand the propagation process of EMI electromagnetic interference through five diagrams - the influence of square wave steepness on high-frequency components, the spectrum graph from time sequenc
How to use QT help documents
(13) Simple temperature alarm device based on 51 single chip microcomputer
Vk1620 temperature controller / smart meter LED digital display driver chip 3/4-wire interface with built-in RC oscillator to provide technical support
pyspark 写入数据到iceberg
Hcip day 9_ BGP experiment
bash-shell 免交互
When unity switches to another scene, he finds that the scene is dimmed
Characteristics of EMC EMI beads
CAT1 4G+以太网开发板232数据通过4G模块TCP发到服务器
Maximum product of leetcode/ word length