Automatically enter password when executing sudo in Linux command line script

Original link: http://blog.163.com/shen_ys/blog/static/657664201475101236733/

 

The principle of using expect to achieve automatic login scripts.
  The script code is as follows:
  ##############################################
  #!/usr/bin/expect
  set timeout 30
  spawn ssh -l username 192.168.1.1
  expect "password:"
  send "ispass\r"
  interact
  ################### ############################
  1. The line [#!/usr/bin/expect]
  tells the code in the operating system script to use that a shell to execute. Expect here is actually the same thing as bash under linux and cmd under windows.
  Note: This line needs to be the first line of the script.
  2. [set timeout 30]
  This is to set the timeout time, the timing unit is: seconds
  3. [spawn ssh -l username 192.168.1.1]
  spawn is an internal command of expect that can be executed after entering the expect environment. If expect is not installed or executed directly under the default SHELL, the spawn command cannot be found. So don't use commands like "which spawn" to find the spawn command. For example, dir in windows is an internal command. This command is provided by the shell. You cannot find an executable file of dir.com or dir.exe.
  Its main function is to add a shell to the ssh running process to pass interactive instructions.
  4. [expect "password:"]
  The expect here is also an internal command of expect. It's a little dizzy. The shell command of expect is the same as the internal command, but it is not a function. Just get used to it. The meaning of this command is to judge whether the string "password:" is contained in the last output result. If so, return immediately, otherwise, wait for a period of time to return. The waiting time here is the previously set 30 seconds.
  5. [send "ispass \r"]
  here is to perform an interactive action, which is equivalent to the action of manually entering a password.
  Reminder: Don't forget to add "\r" at the end of the command string. If there is an abnormal waiting state, you can check it.
  6. [interact]
  After the execution is completed, keep the interactive state, and hand over the control to the console. At this time, it can be operated manually. If you do not have this sentence, you will log out after logging in instead of staying on the remote terminal. If you just log in and execute
  #!/usr/bin/expect #Pay attention to the installation path, not sure whereis expect
  # Change a login shell to bash
  set user [lindex $argv 0]
  spawn bash $user
  expect "]:"
  send "/bin/bash "
  expect eof
  exit

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326614528&siteId=291194637