Linux

[Linux] expect를 사용하여 SSH 자동 생성 Shell Script

DBA_JSH 2017. 1. 18. 18:00

[테스트 환경]

- Linux CentOs7


1. Linux Expect란?

expect는 tenlet이나 ftp와 같은 interactvie한 환경이 필요한 곳에서 특정 문자열을 기다리고(expect), 정해진 문자열을 자동으로 보내는(send)등의 처리를 하는 스크립트 언어


2.expect의 기본 개념 

아래 블로그에 매우 상세하게 나와 있으며, 기본 개념 이해 후 아래의 스크립트 확인

(출처 : http://ktdsoss.tistory.com/149)


3. expect 설치

[root@test01 ~]# yum install expect
Loaded plugins: fastestmirror
base                                                                   | 3.6 kB  00:00:00     
extras                                                                 | 3.4 kB  00:00:00     
updates                                                                | 3.4 kB  00:00:00     
(1/4): base/7/x86_64/group_gz                                          | 155 kB  00:00:00     
(2/4): extras/7/x86_64/primary_db                                      |  98 kB  00:00:00     
(3/4): updates/7/x86_64/primary_db                                     | 1.3 MB  00:00:00     
(4/4): base/7/x86_64/primary_db                                        | 5.6 MB  00:00:00     
Determining fastest mirrors
 * base: centos.mirror.cdnetworks.com
 * extras: centos.mirror.cdnetworks.com
 * updates: centos.mirror.cdnetworks.com
Resolving Dependencies
--> Running transaction check
---> Package expect.x86_64 0:5.45-14.el7_1 will be installed
--> Processing Dependency: libtcl8.5.so()(64bit) for package: expect-5.45-14.el7_1.x86_64
--> Running transaction check
---> Package tcl.x86_64 1:8.5.13-8.el7 will be installed
--> Finished Dependency Resolution

Dependencies Resolved

==============================================================================================
 Package             Arch                Version                      Repository         Size
==============================================================================================
Installing:
 expect              x86_64              5.45-14.el7_1                base              262 k
Installing for dependencies:
 tcl                 x86_64              1:8.5.13-8.el7               base              1.9 M

Transaction Summary
==============================================================================================
Install  1 Package (+1 Dependent package)

Total download size: 2.1 M
Installed size: 4.9 M
Is this ok [y/d/N]: y
Downloading packages:
경고: /var/cache/yum/x86_64/7/base/packages/expect-5.45-14.el7_1.x86_64.rpm: Header V3 RSA/SHA256 Signature, key ID f4a80eb5: NOKEY
Public key for expect-5.45-14.el7_1.x86_64.rpm is not installed
(1/2): expect-5.45-14.el7_1.x86_64.rpm                                 | 262 kB  00:00:00     
(2/2): tcl-8.5.13-8.el7.x86_64.rpm                                     | 1.9 MB  00:00:05     
----------------------------------------------------------------------------------------------
Total                                                         375 kB/s | 2.1 MB  00:00:05     
Retrieving key from file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7
Importing GPG key 0xF4A80EB5:
 Userid     : "CentOS-7 Key (CentOS 7 Official Signing Key) "
 Fingerprint: 6341 ab27 53d7 8a78 a7c2 7bb1 24c6 a8a7 f4a8 0eb5
 Package    : centos-release-7-2.1511.el7.centos.2.10.x86_64 (@anaconda)
 From       : /etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7
Is this ok [y/N]: y
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction
Warning: RPMDB altered outside of yum.
  Installing : 1:tcl-8.5.13-8.el7.x86_64                                                  1/2 
  Installing : expect-5.45-14.el7_1.x86_64                                                2/2 
  Verifying  : 1:tcl-8.5.13-8.el7.x86_64                                                  1/2 
  Verifying  : expect-5.45-14.el7_1.x86_64                                                2/2 

Installed:
  expect.x86_64 0:5.45-14.el7_1                                                               

Dependency Installed:
  tcl.x86_64 1:8.5.13-8.el7                                                                   

Complete!


4. Shell Script Source code

#!/bin/bash
#!/usr/bin/expect

#Admin 접속 정보
USER=root
PW=root

#Ssh 생성 사용자 정보
SshUser=DA_JSH
SshPwd=DA_JSH

#IP주소
IpMaster=192.168.3.206
IpSlave=192.168.3.207

#Host Name
InMasterHostName=test01
InSlaveHostName=test02

#호스트네임 및 SSH설정 
function SettingSSH()
{
   #마스터 서버 호스트네임 및 SSH설정 
   echo "Setting SSH(Master Server)"
	 expect -c "
	 set timeout 3
	 spawn ssh -o StrictHostKeyChecking=no $USER@$IpMaster
	 expect 'password:'
	         send \"$PW\\r\"
	 expect '#'
	        send \"hostname $InMasterHostName\\r\"
	        send \"hostname\\r\"
			    send \"echo -e $IpMaster $InMasterHostName >/etc/hosts\\r\"
	        send \"echo -e $IpSlave $InSlaveHostName >>/etc/hosts\\r\"
	        send \"sed -i -- 's/#RSAAuthentication/RSAAuthentication/g' /etc/ssh/sshd_config\\r\"
	        send \"sed -i -- 's/#PubkeyAuthentication/PubkeyAuthentication/g' /etc/ssh/sshd_config\\r\"
			    send \"service sshd restart\\r\"
			    send \"su - $SshUser \\r\"
			    send \"ssh-keygen -b 1024 -t rsa\\r\"
	 expect ':'
			send \"\r\"
	 expect ':'		
			send \"\r\"
	 expect 'again:'		
			send \"\r\"	
	 expect '$'		
			send \"ssh-copy-id $InMasterHostName\\r\"
	 expect '?'
	        send \"yes\\r\"
	 expect 'password:'
	         send \"$SshPwd\\r\"
	 expect '$'
	        send \"ssh-copy-id $InSlaveHostName\\r\"
	 expect '?'
	        send \"yes\\r\"
	 expect 'password:'
	        send \"$SshPwd\\r\"
	 expect '?'
	        send \"ssh $InMasterHostName\\r\"
			send \"exit\\r\"
	 expect '?'
	        send \"ssh $InSlaveHostName\\r\"
					send \"exit\\r\"		
					send \"exit\\r\"		
			
	 expect eof
	 "
	 
	 echo "Master Server SSH Setting complete!"
	  
	 #슬레이브 서버 호스트네임 및 SSH설정 
	 echo "Setting SSH(Slave Server)"
	 expect -c "
	 set timeout 3
	 spawn ssh -o StrictHostKeyChecking=no $USER@$IpSlave
	 expect 'password:'
	         send \"$PW\\r\"
	 expect '#'
	        send \"hostname $InSlaveHostName\\r\"
	        send \"hostname\\r\"
			    send \"echo -e $IpMaster $InMasterHostName >/etc/hosts\\r\"
	        send \"echo -e $IpSlave $InSlaveHostName >>/etc/hosts\\r\"
	        send \"sed -i -- 's/#RSAAuthentication/RSAAuthentication/g' /etc/ssh/sshd_config\\r\"
	        send \"sed -i -- 's/#PubkeyAuthentication/PubkeyAuthentication/g' /etc/ssh/sshd_config\\r\"
					send \"service sshd restart\\r\"
					send \"su - $SshUser \\r\"
					send \"ssh-keygen -b 1024 -t rsa\\r\"
	 expect ':'
			    send \"\r\"
	 expect ':'		
			    send \"\r\"
	 expect 'again:'		
			    send \"\r\"	
	 expect '$'		
			    send \"ssh-copy-id $InMasterHostName\\r\"
	 expect '?'
	        send \"yes\\r\"
	 expect 'password:'
	        send \"$SshPwd\\r\"
	 expect '$'
	        send \"ssh-copy-id $InSlaveHostName\\r\"
	 expect '?'
	        send \"yes\\r\"
	 expect 'password:'
	        send \"$SshPwd\\r\"
	 expect '?'
	        send \"ssh $InMasterHostName\\r\"
			    send \"exit\\r\"
	 expect '?'
	        send \"ssh $InSlaveHostName\\r\"
			    send \"exit\\r\"		
			    send \"exit\\r\"		
			
	 expect eof
	 "
	 echo "Slave Server SSH Setting complete!"
}
#함수 실행
SettingSSH


5. Expect를 사용하여 2개 서버의 SSH 자동 설치 실행 화면

[root@test01 opt]# chmod 755 SSH_Auto_Installer.SH 
[root@test01 opt]# ./SSH_Auto_Installer.SH 
Setting SSH(Master Server)
spawn ssh -o StrictHostKeyChecking=no root@192.168.3.206
root@192.168.3.206's password: 
Last login: Tue Jan 17 11:39:33 2017 from test01
[root@test01 ~]# hostname test01
[root@test01 ~]# hostname
test01
[root@test01 ~]# echo -e 192.168.3.206 test01 >/etc/hosts
[root@test01 ~]# echo -e 192.168.3.207 test02 >>/etc/hosts
[root@test01 ~]# sed -i -- 's/#RSAAuthentication/RSAAuthentication/g' /etc/ssh/sshd_config
[root@test01 ~]# sed -i -- 's/#PubkeyAuthentication/PubkeyAuthentication/g' /etc/ssh/sshd_config
[root@test01 ~]# service sshd restart
Redirecting to /bin/systemctl restart  sshd.service
[root@test01 ~]# su - DA_JSH 
[DA_JSH@test01 ~]$ ssh-keygen -b 1024 -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/home/DA_JSH/.ssh/id_rsa): 
Created directory '/home/DA_JSH/.ssh'.
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /home/DA_JSH/.ssh/id_rsa.
Your public key has been saved in /home/DA_JSH/.ssh/id_rsa.pub.
The key fingerprint is:
9c:38:30:6e:c6:34:7b:f3:1c:78:22:2d:a3:b6:30:7a DA_JSH@test01
The key's randomart image is:
+--[ RSA 1024]----+
|                 |
|                 |
|    =            |
|   + * + .       |
|    X O S        |
|   + = B .       |
|o o     o        |
|.+E.             |
|...              |
+-----------------+
[DA_JSH@test01 ~]$ ssh-copy-id test01
The authenticity of host 'test01 (192.168.3.206)' can't be established.
ECDSA key fingerprint is 3b:d2:0e:0e:54:b6:7e:fa:27:ea:f4:32:4f:e5:ac:e9.
Are you sure you want to continue connecting (yes/no)? yes
/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
DA_JSH@test01's password: 

