天天看點

用pexpect遠端執行mysql source指令

有一個遠端其它伺服器自動刷.sql檔案的需求,因為測試中的sql是可能會增加的,是以一個sql檔案裡可能前半部分已經刷過了,搜尋了幾個方法,都是遇到錯誤就會退出執行的,無法像指令行裡用source可以遇到錯誤繼續執行完,于是想到用模拟互動來進入mysql指令行裡執行source

我的mysql不能直接把密碼放到指令行裡,不明原因,沒有深究,順便就加了輸入密碼的互動。

安裝pexpect:

https://blog.csdn.net/weixin_34279061/article/details/92489073

修改檔案夾的所有者和所屬組chown -R root.root pexpect-4.8.0

完整代碼如下:

#!/usr/bin/python
# -*-coding:utf-8-*-
# 利用pexpect模拟mysql指令行互動,使用source指令

import pexpect
import optparse
import sys

def createChildSession(host, username, password, database):
    command = 'mysql -u ' + username + ' -p -D ' + database + ' -h ' + host
    print command
    child = pexpect.spawn(command,logfile=sys.stdout)
    ret = child.expect([pexpect.EOF, 'Enter password:'], timeout=None)
    if ret == 1:
        child.sendline("password")
        ret = child.expect([pexpect.EOF, 'mysql> '])
        if ret == 1:
            ret = child.expect([pexpect.EOF, 'mysql> '])
            if ret == 1:
                print 'run success'
                return
            else:
                print('[-] Error Connecting')
                return
        else:
            print('[-] Error Connecting')
            return
    else:
        print('[-] Error Connecting')
        return
    return child


def main():
    parse = optparse.OptionParser('Usage %prog -H <host> -u <username> -p <password> -d <database>')
    parse.add_option('-H', dest='host', type='string', help='specify the host')
    parse.add_option('-u', dest='username', type='string', help='specify the username')
    parse.add_option('-p', dest='password', type='string', help='specify the password')
    parse.add_option('-d', dest='database', type='string', help='specify the database')

    (options, args) = parse.parse_args()
    host = options.host
    username = options.username
    password = options.password
    database = options.database

    session = createChildSession(host, username, password, database)


if __name__ == '__main__':
    main()