리눅스 expect 명령어 실용 예제

LinuxBeginner
지금 연습하기

소개

이 랩에서는 Linux 의 expect 명령어를 사용하여 대화형 명령줄 애플리케이션을 자동화하는 방법을 배우게 됩니다. expect 명령어는 SSH, FTP 및 기타 대화형 프로그램과 같이 사용자 입력을 필요로 하는 프로그램과 스크립트가 상호 작용할 수 있도록 하는 강력한 자동화 도구입니다.

이 랩을 마치면 다음을 수행할 수 있습니다.

  • expect 명령어의 목적과 기본 구문을 이해합니다.
  • SSH 로그인을 자동화하는 스크립트를 만듭니다.
  • expect 스크립트에서 다양한 프롬프트와 응답을 처리합니다.

expect 명령어는 반복적인 작업에 대한 수동 개입을 크게 줄여 시스템 관리 및 일상적인 작업을 더욱 효율적으로 만들 수 있습니다. 먼저 expect의 기본 구문을 설치하고 탐색한 다음, SSH 로그인을 자동화하고 다양한 대화형 프롬프트를 처리하는 스크립트를 만드는 것으로 진행합니다.

Linux 명령어 치트 시트

expect 명령어와 기본 구문 이해

Linux 의 expect 명령어는 일반적으로 사용자 입력을 필요로 하는 대화형 명령줄 프로그램을 자동화할 수 있게 해줍니다. 이는 자동 로그인, 파일 전송 또는 프로그램이 입력을 요청하는 모든 상황에 특히 유용합니다.

expect 설치

먼저, 시스템에 expect 패키지가 설치되어 있는지 확인해 보겠습니다. 터미널을 열고 다음을 실행합니다.

which expect

expect가 이미 설치되어 있다면 해당 경로 (예: /usr/bin/expect) 가 표시됩니다. 그렇지 않은 경우, 설치해야 합니다.

sudo apt-get update
sudo apt-get install -y expect

기본 expect 구문 이해

expect 명령어는 Tcl (Tool Command Language) 을 기반으로 하는 스크립팅 언어를 사용합니다. expect 스크립트의 기본 구조는 다음 명령어를 포함합니다.

  1. spawn: 상호 작용할 프로세스를 시작합니다.
  2. expect: 생성된 프로세스에서 특정 출력을 기다립니다.
  3. send: 생성된 프로세스에 입력을 보냅니다.
  4. set timeout: 예상된 출력을 기다리는 시간을 설정합니다.

이러한 개념을 시연하기 위해 간단한 expect 스크립트를 만들어 보겠습니다. 텍스트 편집기를 열고 프로젝트 디렉토리에서 hello.exp라는 파일을 만듭니다.

cd ~/project
nano hello.exp

다음 내용을 파일에 입력합니다.

#!/usr/bin/expect -f

## Set a timeout of 10 seconds
set timeout 10

## Spawn the bash process
spawn bash

## Wait for the bash prompt
expect "$ "

## Send a command to the bash process
send "echo Hello from expect\r"

## Wait for the bash prompt again
expect "$ "

## Exit the bash session
send "exit\r"

## Wait for the process to complete
expect eof

Ctrl+O를 누르고 Enter를 눌러 파일을 저장하고, Ctrl+X를 눌러 nano 를 종료합니다.

스크립트를 실행 가능하게 만듭니다.

chmod +x ~/project/hello.exp

이제 스크립트를 실행합니다.

~/project/hello.exp

다음과 유사한 출력을 볼 수 있습니다.

spawn bash
$ echo Hello from expect
Hello from expect
$ exit
exit

스크립트의 각 줄 이해

