Example of python Implementation Automated Online Script
- 2021-07-06 11:28:38
- OfStack
Procedure description:
This procedure realizes the package file in the development program server uploaded to the formal production environment through this script (Note: the production environment and the development environment do not communicate)
Basic idea of program:
Copy the package in the development environment to the local bastion machine
Unzip the package
Obtain the decompressed files and synchronize them to the production server
Main knowledge points: python library os. system () basic use of python call xshell command
How to use the program:
python addline. py Development Host ip Package Target Host ip Upload Directory Upload Number
For example: python addline. py 240/home/shaojinlong/2018-7-17/activityIqiyi_766bb10bd811e40732cf79dffde9a904 _ 20180717. tar. gz 165/home/zhouja01 190122
Specific procedures:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/7/17 20:56
# @Author : Zhou Jiaan
# @File : addline.py
import os
import sys
import re
import time
## Usage:
# python addline.py 240 filename 165 directory runnum
## Such as: python addline.py 240 /home/shaojinlong/2018-7-17/activityIqiyi_766bb10bd811e40732cf79dffde9a904_20180717.tar.gz 165 /home/zhouja01 190122
## Copy a file
def cpfile(source_host,source_dir, runnum):
os.system("mkdir -p /sx/%s" % (runnum))
os.system("scp %s:%s /sx/%s " % (source_host,source_dir, runnum))
## Extract a file
def tarfile(source_dir,runnum):
target_test = re.split(r'/', source_dir)
print(target_test[-1])
os.system(
"tar zxvf /sx/%s/%s -C /sx/%s/" % (runnum,target_test[-1], runnum))
time.sleep(1) # Dormancy 1 Seconds Because the synchronization script needs to get the log 1 Seconds
# Synchronize files
def syncfile(filename, runnum,target_host):
os.system("ssh %s 'mkdir -p /home/zhouja01/sx/%s'" % (target_host,runnum))
os.system("scp -r /sx/%s/%s %s:/home/zhouja01/sx/%s/" %
(runnum, filename,target_host,runnum))
# os.system("ssh 165 'sudo -u apps sh /home/zhouja01/bcp_web.sh /home/zhouja01/sx/%s/%s /home/apps/ananetest/%s'" %
# (runnum, filename, filename))
def delfile(runnum):
os.system("mv /sx/%s /sx/wc"%(runnum))
def main():
source_host=sys.argv[1] # Source host ip
source_dir=sys.argv[2] # Source host file
target_host=sys.argv[3] # Target host ip
target_dir=sys.argv[4] # Target host file
runnum=sys.argv[5] #oa Serial number
cpfile(source_host,source_dir,runnum) # Copy files from source host to bastion
tarfile(source_dir,runnum) # Extract a file
# Get the unzipped file name
with open('/var/log/sx.log', 'r') as f:
lines = f.readlines()
last_line = lines[-1]
print(last_line)
filename = re.split(r'/', last_line)
print(filename[3])
syncfile(filename[3], runnum,target_host) # Synchronize files to the target host
delfile(runnum) # Move the home base files to the completion directory
if __name__ == '__main__':
main()