반응형

출처: http://rose-dev.tistory.com/entry/pexpect-%EB%A5%BC-%EC%9D%B4%EC%9A%A9%ED%95%9C-ssh-%EC%A0%91%EC%86%8D-%EC%9E%90%EB%8F%99%ED%99%94


http://rhkdvy1200.tistory.com/entry/Pexpect%EB%A1%9C-SSH-%EC%97%B0%EA%B2%B0%ED%95%98%EA%B8%B0


0. 참고 URL

http://pexpect.readthedocs.io/en/stable/overview.html

http://www.bx.psu.edu/~nate/pexpect/pexpect.html

http://linux.die.net/man/1/expect


1. pexpect 설치


sudo easy_install pexpect

sudo pip install pexpect


* mac el capitan 버전 에서 pip install 오류가 날 때는 --ignore-installed 옵션을 붙여주세요

ex) sudo pip install --ignore-installed pexpect



2. pexpect 란


expect 란 스크립트 언어인 Tcl(Tool Command Language) 로 만든 CLI 자동화 도구이다.

pexpect  python 에서 사용 가능한 expect 를 말한다.


일반 shell 을 사용할 경우 consol 창에 interactive 하게 입력해야하지만 

expect 를 사용하면 화면에 특정 문자열이 출력될때까지 기다렸다가 응답하는 형태의 처리가 가능하다.

* expect 로 할 수 있는 일: ssh, scp, ftp 등 



3. pexpect 주요 메소드 

    spawn(command)

      control 을 child application 으로 넘겨줍니다.

    expect(pattern)

      화면에 pattern 에 맞는 문자열이 나올때까지 기다립니다.

    sendline(str)

      문자열을 입력합니다.

    interact()

      control 을 다시 user 로 넘겨줍니다.


4. ssh 자동 접속 예제

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import pexpect
 
host = 'xx.xx.xx.xx'
name = 'username'
pwd = '********'
 
def ssh(host):
    return 'ssh %s@%s' % (name, host)
 
def wait_password(host):
    return '%s@%s\'s password:' % (name, host)
 
child = pexpect.spawn(ssh(host))
child.setwinsize(400, 400)
child.expect(wait_password(host))
child.sendline(pwd)
child.interact()
child.close()





import pexpect
PROMPT = ['# ','>>> ','> ','\$ ']

def send_command(child, cmd):
        child.sendline(cmd)
        child.expect(PROMPT)
        print child.before
def connect(user, host, password):
        ssh_newkey = 'Are you sure you want to continue connecting'
        connStr = 'ssh '+user+'@'+host
        child = pexpect.spawn(connStr)
        ret = child.expect([pexpect.TIMEOUT, ssh_newkey])
        if ret == 0:
                print '[-] Error Connecting'
                return
        if ret == 1:
                child.sendline('yes')
                ret = child.expect([pexpect.TIMEOUT, \
                '[P|p]assword:'])
                if ret == 0:
                        print '[-] Error Connecting'
                        return
                child.sendline(password)
                child.expect(PROMPT)
                return child
def main():
        host = '127.0.0.1'
        user = 'root'
        password = 'root'
        child = connect(user, host, password)
        send_command(child, 'cat /etc/shadow | grep root')
if __name__ == '__main__':
        main()


반응형

+ Recent posts