python数据库操作对主机批量管理

时间:2023-03-09 13:23:34
python数据库操作对主机批量管理
 import paramiko
import MySQLdb
conn = MySQLdb.connect(host='192.168.1.101',user='root',passwd='',db='host')
cur = conn.cursor(cursorclass=MySQLdb.cursors.DictCursor)
reCout = cur.execute('select pass,users,ip,name from host,user WHERE `user`.name = "root" and `user`.id=`host`.id')
nRet = cur.fetchall()
conn.commit()
cur.close()
conn.close()
for i in nRet:
hosts = i['ip']
users = i ['users']
passs = i['pass']
print hosts,users,passs
transport = paramiko.Transport((hosts, 22))
transport.connect(username=users, password=passs)
ssh = paramiko.SSHClient()
ssh._transport = transport
stdin, stdout, stderr = ssh.exec_command('ls /root')
print stdout.read()
transport.close()

数据表

python数据库操作对主机批量管理

2.以组的方式批量管理

import paramiko
import MySQLdb
conn = MySQLdb.connect(host='192.168.1.101',user='root',passwd='',db='host')
cur = conn.cursor(cursorclass=MySQLdb.cursors.DictCursor)
reCout = cur.execute('select pass,users,ip,name from host,user WHERE `user`.name = "admin" and `user`.id=`host`.id')
nRet = cur.fetchall()
conn.commit()
cur.close()
conn.close()
for i in nRet:
hosts = i['ip']
#users = i ['users']
groups =i['name']
passs = i['pass']
print hosts,groups,passs
transport = paramiko.Transport((hosts, 22))
transport.connect(username=groups, password=passs)
ssh = paramiko.SSHClient()
ssh._transport = transport
stdin, stdout, stderr = ssh.exec_command('ls /home/')
print stdout.read()
transport.close()

数据结构

主机列表

python数据库操作对主机批量管理

组列表

python数据库操作对主机批量管理

组列表的id为主机列表id的外键

查询语句

select pass,users,ip,name from  host,user WHERE `user`.name = "admin" and `user`.id=`host`.id