Run The Bridge

expect를 사용하여 원격지 파일 가져오기 본문

Cloud/Linux

expect를 사용하여 원격지 파일 가져오기

anfrhrl5555 2022. 7. 29. 21:52
728x90
반응형

expect

나는 /bin/bash만 많이 사용해서 expect라는 게 있다는 것도 얼마 전에 알았다.

 

오늘은 expect를 이용하여 원격지 파일을 가져오는 코드를 작성한다.

 

물론 그전에 원격지 서버에 어떤 파일이 어느 위치에 있는지는 알고 있어야 한다(ex: /root/2022-07-29.text.txt)

 

간단하게 짠거라 별 기능은 없다 ㅎㅎ... sftp를 이용해 파일을 가져오는 코드만 필요할 때 유용하게 사용했으면 좋겠다.

#!/usr/bin/env expect

set user [lindex $argv 0]

set hostip [lindex $argv 1]

set password [lindex $argv 2]

spawn /usr/bin/sftp ${user}@${hostip}

expect "${user}@${hostip}'s password:"

send "${password}\r";

expect "sftp>"

send "get /root/started-log.txt\n"

expect "sftp>"

send "exit\n"

interact

.sh 파일로 만들고 실행은 다음과 같이 하면 된다.

 

특수문자가 있을 시 ''로 묶어주면 정상적으로 인식한다.

./[FILE_NAME] root 10.140.20.20 'P@ssw0rd!@#'

이렇게 사용하면 원격지 파일에 '2022-07-29-test.txt'라는 파일을 알아서 가져온다.

root@p-iskim-master /opt/expect # ./expect-login.sh root 10.140.20.20 'P@ssw0rd!@#'
spawn /usr/bin/sftp root@10.140.20.20
root@10.140.20.20's password:
Connected to 10.140.20.20.
sftp> get /root/2022-07-29-test.txt
Fetching /root/2022-07-29-test.txt to 2022-07-29-test.txt
sftp> exit

파일 이름을 변경하면서 가져오고 싶으면 get 부분을 수정하면 된다.

send "get /root/2022-07-29-test.txt [Dst_FILE_NAME]\n"

정상적으로 파일을 가져온 모습을 확인할 수 있다.

root@p-iskim-master /opt/expect # ls -al 2022-07-29-test.txt
-rw-r--r-- 1 root root 0  7월 29 21:48 2022-07-29-test.txt
728x90
반응형

'Cloud > Linux' 카테고리의 다른 글

for 랜덤 난수 출력하는 방법  (2) 2022.11.04
가상 터미널 종료하기  (3) 2022.08.02
vi편집기를 이롭게 만드는 vi 단축키  (1) 2022.06.25
터미널을 이롭게 만드는 bash shell 단축키  (4) 2022.06.25
시간 맞추기  (0) 2022.03.23
Comments