Number of key(s) added: 1

Now try logging into the machine, with:   "ssh 'test01'"
and check to make sure that only the key(s) you wanted were added.

[DA_JSH@test01 ~]$ ssh-copy-id test02
The authenticity of host 'test02 (192.168.3.207)' can't be established.
ECDSA key fingerprint is 7b:0a:34:cb:cc:ef:c4:04:7f:3f:b5:cd:7d:a6:ec:d3.
Are you sure you want to continue connecting (yes/no)? yes
/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
DA_JSH@test02's password: 

Number of key(s) added: 1

Now try logging into the machine, with:   "ssh 'test02'"
and check to make sure that only the key(s) you wanted were added.

[DA_JSH@test01 ~]$ ssh test01
exit
Last login: Tue Jan 17 11:44:45 2017
[DA_JSH@test01 ~]$ exit
logout
Connection to test01 closed.
[DA_JSH@test01 ~]$ ssh test02
exit
exit
[DA_JSH@test02 ~]$ exit
logout
Connection to test02 closed.
[DA_JSH@test01 ~]$ Master Server SSH Setting complete!
Setting SSH(Slave Server)
spawn ssh -o StrictHostKeyChecking=no root@192.168.3.207
root@192.168.3.207's password: 
Last login: Wed Jan 18 17:26:21 2017 from test01
[root@test02 ~]# hostname test02
[root@test02 ~]# hostname
test02
[root@test02 ~]# echo -e 192.168.3.206 test01 >/etc/hosts
[root@test02 ~]# echo -e 192.168.3.207 test02 >>/etc/hosts
[root@test02 ~]# sed -i -- 's/#RSAAuthentication/RSAAuthentication/g' /etc/ssh/sshd_config
[root@test02 ~]# sed -i -- 's/#PubkeyAuthentication/PubkeyAuthentication/g' /etc/ssh/sshd_config
[root@test02 ~]# service sshd restart
Redirecting to /bin/systemctl restart  sshd.service
[root@test02 ~]# su - DA_JSH 
마지막 로그인: 수  1월 18 17:31:24 KST 2017 test01에서 시작 일시 pts/1
[DA_JSH@test02 ~]$ ssh-keygen -b 1024 -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/home/DA_JSH/.ssh/id_rsa): 
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /home/DA_JSH/.ssh/id_rsa.
Your public key has been saved in /home/DA_JSH/.ssh/id_rsa.pub.
The key fingerprint is:
bb:86:62:1f:09:8a:01:6e:fd:9c:d1:7a:55:94:07:7b DA_JSH@test02
The key's randomart image is:
+--[ RSA 1024]----+
|           oo    |
|          ....   |
|.          o.E   |
|o .   .   . .    |
|.o ... .S.       |
|.o .o.+...       |
|. .  =oo.        |
|    o o...       |
|   . o...        |
+-----------------+
[DA_JSH@test02 ~]$ ssh-copy-id test01
The authenticity of host 'test01 (192.168.3.206)' can't be established.
ECDSA key fingerprint is 3b:d2:0e:0e:54:b6:7e:fa:27:ea:f4:32:4f:e5:ac:e9.
Are you sure you want to continue connecting (yes/no)? yes
/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
DA_JSH@test01's password: 

