셸 프로 그래 밍 의 대화 면제(Here Document+Expect)

24627 단어 셸 스 크 립 트
글 목록
  • 1.Here Document 개술
  • 1.1 Here Document 사용 주의사항
  • 1.2 여기 문서 의 상호작용 면제
  • 1.3 여기 문서 변수 설정
  • 1.4 Here 문서 형식 제어
  • 1.5 Here Document 여러 줄 주석
  • 2.Expect 개술
  • 2.1 기본 명령
  • 2.2 Expect 문법
  • 2.3 예상 실행 방식
  • 3.실험 사례
  • 3.1 사용 자 를 만 들 고 비밀 번 호 를 설정 합 니 다
  • 3.2 ssh 자동 로그 인 실현
  • 1.Here 문서 개술
  • I/O 를 사용 하여 명령 목록 을 대화 식 프로그램 에 제공 합 니 다
  • 표준 입력 의 대체 품
  • 문법 서식
      <<  
    ...
    ...
      
    

    1.1 Here 문서 사용 주의사항
  • 표 시 는 임의의 합 법 적 인 문 자 를 사용 할 수 있 습 니 다
  • 끝 에 있 는 표 시 는 반드시 체크 를 해 야 합 니 다.앞 에 문자 가 있 으 면 안 됩 니 다
  • 끝 에 표 시 된 태그 뒤에 도 문자 가 있 을 수 없습니다(빈 칸 포함)
  • 시작 표시 전후의 빈 칸 은 생략 됩 니 다
  • 1.2 Here 문서 상호작용 면제
  • read 명령 을 통 해 입력 을 받 고 인쇄
  • [root@localhost ~]# vim hello.sh
    #!/bin/bash
    read i <<EOF
    hello world
    EOF
    echo $i
    [root@localhost ~]# chmod +x hello.sh 
    [root@localhost ~]# ./hello.sh 
    hello world
    
  • passwd 를 통 해 사용자 에 게 비밀 번 호 를 설정 합 니 다
  • [root@localhost ~]# vim user.sh
    #!/bin/bash
    passwd lisi <<EOF
    123abc    
    123abc
    EOF
    [root@localhost ~]# ./passwd.sh 
         lisi     。
         :     :      7    
             :passwd:               。
    

    1.3 여기 문서 변수 설정
  • 변수 교체
  • [root@localhost ~]# vim user.sh 
    #!/bin/bash
    name="cllt"
    filename="test.txt"
    cat > $filename <<EOF
    this is $name.com
    EOF
    [root@localhost ~]# cat test.txt 
    this is cllt.com
    
  • 변수 설정
  • [root@localhost ~]# vim user.sh 
    #!/bin/bash
    first="hello"
    filename=$(cat <<EOF
    this is cllt.com
    my name is cllt
    $first
    EOF
    )
    echo $filename
    [root@localhost ~]# ./user.sh 
    this is cllt.com my name is cllt hello
    

    1.4 Here 문서 형식 제어
  • 변수 교체 기능 닫 기
  • [root@localhost ~]# vim user.sh 
    #!/bin/bash
    first="hello"
    cat <<'EOF'            '         '
    this is cllt.com
    $first
    EOF
    [root@localhost ~]# ./user.sh 
    this is cllt.com
    $first
    
  • 줄 마다 tab 문자 제거
  • [root@localhost ~]# vim user.sh 
    #!/bin/bash
    first="hello"
    cat <<-EOF           '-       TAB  '
            this is cllt.com
            $first
    EOF
    [root@localhost ~]# ./user.sh 
    this is cllt.com
    hello
    

    1.5 Here Document 여러 줄 주석
    Here Document 방식 을 통 해 Bash 가 여러 줄 주석 을 지원 합 니 다.
    [root@localhost ~]# vim user.sh 
    #!/bin/bash
    first="hello"
    : <<EOF                 '         '
    this is cllt.com
    $first
    EOF
    echo "lemon"
    [root@localhost ~]# ./user.sh 
    lemon
    

    2.기대 개술
  • Expect 는 tcl 을 바탕 으로 하 는 도구 이 고 expect 는 자동화 제어 와 테스트 를 하 는 도구 입 니 다.주로 셸 스 크 립 트 에서 상호작용 할 수 없 는 문 제 를 해결 하고 대규모 Liux 운영 에 도움 이 됩 니 다
  • Linux 운영 과 개발 에서 저 희 는 원 격 로그 인 서버 를 자주 사용 해 야 합 니 다.로그 인 하 는 과정 에서 상호작용 을 하 는 과정 이 므 로 yes/no password 등 정 보 를 입력 해 야 할 수도 있 습 니 다.이 입력 을 모 의 하기 위해 서 는 Expect 스 크 립 트
  • 을 사용 할 수 있 습 니 다.
    Linux 시스템 에 서 는 expect 가 자체 적 으로 가지 고 있 지 않 으 므 로 스스로 설치 해 야 합 니 다.
    yum install expect -y
    

    2.1 기본 명령
  • expect 는 마지막 출력 결과 에 지정 한 문자열 이 포함 되 어 있 는 지 판단 합 니 다.있 으 면 바로 돌아 갑 니 다.그렇지 않 으 면 시간 초과 후 돌아 갑 니 다.spawn 에서 시 작 된 프로 세 스 의 출력 을 캡 처 하여 명령 을 받 은 후 출력 할 수 있 습 니 다.그리고 원 하 는 문자열 과 일치 합 니 다
  • send 는 프로 세 스에 문자열 을 보 냅 니 다.사용자 의 입력 을 모 의 하 는 데 사 용 됩 니 다.이 명령 은 자동 으로 줄 을 바 꿀 수 없습니다.-\r(리 턴)
  • spawn 시작 프로 세 스,후속 상호작용 정보 추적
  • expect eof(끝 문자)는 실행 이 끝 날 때 까지 기다 리 고 있 습 니 다(자동화 작업 을 수행 할 때 보통 expect eof 를 사용 합 니 다)
  • interact(종료 문자)실행 완료 후 상호작용 상 태 를 유지 하고 컨트롤 러 에 게 제어 권 을 맡 깁 니 다
  • set 설정 시간 초과,만 료 되면 후속 명령 단 위 는 초 timeout-1 은 시간 초과 가 없 음 을 표시 합 니 다.기본 적 인 상황 에서 timeout 은 10 초
  • exp_contiune 은 expec 가 명령 을 계속 실행 할 수 있 도록 합 니 다
  • send_user 리 턴 명령,echo
  • 수신 매개 변수 Expect 스 크 립 트 는 bash 에서 전달 하 는 매개 변 수 를 받 아들 일 수 있 습 니 다.[lindex$argv n]획득 n 은 0 부터 각각 첫 번 째,두 번 째,세 번 째..매개 변수
  • 2.2 기대 문법
  • 단일 분기 문법
  • expect "password: " {send "mypassword\r“;}
    
  • 다 중 분기 모드 문법
  • expect "aaa" {send“AAA\r"}    'send           ,    \r 
    '
    expect "bbb" {send“BBB\r"} expect "ccc" {send“CCC\r"}
    expect {    '     aaa bbb ccc      ,     send      expect  '
    "aaa"{send“AAA\r"}
    "bbb" {send“BBB\r"}
    "CCC" {send“CCC\r"}
    }
    
    expect {   'exp_ continue         ,     aaa,    send           bbb'
    "aaa" {send“AAA"; exp_ continue}
    "bbb" {send“BBB"; exp_ continue}
    "ccc" {send“CCC"}
    }
    

    2.3 기대 실행 방식
  • 직접 실행
  • [root@localhost ~]# vim demo01.sh 
    #!/usr/bin/expect
    #    
    set timeout 20
    #    
    log_file test.log
    #    
    log_user 1
    
    #    
    set hostname [lindex $argv 0]
    set password [lindex $argv 1]
    
    #    
    spawn ssh root@${hostname}
    
    #      
    expect {
         "connecting (yes/no)"
         {send "yes\r";exp_continue}
         "*password:"
         {send "${password}\r";}
    }
    #     
    interact
    [root@localhost ~]# ./demo01.sh 192.168.179.144 123456
    spawn ssh root@192.168.179.144
    root@192.168.179.144's password: 
    Last login: Tue Jul 28 09:34:58 2020 from 192.168.179.1
    [root@server ~]# 
    
  • 삽입 실행
  • [root@localhost ~]# vim demo02.sh 
    #!/bin/bash
    hostname=$1
    password=$2
    #expect  
    /usr/bin/expect <<-EOF
    spawn ssh root@${hostname}
    
    #      
    expect {
         "connecting (yes/no)"
         {send "yes\r";exp_continue}
         "*password:"
         {send "${password}\r";}
    }
    expect "*]#"
    send "exit\r"
    expect eof
    EOF
    [root@localhost ~]# ./demo02.sh 192.168.179.144 123456
    spawn ssh root@192.168.179.144
    root@192.168.179.144's password: 
    Last login: Tue Jul 28 09:35:17 2020 from 192.168.179.100
    [root@server ~]# exit
      
    Connection to 192.168.179.144 closed.
    [root@localhost ~]# 
    

    3.실험 사례
    3.1 사용자 생 성 및 비밀번호 설정
    [root@localhost ~]# vim demo03.sh 
    #!/bin/bash
    users=$1
    passwd=$2
    useradd ${users}
    #expect  
    /usr/bin/expect <<-EOF
    spawn passwd ${users}
    #      
    expect {
         "  :"
         {send "$2\r";exp_continue}
         "  :"
         {send "$2\r";}
    }
    #expect eof
    EOF
    [root@localhost ~]# ./demo03.sh wangwu 123456
    spawn passwd wangwu
         wangwu     。
         :
         :      8    
             :
    passwd:               。
    

    3.2 ssh 자동 로그 인 실현
    [root@localhost ~]# vim demo04.sh 
    
    #!/usr/bin/expect
    set timeout 5
    set hostname [lindex $argv 0]
    set password [lindex $argv 1]
    spawn ssh ${hostname}
    expect {
         "Connection refused" exit
         "Name or service not known" exit
         "connecting (yes/no)"{send "yes\r";exp_continue}
         "*password:"{send "${password}\r"}
    }
    interact
    exit
    [root@localhost ~]# ./demo04.sh 192.168.179.144 123456
    spawn ssh 192.168.179.144
    root@192.168.179.144's password: 
    Last login: Tue Jul 28 09:50:59 2020 from 192.168.179.100
    [root@server ~]# exit
    [root@localhost ~]# ./demo04.sh 
    spawn ssh root@
    ssh: Could not resolve hostname : Name or service not known
    [root@localhost ~]# 
    

    좋은 웹페이지 즐겨찾기