스크립트의 각 줄이 무엇을 하는지 설명하겠습니다.

  • #!/usr/bin/expect -f: 이 줄은 시스템에 이 스크립트를 실행하기 위해 expect 인터프리터를 사용하도록 지시하는 shebang 라인입니다.
  • set timeout 10: 이 명령어는 뒤따르는 모든 expect 명령어에 대해 10 초의 타임아웃을 설정합니다.
  • spawn bash: expect가 상호 작용할 새로운 bash 셸 프로세스를 시작합니다.
  • expect "$ ": bash 프롬프트가 나타날 때까지 기다립니다.
  • send "echo Hello from expect\r": bash 셸에 명령을 보냅니다. 끝에 있는 \r은 Enter 키를 누르는 것을 시뮬레이션합니다.
  • expect "$ ": 명령이 실행된 후 다시 bash 프롬프트를 기다립니다.
  • send "exit\r": bash 셸을 닫기 위해 exit 명령을 보냅니다.
  • expect eof: 생성된 프로세스가 종료될 때까지 기다립니다.

이 간단한 예제는 expect의 핵심 기능을 보여줍니다. 다음 단계에서는 이러한 개념을 사용하여 더 실용적인 스크립트를 만들 것입니다.

expect 를 사용하여 모의 SSH 로그인 스크립트 만들기

이 단계에서는 SSH 로그인 프로세스를 시뮬레이션하는 expect 스크립트를 만들 것입니다. 이 환경에서는 실제 SSH 로그인을 수행할 수 없으므로 원리를 보여주는 모의 스크립트를 만들 것입니다.

SSH 인증 흐름 이해

SSH 를 통해 원격 서버에 연결할 때 일반적인 상호 작용은 다음과 같습니다.

  1. ssh username@hostname으로 연결을 시작합니다.
  2. 호스트 키를 수락합니다 (처음 연결하는 경우).
  3. 프롬프트가 표시되면 비밀번호를 입력합니다.
  4. 원격 셸에 액세스합니다.

expect가 이 프로세스를 어떻게 자동화할 수 있는지 보여주기 위해 모의 SSH 환경을 만들어 보겠습니다.

모의 SSH 서버 스크립트 만들기

먼저, 비밀번호를 묻는 SSH 서버를 시뮬레이션하는 스크립트를 만들어 보겠습니다.

cd ~/project
nano mock_ssh_server.sh

다음 내용을 입력합니다.

#!/bin/bash

echo "The authenticity of host 'mockserver' can't be established."
echo "RSA key fingerprint is SHA256:abcdefghijklmnopqrstuvwxyz123456."
echo "Are you sure you want to continue connecting (yes/no)? "
read answer

if [ "$answer" != "yes" ]; then
  echo "Host key verification failed."
  exit 1
fi

echo "Warning: Permanently added 'mockserver' (RSA) to the list of known hosts."
echo "Password: "
read -s password

if [ "$password" == "mockpassword" ]; then
  echo "Last login: Wed Nov 1 12:00:00 2023 from 192.168.1.100"
  echo "Welcome to Mock SSH Server"
  echo "mockuser@mockserver:~$ "

  while true; do
    read -p "" command
    if [ "$command" == "exit" ]; then
      echo "Connection to mockserver closed."
      exit 0
    else
      echo "Executing: $command"
      echo "mockuser@mockserver:~$ "
    fi
  done
else
  echo "Permission denied, please try again."
  exit 1
fi

파일을 저장하고 실행 가능하게 만듭니다.

chmod +x ~/project/mock_ssh_server.sh

이 스크립트는 다음을 시뮬레이션합니다.

  • SSH 호스트 확인 프롬프트
  • 비밀번호 프롬프트
  • 명령에 응답하는 간단한 셸

로그인을 자동화하는 expect 스크립트 만들기

이제 모의 SSH 서버와의 상호 작용을 자동화하는 expect 스크립트를 만들어 보겠습니다.

cd ~/project
nano ssh_login.exp

다음 내용을 입력합니다.

#!/usr/bin/expect -f

## Set variables
set timeout 10
set password "mockpassword"

## Start the mock SSH server
spawn ./mock_ssh_server.sh

