有一个远程其它服务器自动刷.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()

主要参考文章:

​https://www.jianshu.com/p/ea53b74c299c​

​https://blog.csdn.net/weixin_42107374/article/details/112017061​