1. 程式人生 > >Swift 呼叫 Shell 指令碼

Swift 呼叫 Shell 指令碼

最近在進行一個工作專案,需要在swift中呼叫shell指令碼:

Swift呼叫shell介面

  • 1. GetQCRLog.swift
//  GetQCRLog 
//  Created by Cyril on 7/19/18.
//  Copyright © 2018 Cyril. All rights reserved.
import Foundation
import Cocoa
class GetQCRLog: NSObject{
    let homePath = NSHomeDirectory() + "/Desktop/Cyril/"
    override init() {
        super
.init() searchAndDownLogsFromQCR() unzipDownFiles() foundContentFromFiles() } /** 從QCR上批量下載指定 SNs 的logs */ func searchAndDownLogsFromQCR(){ let scriptPath = homePath + "/getQCRLog" let snPath = homePath + "/sn.txt" let logPath = homePath + "/QCR_LOG"
let logPartName:String = "123.zip" execShellScript(scriptPath, logPath, snPath, logPartName) } /** 解壓已下載的檔案 */ func unzipDownFiles(){ let scriptPath = homePath + "/unzipFiles" let logPath = homePath + "/QCR_LOG" execShellScript(scriptPath, logPath) } /** 批量查詢DCSD檔案中內容 “STATION_IP”,並將結果儲存在STATION_IP.txt */
func foundContentFromFiles(){ let scriptPath = homePath + "/foundContentFromFiles" let searchFileDir = homePath + "/QCR_LOG" let searchFileName = "DCSD.log" let searchContent = "STATION_IP" let resultFile = homePath + "STATION_IP.txt" execShellScript(scriptPath, searchFileDir, searchFileName, searchContent, resultFile) } /** Swift 呼叫任意引數個數Shell指令碼 * arg0 : scriptPath // 第一個引數是指令碼路徑 * arg1 : ${1} // 第二個引數是指令碼引數1 (log存放路徑) * arg2 : ${2} // 第三個引數是指令碼引數2 (sn.txt 路徑) * arg3 : ${3} // 第四個引數是指令碼引數3 (log名稱,如:SW-DOWNLOAD.zip) * ... * argn : ${n} */ func execShellScript(_ members: String...){ var index = 0 var scriptPath:String! // var logPath:String! var args:Array = [String]() for i in members{ if index == 0{ // 第一個引數是指令碼路徑 scriptPath = i index += 1 continue } args.append(i) index += 1 } print(args) let task = Process() task.launchPath = scriptPath task.arguments = args let pipe = Pipe() task.standardOutput = pipe task.launch() let data = pipe.fileHandleForReading.readDataToEndOfFile() let output: String = String(data: data, encoding: String.Encoding.utf8)! print(output) } }

被呼叫的指令碼工具

  • unzipFiles.sh
    批量解壓指定目錄下的zip檔案
#!/bin/bash
if [ $# -ne 1 ] ; then
    echo "please input:./unzipFiles filedir"
    exit
fi

file_path="$1"     #加上雙引號才能支援檔案路徑中帶有空格的路徑名(/tmp/test 2/),使用./changefile.sh /tmp/test\ 2

if [ -d "$file_path" ] && cd "$file_path"
then
    for filename in `ls *.zip`
        do
                unzip -o  $filename -d ${file_path}/${filename%.*}    #解壓檔案
        done
fi
echo "finished---spend time:$SECONDS"      #顯示執行時間
  • foundContentFromFiles.sh
    檢索 指定目錄指定檔名 內容是否包含 關鍵字 ,並返回當前行內容
#!/bin/bash
if [$# -ne 4]
then
        echo "Usage:"
        echo "e.g. :./foundContentFromFiles searchFileDir searchFileName searchContent resultFile"
        exit
fi

searchFileDir = $1
searchFileName = $2
searchContent = $3
resultFile = $4
find $1 -iname $2 | xargs grep $3 >> $4
  • getQCRLog.sh
    從伺服器批量下載log。這段程式碼有點亂,不具有通用性,有空再改。
#!/bin/bash
## Modified by Cyril at 18-07-21 01:35
echo "開始呼叫getQCRLog指令碼"
if [ $# -ne 3 ]
then
        echo "Usage:"
        echo "e.g. :./getQCRLog_1117 Log_Out_Put SN_File Targit_log"
        exit
fi

WOSID=""
USER_NAME="***"
PASS_WORD="***"
Original_ip="http://10.172.5.131"
Father_url="http://10.172.5.131/cgi-bin/WebObjects/QCR"
Referer_url="${Father_url}"
new_ip=""
temp_file="/tmp/1.txt"
User_Agent="Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:45.0) Gecko/20100101 Firefox/45.0"
Accept_type="text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
Accept_lang="zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3"
Log_file="/tmp/result.csv"
Log_Out_Put=$1
echo "Log_Out_Put = ${Log_Out_Put}"
SN_File=$2
echo "SN_File = ${SN_File}"
## Log_Out_Put="./QCR_LOG"
Targit_log=$3
echo "Targit_log = ${Targit_log}"

#set -x

if [ -e ${temp_file} ]; then
rm "${temp_file}"
echo "rm temp file"
fi

##### to get wosid / version / username / password
#### input username and password
curl "${Father_url}" -H 'Host: 10.172.5.131' -H "User-Agent: ${User_Agent}" -H "Accept: ${Accept_type}" -H "Accept-Language: ${Accept_lang}" --compressed -H 'Connection: keep-alive' > ${temp_file}
#curl "${Father_url}" -H 'Host: 10.172.5.131' -A "${User_Agent}" -H "Accept: ${Accept_type}" -H "Accept-Language: ${Accept_lang}" --compressed -H 'Connection: keep-alive' > ${temp_file}

button_name="`cat "${temp_file}" | grep -i "input name" | awk -F'"' '{printf $10}'`"
new_ip="`cat "${temp_file}" | grep -i 'method="post"' | awk -F'"' '{printf $6}'`"
WOSID="`cat "${temp_file}" | grep -i 'method="post"' | awk -F'"' '{printf $6}' | awk -F'/' '{printf $7}'`"
curl "${Original_ip}${new_ip}" -H 'Host: 10.172.5.131' -H "User-Agent: ${User_Agent}" -H "Accept: ${Accept_type}" -H "Accept-Language: ${Accept_lang}" --compressed -H "Referer: ${Referer_url}" -H 'Connection: keep-alive' --data "UserName=${USER_NAME}&Password=${PASS_WORD}&${button_name}.x=37&${button_name}.y=7&wosid=${WOSID}" > ${temp_file}

Search_url="`cat ${temp_file} | grep "search_links" -B1 | awk -F'"' '{print $6}' | tr -d '[:cntrl:]'`"

cat "${SN_File}" | while read Serial_Number
do
        #echo "Serial_Number=$Serial_Number"
        #echo "Search_url=$Search_url"
        curl -q "${Original_ip}${Search_url}" -H 'Host: 10.172.5.131' -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:45.0) Gecko/20100101 Firefox/45.0' -H 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8' -H 'Accept-Language: zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3' --compressed -H "Referer: ${Referer_url}" -H 'Connection: keep-alive' --data "1.5.5.29.1=${Serial_Number}&1.5.5.29.3=Search&wosid=${WOSID}" > ${temp_file}
        #exit 0
        View_Log_Url="`cat ${temp_file} | grep "View Process Logs" | awk -F'"' '{print $4}' | head -1 | tr -d '[:cntrl:]'`"
        curl -q "${Original_ip}${View_Log_Url}" -H 'Host: 10.172.5.131' -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:45.0) Gecko/20100101 Firefox/45.0' -H 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8' -H 'Accept-Language: zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3' --compressed -H "Referer: ${Referer_url}" -H 'Connection: keep-alive' -H 'Cache-Control: max-age=0' > ${temp_file}
        cat ${temp_file} | grep "${Targit_log}" | awk -F'"' '{print $3}' | awk -F'<' '{print $1}' | sed 's/>//g' | while read SS_LOG_Name
        do
                SS_LOG_Url="`cat ${temp_file} | grep "${SS_LOG_Name}" -A9 | tail -1 | awk -F'"' '{print $4}' | tr -d '[:cntrl:]'`"
                echo $SS_LOG_Name:$SS_LOG_Url
                echo "logname=$Log_Out_Put/$SS_LOG_Name"
                curl -s --create-dirs "${Original_ip}${SS_LOG_Url}?$(($RANDOM%8+1)),$(($RANDOM%8+1))" -H 'Host: 10.172.5.131' -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:45.0) Gecko/20100101 Firefox/45.0' -H 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8' -H 'Accept-Language: zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3' --compressed -H "Referer: ${Referer_url}" -H 'Connection: keep-alive' -o "${Log_Out_Put}/${SS_LOG_Name}"
                echo "****get sn:${Serial_Number} log return[$?]"
        done
done