Swift备份MySQL数据库

想找一个自动备份博客数据库的程序,然而并没有找到合适的.那就自己写一个吧,也不麻烦…

GitHub地址

Package.swift文件

1
2
3
4
5
6
7
8
9
10
11
12
// swift-tools-version:3.1

import PackageDescription

let package = Package(
name: "MySQLBackup",
targets: [],
dependencies: [
.Package(url: "https://github.com/PerfectlySoft/PerfectLib.git", majorVersion: 2),
.Package(url: "https://github.com/PerfectlySoft/Perfect-SMTP.git", majorVersion: 1)
]
)

runProc.swift文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import PerfectLib
import Foundation
#if os(Linux)
import SwiftGlibc
#else
import Darwin
#endif
func runProc(_ cmd: String, args: [String], read: ((String) -> ())? = nil) throws {
try runProc(cmd, args: args, envs: [String : String](), read: read)
}

// shortcut to execute something on the commandline
// i.e.
// let _ = try runProc("git", args: ["clone","--depth","1","https://github.com/PerfectlySoft/PerfectDocs.git","PerfectDocsSource"], read: true)

func runProc(_ cmd: String, args: [String], envs: [String:String], read: ((String) -> ())? = nil) throws {

// Set up environmental variables
// Note that the PATH, HOME and LANG vars are specifically configured.
// HOME will be set to the runtime user's home directory
var ienvs = [("PATH", "/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local"),
("HOME", ProcessInfo.processInfo.environment["HOME"]!),
("LANG", "en_CA.UTF-8")]

// Additional environmental variables can be added here.
// This allows for situations like AWS where credentials can be specified as ENV Vars.
for e in envs {
ienvs.append(e)
}

// Building the command with arguments a s a correctly formatted string
var newCmd = "'\(cmd)\'"
for n in 0..<args.count {
newCmd.append(" ${\(n)}")
}

// Execute the command.
// For more information see https://www.perfect.org/docs/sysProcess.html
let proc = try SysProcess("/bin/bash", args: ["--login", "-c", newCmd] + args, env: ienvs)

// Reading the result of the command
if let read = read {
while true {
do {
guard let s = try proc.stdout?.readSomeBytes(count: 1024) , s.count > 0 else {
break
}
let str = UTF8Encoding.encode(bytes: s)
read(str)

} catch PerfectLib.PerfectError.fileError(let code, _) {
if code != EINTR {
break
}
}
}
}
let res = try proc.wait(hang: true)
if res != 0 {
let s = try proc.stderr?.readString()
throw PerfectError.systemError(Int32(res), s!)
}
}

main.swift文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
//mysqldump -uroot -pJxt51921100% tokendemo > /Users/Adrift/Desktop/tokendemo.sql
//swift build -c release & ./.build/release/MySQLBackup
import PerfectLib
import Foundation
import PerfectSMTP

let dbUsername = "root"
let dbPassword = "Jxt51921100%"
let dbName = "perfect_testing"

let clientUrl = "smtps://smtp.qq.com"
let clientUsername = "jingxuetao@qq.com"
let clientPassword = "xxxxxxxx"

let fromName = "发抖喵小咪"
let fromAddress = "jingxuetao@qq.com"

let toName = "发抖喵小咪"
let toAddress = "jingxuetao@qq.com"

var content = ""
var wait = true
do {
try runProc("mysqldump", args: ["-u\(dbUsername) -p\(dbPassword) \(dbName)"]) { (str) in
content.append(str)
}
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
let dateStr = formatter.string(from: Date())
let path = "/Users/Adrift/Desktop/\(dateStr).sql"

let manager = FileManager()
let data = content.data(using: String.Encoding.utf8)!
let created = manager.createFile(atPath: path, contents: content.data(using: String.Encoding.utf8)!, attributes: nil)

let client = SMTPClient(url: clientUrl, username: clientUsername, password: clientPassword)
let from = Recipient(name: fromName, address: fromAddress)
let to = Recipient(name: toName, address: toAddress)

var email = EMail(client: client)
email.subject = "博客数据库备份 \(dateStr)"
email.from = from
email.to.append(to)

email.text = "博客数据库备份"
email.attachments.append(path)

try email.send(completion: { (code, header, body) in
print(code)
print(header.utf8)
print(body.utf8)
wait = false
})
while wait {
sleep(1)
}
} catch {
print(error)
}
print("done!")

然而,Swift运行的系统环境需要Ubuntu,so 晚上回去重装一下博客系统吧…

–EOF–