1. config.ini 만들기 

  2. 실행파일 가져가기

  3. 실행 테스트

변경개발시          : 파이썬 3.x , paramiko , ConfigParser, pyinstaller 설치

ini 수정 수 사용시 : ini 수정만 함, 서버스크립 작성 (1.2), tomcat war root 위치 설정확인

was : tomcat 8.5


1. 소스들

 1.1 ini 파일 생성 ( 예제 )

from configparser import ConfigParser
config = ConfigParser()
config['settings'] = {
'go': 'set -m; /home/tomcat/apache-tomcat-8.5.53/bin/startup.sh',
'stop': '/home/tomcat/apache-tomcat-8.5.53/bin/shutdown.sh',
'waslog': 'tail -f /home/tomcat/apache-tomcat-8.5.53/logs/catalina.out',
'rebilud': '/home/tomcat/bt.sh'
}

config['ssh'] = {
'id': 'root',
'pw': 'pw',
'host': '192.168.0.8',
'port': '22'
}

config['files'] = {
'upfile': 'C:/Users/torrms/Desktop/web.war',
'dwfile': '/home/tomcat/web.war'
}
with open('./config.ini', 'w') as f:
config.write(f)

 예파일  config.ini

[settings]
go = set -m; /home/tomcat/apache-tomcat-8.5.53/bin/startup.sh
stop = /home/tomcat/apache-tomcat-8.5.53/bin/shutdown.sh
waslog = tail -f /home/tomcat/apache-tomcat-8.5.53/logs/catalina.out
rebilud = /home/tomcat/bt.sh

[ssh]
id = root
pw = pw
host = 198.168.0.8
port = 22

[files]
upfile = C:/Users/torrms/Desktop/web.war
dwfile = /home/tomcat/web.war

 

 1.2  rebilud 를 위한 sh 생성 예

 - 직접 서버에서 실행권한 및 스크립트를 작성한다. 

 - war 반영 위치를 tomcat 에 설정한다. 또는 위치 확인

 - 경로는 반드시 full 경로 사용 .. 등의 사용은 안됨.

 -  예)

  > vi bt.sh

rm -rf web
mkdir web
cd web
jar xvf /home/tomcat/web.war
cd /home/tomcat
mv web.war ./bakwar/wab_20$(date +%Y%m%d_%H%M%S).war

 

 2. 실행파일 (첨부 확인) 또는 소스 (접는글 참조, 단 들여쓰기가 날라가네요 ^^)

더보기

#실행용으로 변경시 확인하세요 ^^

import paramiko
import os, sys
from configparser import ConfigParser

# ssh 명령을 수행한다.
# exit status를 리턴한다.
def ssh_execute(ssh, command, is_print=True):
# ssh 명령의 결과로 exit status를 구하는게 쉽지 않다.
# 따라서, 명령의 끝에 "mark=$?"를 출력하여,
# 최종 exit statud를 구할 수 있도록 한다.
exit_status=0
mark="ssh_helper_result_mark!!@@="
command=command+";echo " + mark + "$?"

try:
stdin, stdout, stderr = ssh.exec_command(command, get_pty=True)
except Exception as e:
print(e)
raise e

for line in stdout:
msg=line.strip('\n')
if (msg.startswith(mark)):
exit_status=msg[len(mark):]
else:
if (True == is_print):
print(line.strip('\n'))

return int(exit_status)

# sftp 상에 경로를 생성한다.
# remote 경로가 directory이면, is_dir에 True를 전달한다.
def mkdir_p(sftp, remote, is_dir=False):
dirs_ = []
if is_dir:
dir_ = remote
else:
dir_, basename = os.path.split(remote)
while len(dir_) > 1:
dirs_.append(dir_)
dir_, _ = os.path.split(dir_)

if len(dir_) == 1 and not dir_.startswith("/"):
dirs_.append(dir_) # For a remote path like y/x.txt

while len(dirs_):
dir_ = dirs_.pop()
try:
sftp.stat(dir_)
except:
print("making ... dir", dir_)
sftp.mkdir(dir_)

#https://greenfishblog.tistory.com/258
# sftp 상에 파일을 업로드한다.
# src_path에 dest_path로 업로드한다. 두개 모두 file full path여야 한다.
def file_upload(sftp, src_path, dest_path):
#mkdir_p(sftp, dest_path)
try:
sftp.put(src_path, dest_path)
except Exception as e:
print("fail to upload " + src_path + " ==> " + dest_path)
raise e
print("success to upload " + src_path + " ==> " + dest_path)
return "0"

def get_sftp(ssh):
try:
sftp = paramiko.SFTPClient.from_transport(ssh.get_transport())
except Exception as e:
print(e)
raise e
return sftp


def get_ssh(host_ip, port, id, pw):
try:
# ssh client 생성
ssh = paramiko.SSHClient()

# ssh 정책 설정
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

# connect
ssh.connect(hostname=host_ip, port=port, username=id, password=pw)
except Exception as e:
print(e)
raise e

return ssh

# 프로세스 시작 ##################################
if __name__ == '__main__':
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

parser = ConfigParser()
parser.read('config.ini')

print(parser.sections())

ip = parser.get('ssh', 'host')
port = parser.get('ssh', 'port')
id = parser.get('ssh', 'id')
pwd = parser.get('ssh', 'pw')

ssh.connect(ip,port=port, username=id, password=pwd)

# 웹서버 명령
#exitcode = ssh_execute(ssh, "cat /project/EDIP/edip.sh")
#print("result : %d" % exitcode)
go = parser.get('settings', 'go')
stop = parser.get('settings', 'stop')
waslog = parser.get('settings', 'waslog')
rebilud = parser.get('settings', 'rebilud')

#자신의 반영 파일 로컬위치
upfile = parser.get('files', 'upfile')
dwfile = parser.get('files', 'dwfile')

print(go , stop, waslog, rebilud, upfile, dwfile)

print(os.path.exists(upfile))
if os.path.exists(upfile):
print(str(os.path.getsize(upfile)/1024/1024) + " MB")
else:
print("파일이 " + upfile + "존재 하지 않습니다.")
sys.exit()

#
#https://greenfishblog.tistory.com/258

# 정지
a = ssh_execute(ssh, stop)
while True:
if a == 0:
print("정지 : %d" % a)
break

#파일 업로드

sftp = get_sftp(ssh)
res = file_upload(sftp, upfile, dwfile)
while True:
if res == "0":
print("파일업로드 : %s" % res)
break



#반영
a = ssh_execute(ssh, rebilud)
while True:
if a == 0:
print("반영 : %d" % a)
break

#재시작
a = ssh_execute(ssh, go)
while True:
if a == 0:
print("재시작 : %d" % a)
break

#로그확인
a = ssh_execute(ssh, waslog)
while True:
if a == 0:
print("result : %d" % a)
break

ssh.close()
sftp.close()

 

autorebuild.zip
8.61MB

 

3. 실행 테스트

dos 창이 뜨면서 실행 및 등등의 작업이 진행됨을 알수 있다.

+ Recent posts