## Handle the host verification prompt
expect "Are you sure you want to continue connecting (yes/no)? "
send "yes\r"

## Handle the password prompt
expect "Password: "
send "$password\r"

## Wait for the shell prompt
expect "mockuser@mockserver:~$ "

## Execute a command
send "ls -la\r"
expect "mockuser@mockserver:~$ "

## Exit the session
send "exit\r"

## Wait for the process to complete
expect eof

puts "\nSSH login automation completed successfully!"

파일을 저장하고 실행 가능하게 만듭니다.

chmod +x ~/project/ssh_login.exp

자동 로그인 스크립트 실행

이제 모의 SSH 서버와의 상호 작용을 자동화하기 위해 expect 스크립트를 실행해 보겠습니다.

cd ~/project
./ssh_login.exp

다음과 유사한 출력을 볼 수 있습니다.

spawn ./mock_ssh_server.sh
The authenticity of host 'mockserver' can't be established.
RSA key fingerprint is SHA256:abcdefghijklmnopqrstuvwxyz123456.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added 'mockserver' (RSA) to the list of known hosts.
Password:
Last login: Wed Nov 1 12:00:00 2023 from 192.168.1.100
Welcome to Mock SSH Server
mockuser@mockserver:~$ ls -la
Executing: ls -la
mockuser@mockserver:~$ exit
Connection to mockserver closed.

SSH login automation completed successfully!

스크립트 설명

expect 스크립트의 각 부분이 무엇을 하는지 설명하겠습니다.

  1. set timeout 10: 모든 expect 명령어에 대해 10 초의 전역 타임아웃을 설정합니다.
  2. set password "mockpassword": 비밀번호를 변수에 저장합니다.
  3. spawn ./mock_ssh_server.sh: 모의 SSH 서버 스크립트를 시작합니다.
  4. expect "Are you sure you want to continue connecting (yes/no)? ": 호스트 확인 프롬프트를 기다립니다.
  5. send "yes\r": 호스트 키를 수락하기 위해 "yes"를 보냅니다.
  6. expect "Password: ": 비밀번호 프롬프트를 기다립니다.
  7. send "$password\r": 비밀번호를 보냅니다.
  8. expect "mockuser@mockserver:~$ ": 셸 프롬프트를 기다립니다.
  9. send "ls -la\r": 파일을 나열하는 명령을 보냅니다.
  10. expect "mockuser@mockserver:~$ ": 셸 프롬프트를 다시 기다립니다.
  11. send "exit\r": 세션을 닫기 위해 exit 명령을 보냅니다.
  12. expect eof: 프로세스가 종료될 때까지 기다립니다.
  13. puts "\nSSH login automation completed successfully!": 성공 메시지를 출력합니다.

이 예제는 호스트 키 수락부터 원격 서버에서 명령 실행, 안전하게 종료까지 전체 SSH 로그인 프로세스를 자동화하는 데 expect를 사용하는 방법을 보여줍니다.

expect 를 사용하여 여러 프롬프트 및 응답 처리

실제 시나리오에서 대화형 프로그램은 종종 여러 프롬프트를 표시하며, 다른 조건에 따라 다른 응답을 요구할 수 있습니다. 이 단계에서는 expect 스크립트에서 여러 프롬프트와 조건부 응답을 처리하는 방법을 배우겠습니다.

조건부 expect 블록 이해

expect 명령어는 다양한 가능한 프롬프트를 처리하기 위해 패턴 - 액션 블록 구조와 함께 사용할 수 있습니다.

expect {
    "pattern1" { actions for pattern1 }
    "pattern2" { actions for pattern2 }
    timeout { actions for timeout }
    eof { actions for end of file }
}

이 구조를 통해 스크립트는 수신하는 출력에 따라 다르게 응답할 수 있습니다.

다중 프롬프트 처리 스크립트 만들기

여러 프롬프트가 있는 프로그램을 시뮬레이션하는 스크립트를 만들어 보겠습니다.

