Linux expect implements automatic login script instance code

  • 2020-10-07 18:57:54
  • OfStack

expect

expect allows us to automatically log in to the remote machine and to automatically execute commands remotely. Of course, if you use key authentication without password, you can also realize automatic login and automatic remote execution of commands. But when we can't use key validation, we have no choice. Therefore, at this time, as long as you know the other machine's account and password, you can use the expect script to achieve login and remote command.

The introduction

At present, I have one virtual machine for each person in the company. Most of my work needs to be done on the virtual machine, so I have to execute [ssh ES11en@xxxxxx] instructions to log in to the virtual machine many times every day. There are many ways to solve this problem, such as using xshell, secureCRT and other tools to record common connections, I wrote a simple script to achieve 1 key login ~

The login.sh script reads as follows:


#!/usr/bin/expect
spawn ssh xxx@xxxxxx
expect "*password:"
send " password \r"
interact

Then [./ login. sh] configure the alias alias, or move it to the executable directory to achieve [login] 1 key login;

expect is an instruction to handle the interaction. With expect, we can write the interaction to the Shell script to achieve some automation

expect has four core instructions:

spawn: Start a new process, followed by the instructions to be executed by the new process; expect: Specifies the string to be listened to, and triggers send if the spawn process returns a matching string (such as a standard input prompt); send: Sends the specified string to the spawn process instead of standard input; interact: User participation interaction;

The execution of ES43en.sh is as follows:

[spawn] starts a new process to execute the ssh login instruction, [expect] listens to the standard input prompt message "xxx@xxxxxx 's password" which conforms to the matching rules, triggers [send] to send a password instead of manual input to complete the login, [interact] user participates in the interaction, and at this time has logged in to the virtual machine;

Using expect can also be completed such as: batch update git code base, automatic login FTP and other functions ~

conclusion


Related articles: