开发堡垒机以前,先学习Python的paramiko模块,该模块基于SSH用于链接远程服务器并执行相关操做。html
SSHClientpython
用于链接远程服务器并执行基本命令mysql
基于用户名密码链接:linux
#!/usr/bin/env python
# --*--coding:utf-8 --*--
import paramiko
#建立SSH对象
ssh = paramiko.SSHClient()
# 容许链接不在know_hosts文件中的主机
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# 链接服务器
ssh.connect(hostname='192.168.1.30', port=22, username='wulaoer', password='123456')
while True:
NAM = raw_input('input:')
# 执行命令
stdin, stdout, stderr = ssh.exec_command(NAM)
# 获取命令结果
print stdout.read()
result = stdout.read()
# 关闭链接
ssh.close()
#!/usr/bin/env python
# --*--coding:utf-8 --*--
import paramiko
transport = paramiko.Transport(('192.168.1.30', 22))
transport.connect(username='wulaoer', password='123456')
ssh = paramiko.SSHClient()
ssh._transport = transport
stdin, stdout, stderr = ssh.exec_command('df')
print stdout.read()
transport.close()
基于公钥密钥链接:ios
#!/usr/bin/env python
# --*--coding:utf-8 --*--
import paramiko
private_key = paramiko.RSAKey.from_private_key_file('/home/auto/.ssh/id_rsa')
# 建立SSH对象
ssh = paramiko.SSHClient()
# 容许链接不在know_hosts文件中的主机
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# 链接服务器
ssh.connect(hostname='192.168.1.30', port=22, username='wulaoer', pkey=private_key)
# 执行命令
stdin, stdout, stderr = ssh.exec_command('df')
# 获取命令结果
result = stdout.read()
# 关闭链接
ssh.close()
#!/usr/bin/env python
# --*--coding:utf-8 --*--
import paramiko
private_key = paramiko.RSAKey.from_private_key_file('/home/auto/.ssh/id_rsa')
transport = paramiko.Transport(('192.168.1.30', 22))
transport.connect(username='wulaoer', pkey=private_key)
ssh = paramiko.SSHClient()
ssh._transport = transport
stdin, stdout, stderr = ssh.exec_command('df')
transport.close()
SFTPClientgit
用于链接远程服务器并执行上传下载sql
基于用户名密码上传下载shell
#!/usr/bin/env python
# --*--coding:utf-8 --*--
import paramiko
transport = paramiko.Transport(('192.168.1.30',22))
transport.connect(username='wulaoer',password='123')
sftp = paramiko.SFTPClient.from_transport(transport)
# 将location.py 上传至服务器 /tmp/test.py
sftp.put('/tmp/location.py', '/tmp/test.py')
# 将remove_path 下载到本地 local_path
sftp.get('remove_path', 'local_path')
transport.close()
基于公钥密钥上传下载数据库
#!/usr/bin/env python
# --*--coding:utf-8 --*--
import paramiko
private_key = paramiko.RSAKey.from_private_key_file('/home/auto/.ssh/id_rsa')
transport = paramiko.Transport(('192.168.1.30', 22))
transport.connect(username='wulaoer', pkey=private_key )
sftp = paramiko.SFTPClient.from_transport(transport)
# 将location.py 上传至服务器 /tmp/test.py
sftp.put('/tmp/location.py', '/tmp/test.py')
# 将remove_path 下载到本地 local_path
sftp.get('remove_path', 'local_path')
transport.close()
实现思路:windows

堡垒机执行流程:
一、管理员为用户在服务器上建立账号(将公钥放置服务器,或者使用用户名密码)
二、用户登陆堡垒机,输入堡垒机用户名密码,现实当前用户管理的服务器列表
三、用户选择服务器,并自动登陆
四、执行操做并同时将用户操做记录
注:配置.brashrc实现ssh登陆后自动执行脚本,如:/usr/bin/python /home/wulaoer/menu.py
实现过程
步骤一,使用用户登陆
#!/usr/bin/env python
# --*--coding:utf-8 --*--
import getpass
user = raw_input('username:')
pwd = getpass.getpass('password:')
if user == 'wulaoer' and pwd == '123':
print '登录成功'
else:
print '登录失败'
步骤二,根据用户获取相关服务器列表
dic = {
'laowu': [
'172.16.103.189',
'c10.puppet.com',
'c11.puppet.com',
],
'wu': [
'c100.puppet.com',
]
}
host_list = dic['laowu']
#用户能够链接的主机IP
print 'please select:'
for index, item in enumerate(host_list, 1):
print index, item
#循环能够链接的主机
inp = raw_input('your select (No):')#选择要链接的IP
inp = int(inp)
hostname = host_list[inp-1]#链接的主机IP
port = 22
步骤三,根据用户名、私钥登陆服务器
tran = paramiko.Transport((hostname, port,))
#链接服务器的端口和IP
tran.start_client()
default_path = os.path.join(os.environ['HOME'], '.ssh', 'id_rsa')
#链接方式,使用密钥
key = paramiko.RSAKey.from_private_key_file(default_path)
#密钥默认路径
tran.auth_publickey('wulaoer', key)
#链接用户名和密钥
# 打开一个通道
chan = tran.open_session()
# 获取一个终端
chan.get_pty()
# 激活器
chan.invoke_shell()
#########
# 利用sys.stdin,肆意妄为执行操做
# 用户在终端输入内容,并将内容发送至远程服务器
# 远程服务器执行命令,并将结果返回
# 用户终端显示内容
#########
用户监控日志:
while True:
# 监视用户输入和服务器返回数据
# sys.stdin 处理用户输入
# chan 是以前建立的通道,用于接收服务器返回信息
readable, writeable, error = select.select([chan, sys.stdin, ],[],[],1)
if chan in readable:
try:
x = chan.recv(1024)
if len(x) == 0:
print '\r\n*** EOF\r\n',
break
sys.stdout.write(x)
sys.stdout.flush()
except socket.timeout:
pass
if sys.stdin in readable:
inp = sys.stdin.readline()
chan.sendall(inp)
# 获取原tty属性
oldtty = termios.tcgetattr(sys.stdin)
try:
# 为tty设置新属性
# 默认当前tty设备属性:
# 输入一行回车,执行
# CTRL+C 进程退出,遇到特殊字符,特殊处理。
# 这是为原始模式,不认识全部特殊符号
# 放置特殊字符应用在当前终端,如此设置,将全部的用户输入均发送到远程服务器
tty.setraw(sys.stdin.fileno())
chan.settimeout(0.0)
while True:
# 监视 用户输入 和 远程服务器返回数据(socket)
# 阻塞,直到句柄可读
r, w, e = select.select([chan, sys.stdin], [], [], 1)
if chan in r:
try:
x = chan.recv(1024)
if len(x) == 0:
print '\r\n*** EOF\r\n',
break
sys.stdout.write(x)
sys.stdout.flush()
except socket.timeout:
pass
if sys.stdin in r:
x = sys.stdin.read(1)
if len(x) == 0:
break
chan.send(x)
finally:
# 从新设置终端属性
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, oldtty)
def windows_shell(chan):
import threading
sys.stdout.write("Line-buffered terminal emulation. Press F6 or ^Z to send EOF.\r\n\r\n")
def writeall(sock):
while True:
data = sock.recv(256)
if not data:
sys.stdout.write('\r\n*** EOF ***\r\n\r\n')
sys.stdout.flush()
break
sys.stdout.write(data)
sys.stdout.flush()
writer = threading.Thread(target=writeall, args=(chan,))
writer.start()
try:
while True:
d = sys.stdin.read(1)
if not d:
break
chan.send(d)
except EOFError:
# user hit ^Z or F6
pass
注:密码验证t.auth_password(username,pw)
详见:paramiko源码demo
Python操做 Mysql模块的安装
linux:
yum install MySQL-python
window:
http://files.cnblogs.com/files/wupeiqi/py-mysql-win.zip
SQL基本使用
一、数据库操做
show databases; #查看数据库
use [databasename]; #切换数据或者进入数据库
create database [name]; #新建数据库
二、数据表操做
show tables; #查看数据库表
create table students #新建数据库表
(
id int not null auto_increment primary key,
name char(8) not null,
sex char(4) not null,
age tinyint unsigned not null,
tel char(13) null default "-"
);
CREATE TABLE `wb_blog` (
`id` smallint(8) unsigned NOT NULL,
`catid` smallint(5) unsigned NOT NULL DEFAULT '0',
`title` varchar(80) NOT NULL DEFAULT '',
`content` text NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `catename` (`catid`)
) ;
三、数据库操做
insert into students(name,sex,age,tel) values('wulaoer','man',18,'151515151')
#插入表数据
delete from students where id =2;
#删除表数据
update students set name = 'dn' where id =1;
#修改表数据
select * from students
#查看整个表
四、其余
更多mysql操做萌点这里
Python MySQL API
1、插入数据
#!/usr/bin/env python
# --*--coding:utf-8 --*--
import MySQLdb
conn = MySQLdb.connect(host='127.0.0.1',user='root',passwd='123456',db='mydb')
#根据IP、数据用户名、密码、数据库名。链接数据库
cur = conn.cursor()
reCount = cur.execute('insert into UserInfo(Name,Address) values(%s,%s)',('wulaoer','usa'))
#进入数据库,插入一条数据
conn.commit()
cur.close()
conn.close()
print reCount
#!/usr/bin/env python
# --*--coding:utf-8 --*--
import MySQLdb
conn = MySQLdb.connect(host='127.0.0.1',user='root',passwd='1234',db='mydb')
#根据IP、数据用户名、密码、数据库名。链接数据库
cur = conn.cursor()
li =[
('wulaoer','usa'),
('dn','usa'),
]
#插入的表
reCount = cur.executemany('insert into UserInfo(Name,Address) values(%s,%s)',li)
conn.commit()
cur.close()
conn.close()
print reCount
注意:cur.lastowid
2、删除数据
#!/usr/bin/env python
# --*--coding:utf-8 --*--
import MySQLdb
conn = MySQLdb.connect(host='127.0.0.1',user='root',passwd='1234',db='mydb')
#根据IP、数据用户名、密码、数据库名。链接数据库
cur = conn.cursor()
reCount = cur.execute('delete from UserInfo')
#删除数据
conn.commit()
cur.close()
conn.close()
print reCount
3、修改数据
#!/usr/bin/env python
# --*--coding:utf-8 --*--
import MySQLdb
conn = MySQLdb.connect(host='127.0.0.1',user='root',passwd='1234',db='mydb')
#根据IP、数据用户名、密码、数据库名。链接数据库
cur = conn.cursor()
reCount = cur.execute('update UserInfo set Name = %s',('alin',))
#修改数据
conn.commit()
cur.close()
conn.close()
print reCount
4、查看数据
#!/usr/bin/env python
# --*--coding:utf-8 --*--
# ############################## fetchone/fetchmany(num) ##############################
import MySQLdb
conn = MySQLdb.connect(host='127.0.0.1',user='root',passwd='1234',db='mydb')
#根据IP、数据用户名、密码、数据库名。链接数据库
cur = conn.cursor()
reCount = cur.execute('select * from UserInfo')
#查看表数据
print cur.fetchone()
print cur.fetchone()
cur.scroll(-1,mode='relative')
print cur.fetchone()
print cur.fetchone()
cur.scroll(0,mode='absolute')
print cur.fetchone()
print cur.fetchone()
cur.close()
conn.close()
print reCount
# ############################## fetchall ##############################
import MySQLdb
conn = MySQLdb.connect(host='127.0.0.1',user='root',passwd='1234',db='mydb')
#根据IP、数据用户名、密码、数据库名。链接数据库
#cur = conn.cursor(cursorclass = MySQLdb.cursors.DictCursor)
cur = conn.cursor()
reCount = cur.execute('select Name,Address from UserInfo')
nRet = cur.fetchall()
cur.close()
conn.close()
print reCount
print nRet
for i in nRet:
print i[0],i[1]