当前位置:网站首页>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边栏推荐
- 思迈特软件完成C轮融资,让BI真正实现“普惠化”
- The five pictures tell you: why is there such a big gap between people in the workplace?
- Can‘t connect to server on ‘IP‘ (60)
- GB/T 41479-2022信息安全技术 网络数据处理安全要求 导图概览
- 2022 Niuke multi school second problem solving Report
- 博客搭建九:hugo添加搜索功能
- Blog Building 9: add search function to Hugo
- 说透缓存一致性与内存屏障
- 模型预测控制(MPC)解析(九):二次规划的数值解(下)
- ASP. Net core foundation IV
猜你喜欢

uniapp---- 获取当前位置的经纬度等信息的详细步骤(包含小程序)
![[Qt5] QT small software release](/img/83/9867bd4513caadac6a056c801abe48.png)
[Qt5] QT small software release

sql server时间字段排序

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
![[Qt5] a method of multi window parameter transmission (using custom signal slot) and case code download](/img/6d/870add6179f0e3a2f9b719f79594f3.png)
[Qt5] a method of multi window parameter transmission (using custom signal slot) and case code download

Hcip --- LDP and MPLS Technology (detailed explanation)

Gbase 8A MPP and Galaxy Kirin (x86 version) complete deep adaptation

分布式系统架构理论与组件

Can‘t connect to server on ‘IP‘ (60)

Mysql-怎么添加用户和设置权限?
随机推荐
How CI framework integrates Smarty templates
[Qt5] a method of multi window parameter transmission (using custom signal slot) and case code download
CAT1 4G+以太网开发板232数据通过4G模块TCP发到服务器
Window 1 - > main window of the application (27)
[reprint] man Rsync translation (Chinese Manual of Rsync command)
博客搭建九:hugo添加搜索功能
[soft test software evaluator] 2013 comprehensive knowledge over the years
解决:IndexError: index 13 is out of bounds for dimension 0 with size 13
pyspark 写入数据到iceberg
一篇文章搞懂数据仓库:元数据分类、元数据管理
说透缓存一致性与内存屏障
JS手写函数之slice函数(彻底弄懂包头不包尾)
优炫数据库导入和导出方法
opencv+paddle orc 识别图片提取表格信息
ASP. Net core foundation VIII
Analysis of model predictive control (MPC) (IX): numerical solution of quadratic programming (II)
When unity switches to another scene, he finds that the scene is dimmed
How to configure phpunit under window
Matlab (3) matlab program flow control statement
Opencv+paddle Orc recognize pictures and extract table information