cd ~/project
nano multi_prompt.sh

다음 내용을 입력합니다.

#!/bin/bash

echo "Please select an option:"
echo "1. Show date and time"
echo "2. List files"
echo "3. Show system info"
echo "4. Exit"
echo -n "Enter your choice (1-4): "
read choice

case $choice in
  1)
    echo "Current date and time:"
    date
    ;;
  2)
    echo "File listing:"
    ls -la
    ;;
  3)
    echo "System information:"
    uname -a
    ;;
  4)
    echo "Exiting program..."
    exit 0
    ;;
  *)
    echo "Invalid option. Please enter a number between 1 and 4."
    exit 1
    ;;
esac

echo "Do you want to continue? (yes/no): "
read answer

if [ "$answer" == "yes" ]; then
  echo "Continuing..."
  echo "Operation completed successfully."
else
  echo "Exiting program..."
fi

파일을 저장하고 실행 가능하게 만듭니다.

chmod +x ~/project/multi_prompt.sh

이제 이 프로그램과 상호 작용하고 가능한 모든 프롬프트를 처리하는 expect 스크립트를 만들어 보겠습니다.

cd ~/project
nano handle_prompts.exp

다음 내용을 입력합니다.

#!/usr/bin/expect -f

## Set a timeout
set timeout 10

## Start the multi-prompt program
spawn ./multi_prompt.sh

## Wait for the choice prompt
expect "Enter your choice (1-4): "

## Generate a random choice (1-3)
set choice [expr {int(rand() * 3) + 1}]
send "$choice\r"

## Process the result based on the choice
switch $choice {
    1 {
        expect "Current date and time:"
        expect "Do you want to continue? (yes/no): "
    }
    2 {
        expect "File listing:"
        expect "Do you want to continue? (yes/no): "
    }
    3 {
        expect "System information:"
        expect "Do you want to continue? (yes/no): "
    }
}

## Handle the continue prompt
expect {
    "Do you want to continue? (yes/no): " {
        ## 70% chance to say yes, 30% chance to say no
        if {rand() < 0.7} {
            send "yes\r"
            expect "Operation completed successfully."
        } else {
            send "no\r"
            expect "Exiting program..."
        }
    }
    timeout {
        puts "Timeout waiting for continue prompt"
        exit 1
    }
}

## Wait for the program to complete
expect eof

puts "\nMulti-prompt handling completed successfully!"

파일을 저장하고 실행 가능하게 만듭니다.

chmod +x ~/project/handle_prompts.exp

다중 프롬프트 처리 스크립트 실행

이제 다중 프롬프트 프로그램과 상호 작용하기 위해 expect 스크립트를 실행해 보겠습니다.

cd ~/project
./handle_prompts.exp

이 스크립트를 실행할 때마다 임의로 옵션 중 하나를 선택하고 계속할지 또는 종료할지를 무작위로 결정합니다. 다음은 예시 출력입니다.

spawn ./multi_prompt.sh
Please select an option:
1. Show date and time
2. List files
3. Show system info
4. Exit
Enter your choice (1-4): 2
File listing:
total 20
drwxr-xr-x 2 labex labex 4096 Nov  1 10:00 .
drwxr-xr-x 4 labex labex 4096 Nov  1 10:00 ..
-rwxr-xr-x 1 labex labex  345 Nov  1 10:00 handle_prompts.exp
-rwxr-xr-x 1 labex labex  578 Nov  1 10:00 multi_prompt.sh
-rwxr-xr-x 1 labex labex  221 Nov  1 10:00 ssh_login.exp
Do you want to continue? (yes/no): yes
Continuing...
Operation completed successfully.

Multi-prompt handling completed successfully!

더 발전된 expect 스크립트 만들기

이제 예기치 않은 프롬프트와 오류를 처리할 수 있는 더 발전된 스크립트를 만들어 보겠습니다.

