python 使用paramiko, pymysql实现批量管理服务器,paramikopymysql,使用paramiko


使用paramiko,pymysql批量管理主机,用户信息,及主机信息存在数据库中例子:#!/usr/bin/python#--*--coding:utf-8--*--importparamikoimportpymysqlfromthreadingimportThread,RLockimportsysdefconnect_user_tb():"""返回执行sql结果"""conn=pymysql.Connect(host=‘127.0.0.1‘,port=3306,user=‘root‘,password=‘aixocm‘,database=‘oldboy‘,charset=‘utf8‘)cursor=conn.cursor()cursor.execute(‘selectuser_tb.id,username,passwd,email,deptment_tb.namefromuser_tbleftjoindeptment_tbonuser_tb.deptId=deptment_tb.id‘)db_res=cursor.fetchall()cursor.close()conn.close()returndb_resdefauth():"""用户登录"""count=0whilecount<3:username=input("请输入用户名:")passwd=input("请输入密码:")user_info=connect_user_tb()foriinuser_info:ifusername==i[1]andpasswd==i[2]:return(i)else:count+=1print(‘您输入的用户名密码不正确,请重新输入‘)continueelse:returnFalsedefconnect_host_user_tb(data):conn=pymysql.Connect(host=‘127.0.0.1‘,port=3306,user=‘root‘,password=‘aixocm‘,database=‘oldboy‘,charset=‘utf8‘)cursor=conn.cursor()cursor.execute(‘selecthost_tb.ip,host_tb.port,host_tb.username,host_tb.passwdfromhost_user_tbinnerjoinhost_tbonhost_user_tb.hostId=host_tb.idandhost_user_tb.userId=%s‘,[data])host_info=cursor.fetchall()cursor.close()conn.close()returnhost_infoclassMythread(Thread):def__init__(self,host,port,username,passwd,lock,cmd):super().__init__()self.host=hostself.port=portself.username=usernameself.passwd=passwdself.lock=lockself.cmd=cmddefrun(self):withself.lock:try:ssh=paramiko.SSHClient()ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy)#忽略密钥认证,使用密码认证ssh.connect(hostname=self.host,username=self.username,password=self.passwd)stdin,stdout,stderr=ssh.exec_command(self.cmd)print("#######################主机%s开始执行名########################"%(self.host))print(stdout.read().decode(‘utf-8‘))print(stderr.read().decode(‘utf-8‘))ssh.close()print("#######################主机执行结束########################")exceptExceptionase:print(e)defmain():"""程序入口"""lock=RLock()auth_res=auth()ifauth_res:host_info=connect_host_user_tb(auth_res[0])str="用户名:%s邮箱:%s部门:%s"%(auth_res[1],auth_res[3],auth_res[4])print(str)print(‘ipportusernamepasswd‘)forhostinhost_info:print(host[0]+‘‘,host[1],‘‘+host[2]+‘‘+host[3])t_list=[]whileTrue:try:select_ip=input("请输入要执行命令的主机ip,多个主机以逗号分隔,未选择表示执行所有主机:>>").strip()ip_list=select_ip.split(‘,‘)cmd=input("请输入执行的命令>>:").strip()ifnotselect_ip:forhostinhost_info:t=Mythread(host[0],host[1],host[2],host[3],lock,cmd)t.daemon=Truet.start()t_list.append(t)fortint_list:t.join()else:foripinip_list:forhostinhost_info:ifip==host[0]:t=Mythread(host[0],host[1],host[2],host[3],lock,cmd)t.daemon=Truet.start()t_list.append(t)fortint_list:t.join()is_exit=input("是否退出,输入yY/nN")ifis_exit.upper()==‘Y‘:breakexceptExceptionase:print(e)breakelse:print(‘登录失败,退出程序‘)if__name__==‘__main__‘:main()


本文出自 “linux技术” 博客,请务必保留此出处http://haoyonghui.blog.51cto.com/4278020/1947584

python 使用paramiko, pymysql实现批量管理服务器

评论关闭