"리눅스 expect"의 두 판 사이의 차이

53번째 줄: 53번째 줄:


;plus.c (컴파일 후 plus 가 됨)
;plus.c (컴파일 후 plus 가 됨)
* "gcc -o plus plus.c"로 컴파일 후 plus 실행 파일이 되며 expect script의 spawn "./plus"로 호출이 됨
* "gcc -o plus plus.c"로 컴파일 후 plus 실행 파일이 되며 이 프로그램은 expect script의 spawn "./plus"로 호출이 됨
<source lang="c">
<source lang="c">
#include <stdio.h>
#include <stdio.h>

2016년 12월 31일 (토) 01:57 판

1 개요

리눅스 expect
  • CLI 상호작용 자동화 프로그램
  • Tcl 스크립트 언어의 확장판
  • 라이선스: 퍼블릭 도메인
  • SSH, SFTP, SSH 작업 등 자동화 가능
  • Expect 스크립트는 일반적으로 .exp 확장자를 가짐

2 주요 명령어

명령어 설명
send 문자열을 프로세스에 보냄
expect 프로세스로 부터 특정 문자열을 기다림
spawn 명령을 시작

3 Hello World

  • 사용자가 hello를 입력하면 world가 출력됨
#!/usr/bin/expect
expect "hello"
send "world"
→ expect 명령으로 hello가 입력 되기를 기다리며 hello를 입력하면 world를 출력해줌

4 입력 대기 시간 설정

  • 기본적으로 10초 대기후 아무런 입력이 없으면 다음으로 넘어감
  • 시간을 늘리기 위해서 "set timeout 시간"을 입력하여 원하는 시간 설정 가능
#!/usr/bin/expect
set timeout 30
expect "hello"
send "world"

5 프로그램 입력 자동화

expect script
  • expect script로 plus(plus.c 실행 파일)를 호출
#!/usr/bin/expect
set timeout 30

spawn "./plus"

expect "a" {send "1\n"}
expect "b" {send "2\n"}
interact
→ plus 실행 파일이 원하는 a, b 값을 expect script가 1, 2로 각각 입력해주면 plus가 그 값을 처리하여 결과값 3을 출력해줌
plus.c (컴파일 후 plus 가 됨)
  • "gcc -o plus plus.c"로 컴파일 후 plus 실행 파일이 되며 이 프로그램은 expect script의 spawn "./plus"로 호출이 됨
#include <stdio.h>

void main()
{
    int a, b;

    printf("a: ");
    scanf("%d", &a);
    printf("b: ");
    scanf("%d", &b);

    printf("a + b = %d\n", a + b);
}
→ a와 b의 값을 각각 받아 그의 합을 돌려주는 프로그램

6 예시: FTP 작업 자동화

set timeout -1
spawn ftp $remote_server
expect "username:"
send "$my_user_id\r"
expect "password:"
send "$my_password\r"
expect "ftp>"
send "bin\r"
expect "ftp>"
send "prompt\r"
expect "ftp>"
send "mget *\r"
expect "ftp>"
send "bye\r"
expect eof

7 예시: SFTP 작업 자동화

#!/usr/bin/env expect -f
proc connect {passw} {
  expect {
    "Password:" {
      send "$passw\r"
        expect {
          "sftp*" {
            return 0
          }
        }
    }
  }
  return 1
}
set user [lindex $argv 0]
set passw [lindex $argv 1]
set host [lindex $argv 2]
set location [lindex $argv 3]
set file1 [lindex $argv 4]
set file2 [lindex $argv 5]
if { $user == "" || $passw == "" || $host == "" || $location == "" || $file1 == "" || $file2 == "" }  {
  puts "Usage: <user> <passw> <host> <location> <file1 to send> <file2 to send>\n"
  exit 1
}

spawn sftp $user@$host
set rez [connect $passw]
if { $rez == 0 } {
  send "cd $location\r"
  set timeout -1
  send "put $file2\r"
  send "put $file1\r"
  send "ls -l\r"
  send "quit\r"
  expect eof
  exit 0
}
puts "\nError connecting to server: $host, user: $user and password: $passw!\n"
exit 1

8 같이 보기

9 참고 자료

문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}