import
MySQLdb,os,paramiko,sys,time
from multiprocessing
import
Process,Pool
#数据库连接类
class
Connect_mysql:
conn = MySQLdb.connect(host =
'localhost'
, user =
'root'
,passwd =
'123456'
, db =
'manager_system'
, port =
3306
)
cur = conn.cursor()
def __init__(self,username,password=
'NULL'
):
self.username = username
self.password = password
#contect to the login table
def login_check(self): #连接管理系统账号信息数据库并验证用户名密码信息
try
:
self.cur.execute(
"select * from users where username = '%s' and password = '%s'"
% (self.username,self.password))
qur_result = self.cur.fetchall() #
return
the tuple
if
qur_result == (): #database
do
not have
this
user
return
0
else
:
return
1
#database has
this
user
self.cur.close()
self.conn.close()
except MySQLdb.Error,e:
print
'\033[31;1mMysql Error Msg:%s\033[0m'
% e
#contect to the server table
def return_server(self): #连接用户主机列表数据库并返回表信息
self.cur.execute(
"select * from %s_server"
% self.username)
qur_result = self.cur.fetchall()
return
qur_result
def ssh_run(host_info,cmd,sysname): #批量远程命令执行程序
ip,username,password,port= host_info[
1
],host_info[
2
],host_info[
3
],host_info[
4
]
date = time.strftime(
'%Y_%m_%d'
)
date_detial = time.strftime(
'%Y_%m_%d %H:%M:%S'
)
f = file(
'./log/%s_%s_record.log'
% (sysname,date),
'a+'
) #操作日志记录,记录程序所有目录的/log目录里
try
:
s.connect(ip,
int
(port),username,password,timeout=
5
)
stdin,stdout,stderr = s.exec_command(cmd)
cmd_result = stdout.read(),stderr.read()
print
'\033[32;1m-------------%s--------------\033[0m'
% ip
for
line
in
cmd_result:
print line,
print
'\033[32;1m-----------------------------\033[0m'
except:
log =
"Time:%s | Type:%s | Detial:%s | Server:%s | Result:%s\n"
% (date_detial,
'cmd batch'
,cmd,ip,
'failed'
)
f.write(log)
f.close()
print
'\033[31;1mSomething is wrong of %s\033[0m'
% ip
else
:
log =
"Time:%s | Type:%s | Detial:%s | Server:%s | Result:%s\n"
% (date_detial,
'cmd batch'
,cmd,ip,
'success'
)
f.write(log)
f.close()
return
1
def distribute_file(host_info,file_name,sysname): #批量文件分发函数
ip,username,password,port = host_info[
1
],host_info[
2
],host_info[
3
],
int
(host_info[
4
])
date = time.strftime(
'%Y_%m_%d'
)
date_detial = time.strftime(
'%Y_%m_%d %H:%M:%S'
)
f = file(
'./log/%s_%s_record.log'
% (sysname,date),
'a+'
) #日志记录
try
:
t = paramiko.Transport((ip,port))
t.connect(username=username,password=password)
sftp = paramiko.SFTPClient.from_transport(t)
sftp.put(file_name,
'/tmp/%s'
% file_name)
t.close()
except:
log =
"Time:%s | Type:%s | Detial:%s | Server:%s | Result:%s\n"
% (date_detial,
'distribute file'
,file_name,ip,
'failed'
)
f.write(log)
f.close()
print
'\033[31;1mSomething is wrong of %s\033[0m'
% ip
else
:
log =
"Time:%s | Type:%s | Detial:%s | Server:%s | Result:%s\n"
% (date_detial,
'distribute file'
,file_name,ip,
'success'
)
f.write(log)
f.close()
print
"\033[32;1mDistribute '%s' to %s Successfully!\033[0m"
% (file_name,ip)
os.system(
'clear'
)
print
'\033[32;1mWelcome to the Manager System!\033[0m'
while
True: #程序主程序
username = raw_input(
'Username:'
).strip()
password = raw_input(
'Password:'
).strip()
if
len(username) <=
3
or len(password) <
6
:
print
'\033[31;1mInvalid username or password!\033[0m'
continue
#Begin to login
p = Connect_mysql(username,password)
mark = p.login_check()
if
mark ==
0
: #login failed
print
'\033[31;1mUsername or password wrong!Please try again!\033[0m'
elif mark ==
1
: #login success
print
'\033[32;1mLogin Success!\033[0m'
print
'The server list are as follow:'
#seek
for
the server list managed by the system user
p = Connect_mysql(username)
server_list = p.return_server()
for
server
in
server_list:
print
'%s:%s'
% (server[
5
],server[
1
])
while
True:
print
''
'What
do
you want to
do
? #程序主菜单
1
.Execute the command batch.
2
.Distribute file(s) batch.
3
.Exit.
''
'
choice = raw_input(
'\033[32;1mYour choice:\033[0m'
).strip()
if
'1'
<= choice <=
'4'
:pass
else
:
continue
#Execute the command batch.
if
choice ==
'1'
: #批量执行命令程序块
s = paramiko.SSHClient() #调用Paramiko模块
s.load_system_host_keys()
s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
p = Pool(processes=
3
) #设定进程池数据
result_list = []
while
True:
cmd = raw_input(
'\033[32;0mEnter the command(or quit to quit):\033[0m'
)
if
cmd ==
'quit'
:
break
for
h
in
server_list:
result_list.append(p.apply_async(ssh_run,[h,cmd,username])) #the usename
is
system name
#调用相关功能函数,并执行多进程并发
for
res
in
result_list:
res.
get
()
s.close()
#Distribute file(s) batch.
elif choice ==
'2'
: #批量分发文件程序块
s = paramiko.SSHClient() #调用Paramiko模块
s.load_system_host_keys()
s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
p = Pool(processes=
3
)
result_list = [] #save the suanfa that come from the apply_async
while
True:
file_name = raw_input(
'The file you want to distribute(or quit to quit):'
).strip()
start = time.time()
if
file_name ==
'quit'
:
break
file_chcek = os.path.isfile(file_name)
log_list = []
if
file_chcek == False:
print
'\033[31;1mThe file does not exist or it is a directory!\033[0m'
continue
for
h
in
server_list:
result_list.append(p.apply_async(distribute_file,[h,file_name,username])) #the list save the suanfa
for
res
in
result_list:
res.
get
() #run the suanfa
end = time.time()
print
'\033[31;1mCost time:%ss\033[0m'
% str(end - start)
s.close()
#Exit the system
elif choice ==
'3'
: #退出系统
sys.exit(
'\033[32;1mWelcome to use our system!\033[0m'
)