将linux系统用户导入mysql表

下面这个程序实现的一个很简单的功能,读取passwd文件,将里面的用户信息写入到mysql里面,

具体代码如下:

 

 1 #!/usr/bin/python
 2 
 3 import pymysql
 4 import time
 5 
 6 
 7 '''
 8 
 9 CREATE TABLE `os_user` (
10   `user` varchar(20) NOT NULL,
11   `haspass` char(5) NOT NULL,
12   `uid` int(10) NOT NULL,
13   `gid` int(10) NOT NULL,
14   `descuser` varchar(100) NOT NULL,
15   `homedir` varchar(100) NOT NULL,
16   `loginshell` varchar(100) NOT NULL,
17   PRIMARY KEY (`uid`),
18   UNIQUE KEY `unique_var` (`user`,`uid`)
19 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
20 
21 
22 '''
23 
24 try:
25     conn = pymysql.connect(host='127.0.0.1',unix_socket='/tmp/mysql.sock',\
26                            user='root',passwd='123456',db='pydb')
27     cur = conn.cursor()
28     f = open('passwd')
29 
30     try:
31         for i in f.readlines():
32             Tmplist = list(i.strip('\n').split(':'))
33             sql = 'INSERT INTO os_user \
34                   (user,haspass,uid,gid,descuser,homedir,loginshell) values \
35                   (\'%s\',\'%s\',%s,%s,\'%s\',\'%s\',\'%s\')' % \
36                   (Tmplist[0],Tmplist[1],Tmplist[2],Tmplist[3],Tmplist[4],Tmplist[5],Tmplist[6])
37             cur.execute(sql)
38             time.sleep(1)
39             conn.commit()
40             print 'Create user %s Successful..' % Tmplist[0]
41     except pymysql.err.IntegrityError as e:
42          print 'User %s exits.' % Tmplist[0]
43          print 'Please check, Exit...' 
44     except Exception as e:
45          print 'Error : %s ' % e
46 
47 except Exception as e:
48      print 'Error : %s ' % e
49 
50 
51 finally:
52     cur.close()
53     conn.close()
54     f.close()

 

posted @ 2017-07-02 18:41  Topic  阅读(425)  评论(0编辑  收藏  举报
转载请注明出处. 作者: 运维的自我修养 地址: http://www.cnblogs.com/topicjie/