Number of key(s) added: 1

Now try logging into the machine, with:   "ssh 'test01'"
and check to make sure that only the key(s) you wanted were added.

[DA_JSH@test02 ~]$ ssh-copy-id test02
The authenticity of host 'test02 (192.168.3.207)' can't be established.
ECDSA key fingerprint is 7b:0a:34:cb:cc:ef:c4:04:7f:3f:b5:cd:7d:a6:ec:d3.
Are you sure you want to continue connecting (yes/no)? yes
/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
DA_JSH@test02's password: 

Number of key(s) added: 1

Now try logging into the machine, with:   "ssh 'test02'"
and check to make sure that only the key(s) you wanted were added.

[DA_JSH@test02 ~]$ ssh test01
Last login: Tue Jan 17 11:45:15 2017 from test01
exit
[DA_JSH@test01 ~]$ exit
logout
Connection to test01 closed.
[DA_JSH@test02 ~]$ ssh test02
exit
exit
Last login: Wed Jan 18 17:31:32 2017
[DA_JSH@test02 ~]$ exit
logout
Connection to test02 closed.
[DA_JSH@test02 ~]$ Slave Server SSH Setting complete!
[root@test01 opt]# 


'Linux' 카테고리의 다른 글

Linux/Unix 접속한 사용자 명령어를 기록하는 방법  (0) 2015.06.19
파일 인코딩  (0) 2015.06.05
Windows와 Linux의 폴더 공유  (0) 2015.06.05