cd ~/project
nano advanced_expect.exp

다음 내용을 입력합니다.

#!/usr/bin/expect -f

## Set a timeout
set timeout 10

## Define variables
set program "./multi_prompt.sh"
set max_retries 3
set retry_count 0

## Define a procedure to handle errors
proc handle_error {} {
    global retry_count max_retries program
    incr retry_count

    if {$retry_count < $max_retries} {
        puts "\nRetrying... Attempt $retry_count of $max_retries"
        ## Start the program again
        spawn $program
        return 1
    } else {
        puts "\nMaximum retry attempts reached. Exiting."
        exit 1
    }
}

## Start the program
spawn $program

## Main interaction loop
while {$retry_count < $max_retries} {
    expect {
        "Enter your choice (1-4): " {
            send "1\r"  ## Always choose option 1 for deterministic behavior
        }
        "Invalid option" {
            puts "\nReceived invalid option message."
            if {[handle_error]} continue
        }
        "Current date and time:" {
            ## Successfully got date output
        }
        "Do you want to continue? (yes/no): " {
            send "yes\r"
        }
        "Operation completed successfully." {
            puts "\nAdvanced expect script completed successfully!"
            break
        }
        timeout {
            puts "\nTimeout occurred waiting for prompt."
            if {[handle_error]} continue
        }
        eof {
            puts "\nUnexpected end of file."
            if {[handle_error]} continue
        }
    }
}

## Wait for the program to complete
expect eof

파일을 저장하고 실행 가능하게 만듭니다.

chmod +x ~/project/advanced_expect.exp

고급 스크립트를 실행합니다.

cd ~/project
./advanced_expect.exp

예시 출력:

spawn ./multi_prompt.sh
Please select an option:
1. Show date and time
2. List files
3. Show system info
4. Exit
Enter your choice (1-4): 1
Current date and time:
Wed Nov  1 10:00:00 UTC 2023
Do you want to continue? (yes/no): yes
Continuing...
Operation completed successfully.

Advanced expect script completed successfully!

고급 스크립트 이해

이 고급 스크립트는 몇 가지 중요한 expect 기술을 보여줍니다.

  1. 오류 처리: 오류 또는 예기치 않은 응답을 처리하기 위해 재시도 메커니즘을 사용합니다.
  2. 프로시저 (Procedures): 재사용 가능한 오류 처리를 위해 handle_error라는 사용자 정의 프로시저를 정의합니다.
  3. 제어 흐름: 성공 또는 최대 재시도 횟수에 도달할 때까지 상호 작용을 유지하기 위해 while 루프를 사용합니다.
  4. 다중 expect 패턴: 여러 다른 패턴을 처리하고 각 패턴에 대해 적절한 작업을 수행합니다.
  5. 패턴 순서: expect 블록의 패턴 순서가 중요합니다. 더 구체적인 패턴이 더 일반적인 패턴보다 먼저 와야 합니다.

이러한 기술은 흐름이 다를 수 있거나 오류가 발생할 수 있는 복잡한 대화형 프로그램을 자동화하는 데 적용할 수 있습니다.

일반적인 작업을 위한 실용적인 expect 스크립트 만들기

이 단계에서는 시스템 관리자가 자주 자동화해야 하는 일반적인 작업을 위한 실용적인 expect 스크립트를 만들 것입니다. 파일 작업, 사용자 상호 작용 및 시스템 모니터링에 중점을 둘 것입니다.

expect 를 사용하여 파일 전송 자동화

scp 명령을 사용하여 파일 전송을 자동화하는 expect 스크립트를 만들어 보겠습니다. 이 환경에서는 실제 파일 전송을 수행할 수 없으므로 시뮬레이션합니다.

cd ~/project
nano file_transfer.sh

SCP 와 유사한 파일 전송을 시뮬레이션하려면 다음 내용을 입력합니다.

#!/bin/bash

