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

猜你喜欢

转载自blog.csdn.net/u011865919/article/details/81227507