Usually in the console input commands such as: sudo, SSH, ftp or modify the admin permissions of the file will require input password, but in the She ll script to run the process of how to automatically enter the password.
Below is a summary of three implementation methods.
First, redirect: The premise of using the redirection method to implement interaction is that the instruction needs to have parameters to specify the password input mode, such as FTP has the-i parameter to specify the use of standard input to enter the password
The shell uses redirection as a standard input: Cmd<<delimiter, the shell will delimiter the delimiter until the next same delimiter as input
Implementation of FTP automatic login and run the LS instruction is used as follows: Where ZJK is the username, zjk123 is the password
Ftp-i-N 192.168.21.46 <<eof
user zjk zjk123
ls
EOF
Two: Pipeline: As with redirection, instructions also have parameters to specify the password input mode, such as the sudo-s parameter, passwd's-stdin parameter
So the script that implements sudo automatic input password is as follows: where zjk123 is the password
echo ' zjk123 ' | Sudo-s CP file1/etc/hosts
The script that implements the automatic password modification is as follows:
echo ' Password ' | Passwd-stdin username
Three: Expect: The two methods described above presupposes that the instructions have parameters to set the password input mode, such as SSH instructions do not have such parameters, the third way of interaction will come in handy
Expect is used for interactive use, basically any interactive logon situation can be used, but need to install expect package
The syntax is as follows:
#!/bin/expect
Set timeout
spawn ssh-l jikuan.zjk 10.125.25.189 expect
"Password:"
send "zjk123\r" C4/>interact
Note: Expect is similar to bash and is used to log in to expect, so the first line is to specify the use of expect
To expect file when running script, not sh file
The first sentence of the above statement is to set the timeout time for 30s,spawn is expect statement, before executing the command to add this sentence
Expect "Password:" means whether the interactive fetch returns the password: keyword, because the prompt for the input password is returned when the SSH is executed: jikuan.zjk@10.125.25.189 ' s password:
Send is the password zjk123 sent to the past
Interact on behalf of the remote console, do not add this sentence after the completion of the return to the local console