echo "scp file transfer simulation"
echo "Source file: $1"
echo "Destination: $2"
echo "Password: "
read -s password

if [ "$password" == "transfer123" ]; then
  echo "Transferring file..."
  echo "0%"
  sleep 1
  echo "25%"
  sleep 1
  echo "50%"
  sleep 1
  echo "75%"
  sleep 1
  echo "100%"
  echo "File transfer completed successfully."
else
  echo "Authentication failed."
  exit 1
fi

파일을 저장하고 실행 가능하게 만듭니다.

chmod +x ~/project/file_transfer.sh

이제 이 파일 전송을 자동화하는 expect 스크립트를 만들어 보겠습니다.

cd ~/project
nano file_transfer.exp

다음 내용을 입력합니다.

#!/usr/bin/expect -f

## Set variables
set timeout 10
set source_file "local_file.txt"
set destination "user@remote:/path/to/destination/"
set password "transfer123"

## Create a dummy source file
spawn bash -c "echo 'This is a test file' > $source_file"
expect eof

## Start the file transfer simulation
spawn ./file_transfer.sh $source_file $destination

## Handle the password prompt
expect "Password: "
send "$password\r"

## Monitor the transfer progress
expect "0%"
puts "Transfer started..."

expect "25%"
puts "Transfer 1/4 complete..."

expect "50%"
puts "Transfer 1/2 complete..."

expect "75%"
puts "Transfer 3/4 complete..."

expect "100%"
puts "Transfer almost done..."

expect "File transfer completed successfully."
puts "File transfer automation completed!"

## Clean up the dummy file
spawn bash -c "rm $source_file"
expect eof

파일을 저장하고 실행 가능하게 만듭니다.

chmod +x ~/project/file_transfer.exp

파일 전송 자동화 스크립트를 실행합니다.

cd ~/project
./file_transfer.exp

예시 출력:

spawn bash -c echo 'This is a test file' > local_file.txt
spawn ./file_transfer.sh local_file.txt user@remote:/path/to/destination/
scp file transfer simulation
Source file: local_file.txt
Destination: user@remote:/path/to/destination/
Password:
Transferring file...
0%
Transfer started...
25%
Transfer 1/4 complete...
50%
Transfer 1/2 complete...
75%
Transfer 3/4 complete...
100%
Transfer almost done...
File transfer completed successfully.
File transfer automation completed!
spawn bash -c rm local_file.txt

expect 를 사용하여 사용자 생성 자동화

이제 사용자 생성을 자동화하는 expect 스크립트를 만들어 보겠습니다. 다시, 이 프로세스를 시뮬레이션합니다.

cd ~/project
nano create_user.sh

다음 내용을 입력합니다.

#!/bin/bash

echo "User creation utility"
echo "Please enter new username: "
read username

echo "Please enter password for $username: "
read -s password

echo "Please confirm password: "
read -s password_confirm

if [ "$password" != "$password_confirm" ]; then
  echo "Error: Passwords do not match."
  exit 1
fi

echo "Creating user $username..."
echo "User $username created successfully."
echo "Do you want to add this user to the sudo group? (yes/no): "
read sudo_choice

if [ "$sudo_choice" == "yes" ]; then
  echo "Adding $username to sudo group..."
  echo "User $username added to sudo group."
fi

echo "User setup completed."

파일을 저장하고 실행 가능하게 만듭니다.

chmod +x ~/project/create_user.sh

이제 사용자 생성을 자동화하는 expect 스크립트를 만들어 보겠습니다.

cd ~/project
nano create_user.exp

다음 내용을 입력합니다.

#!/usr/bin/expect -f

## Set variables
set timeout 10
set username "testuser"
set password "P@ssw0rd123"
set add_sudo "yes"

## Start the user creation utility
spawn ./create_user.sh

## Handle the username prompt
expect "Please enter new username: "
send "$username\r"

## Handle the password prompt
expect "Please enter password for $username: "
send "$password\r"

## Handle the password confirmation prompt
expect "Please confirm password: "
send "$password\r"

## Wait for the user creation confirmation
expect "User $username created successfully."

## Handle the sudo prompt
expect "Do you want to add this user to the sudo group? (yes/no): "
send "$add_sudo\r"

## If we chose to add to sudo, wait for confirmation
if {$add_sudo == "yes"} {
    expect "User $username added to sudo group."
}

## Wait for completion
expect "User setup completed."

puts "\nUser creation automation completed successfully!"

파일을 저장하고 실행 가능하게 만듭니다.

chmod +x ~/project/create_user.exp

사용자 생성 자동화 스크립트를 실행합니다.

cd ~/project
./create_user.exp

예시 출력:

spawn ./create_user.sh
User creation utility
Please enter new username:
testuser
Please enter password for testuser:
Please confirm password:
Creating user testuser...
User testuser created successfully.
Do you want to add this user to the sudo group? (yes/no):
yes
Adding testuser to sudo group...
User testuser added to sudo group.
User setup completed.

User creation automation completed successfully!

실용적인 expect 스크립트 이해

우리가 만든 실용적인 스크립트는 실제 자동화에 대한 몇 가지 중요한 개념을 보여줍니다.

  1. 순차적 상호 작용: 두 스크립트 모두 정의된 프롬프트 및 응답 시퀀스를 따릅니다.
  2. 진행 상황 모니터링: 파일 전송 스크립트는 진행 상황을 모니터링하고 사용자 친화적인 업데이트를 제공합니다.
  3. 조건부 로직: 사용자 생성 스크립트는 sudo 옵션을 처리하기 위해 조건부 로직을 사용합니다.
  4. 환경 설정 및 정리: 파일 전송 스크립트는 테스트 파일을 생성하고 정리합니다.

이러한 기술은 다음과 같은 많은 일반적인 시스템 관리 작업을 자동화하는 데 적용할 수 있습니다.

  • 원격 백업
  • 소프트웨어 설치
  • 시스템 구성
  • 일괄 작업

expect를 마스터하면 수동 개입이 필요한 복잡한 대화형 프로세스를 자동화하여 시간 절약 및 인적 오류 가능성을 줄일 수 있습니다.

요약

이 랩에서는 Linux 에서 expect 명령을 사용하여 대화형 명령줄 애플리케이션을 자동화하는 방법을 배웠습니다. 다음 사항에 대한 실질적인 경험을 얻었습니다.

  • expect 명령의 기본 구문을 설치하고 이해하기
  • SSH 로그인을 자동화하고 다양한 인증 프롬프트를 처리하는 스크립트 만들기
  • expect 스크립트에서 여러 프롬프트 및 응답 처리
  • 일반적인 시스템 관리 작업을 위한 실용적인 자동화 스크립트 만들기

expect 명령은 대화형 프로세스를 자동화해야 하는 시스템 관리자 및 개발자를 위한 강력한 도구입니다. expect를 사용하면 반복적인 작업에 대한 수동 개입의 필요성을 없애 시간 절약과 인적 오류 위험 감소를 할 수 있습니다.

이 랩의 몇 가지 주요 내용:

  • expect 명령은 프로그램과 상호 작용하기 위해 패턴 - 액션 모델을 사용합니다.
  • 다양한 가능한 프롬프트 및 오류 조건을 처리하여 스크립트를 더욱 강력하게 만들 수 있습니다.
  • 조건부 로직 및 사용자 정의 프로시저를 사용하여 복잡한 상호 작용을 자동화할 수 있습니다.
  • 실용적인 자동화는 일반적인 시스템 작업의 효율성을 크게 향상시킬 수 있습니다.

이 랩에서 배운 기술을 통해 이제 다양한 대화형 명령줄 애플리케이션에 대한 자체 자동화 스크립트를 만들 수 있습니다.

Linux Commands Cheat Sheet