堡垒机实例

堡垒机实例

paramiko---SSHClient

基于SSH用于连接远程服务器并执行相关操作,

 1 import paramiko
 2   
 3 # 创建SSH对象
 4 ssh = paramiko.SSHClient()
 5 # 允许连接不在know_hosts文件中的主机
 6 ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
 7 # 连接服务器
 8 ssh.connect(hostname='c1.salt.com', port=22, username='wupeiqi', password='123')
 9   
10 # 执行命令
11 stdin, stdout, stderr = ssh.exec_command('df')
12 # 获取命令结果
13 result = stdout.read()
14   
15 # 关闭连接
16 ssh.close()
基于用户名密码的连接

SSHClient本质上封装transport

import paramiko

transport = paramiko.Transport(('hostname', 22))
transport.connect(username='wupeiqi', password='123')

ssh = paramiko.SSHClient()
ssh._transport = transport

stdin, stdout, stderr = ssh.exec_command('df')
print stdout.read()

transport.close()

 1 import paramiko
 2  
 3 private_key = paramiko.RSAKey.from_private_key_file('/home/auto/.ssh/id_rsa')
 4  
 5 # 创建SSH对象
 6 ssh = paramiko.SSHClient()
 7 # 允许连接不在know_hosts文件中的主机
 8 ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
 9 # 连接服务器
10 ssh.connect(hostname='c1.salt.com', port=22, username='wupeiqi', key=private_key)
11  
12 # 执行命令
13 stdin, stdout, stderr = ssh.exec_command('df')
14 # 获取命令结果
15 result = stdout.read()
16  
17 # 关闭连接
18 ssh.close()
基于公私钥的连接

SSHClient本质上封装transport

import paramiko

private_key = paramiko.RSAKey.from_private_key_file('/home/auto/.ssh/id_rsa')

transport = paramiko.Transport(('hostname', 22))
transport.connect(username='wupeiqi', pkey=private_key)

ssh = paramiko.SSHClient()
ssh._transport = transport

stdin, stdout, stderr = ssh.exec_command('df')

transport.close()

paramiko---SFTPClient

 

基于用户名密码的上传下载

import paramiko
 
transport = paramiko.Transport(('hostname',22))
transport.connect(username='wupeiqi',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()

 

 

基于公私钥的上传下载

 

 

import paramiko
 
private_key = paramiko.RSAKey.from_private_key_file('/home/auto/.ssh/id_rsa')
transport = paramiko.Transport(('hostname', 22))
transport.connect(username='wupeiqi', 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()

 

 

 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 import paramiko
 4 import uuid
 5 
 6 class Haproxy(object):
 7 
 8     def __init__(self):
 9         self.host = 'localhost'
10         self.port = 22
11         self.username = 'root'
12         self.pwd = '123'
13         self.__k = None
14 
15     def create_file(self):
16         file_name = str(uuid.uuid4())
17         with open(file_name,'w') as f:
18             f.write('sb')
19         return file_name
20 
21     def run(self):
22         self.connect()
23         self.upload()
24         self.rename()
25         self.close()
26 
27     def connect(self):
28         transport = paramiko.Transport((self.host,self.port))
29         transport.connect(username=self.username,password=self.pwd)
30         self.__transport = transport
31 
32     def close(self):
33 
34         self.__transport.close()
35 
36     def upload(self):
37         # 连接,上传
38         file_name = self.create_file()
39 
40         sftp = paramiko.SFTPClient.from_transport(self.__transport)
41         # 将location.py 上传至服务器 /tmp/test.py
42         sftp.put(file_name, '/home/wupeiqi/tttttttttttt.py')
43 
44     def rename(self):
45 
46         ssh = paramiko.SSHClient()
47         ssh._transport = self.__transport
48         # 执行命令
49         stdin, stdout, stderr = ssh.exec_command('mv /home/wupeiqi/tttttttttttt.py /home/wupeiqi/ooooooooo.py')
50         # 获取命令结果
51         result = stdout.read()
52 
53 
54 ha = Haproxy()
55 ha.run()
paramiko实现Haproxy配置文件的替换实例

 

堡垒机的实现

 

堡垒机执行流程:

 

    1. 管理员为用户在服务器上创建账号(将公钥放置服务器,或者使用用户名密码)
    2. 用户登陆堡垒机,输入堡垒机用户名密码,现实当前用户管理的服务器列表
    3. 用户选择服务器,并自动登陆
    4. 执行操作并同时将用户操作记录

 

 

 

  1 #!/usr/bin/env python
  2 # -*- coding:utf8 -*-
  3 # written by liYang
  4 import paramiko
  5 import sys
  6 import tty
  7 import termios
  8 import select
  9 import socket
 10 import MySQLdb
 11 
 12 
 13 class MyJump(object):
 14 
 15     def __init__(self, port=22):
 16         self.port = port
 17 
 18     def __get_login_from_mysql(self):
 19         """
 20         mysql> select user_name,group_name,host_name
 21                     from users,user_group,user_host
 22                     where users.group_id = user_group.group_id
 23                         and users.host_id = user_host.host_id;
 24         +-----------+------------+----------------+
 25         | user_name | group_name | host_name      |
 26         +-----------+------------+----------------+
 27         | alex      | staff      | 192.168.122.24 |
 28         | eric      | staff      | 192.168.122.23 |
 29         | liyang    | admin      | 192.168.122.20 |
 30         | seven     | staff      | 192.168.122.22 |
 31         | xiyu      | ops        | 192.168.122.21 |
 32         +-----------+------------+----------------+
 33         """
 34         conn = MySQLdb.connect(host="127.0.0.1",
 35                                user="root",
 36                                passwd="123456",
 37                                db="hostmanager")
 38 
 39         cur = conn.cursor()
 40 
 41         reCount = cur.execute("select user_name,host_name,group_name \
 42                            from users,user_group,user_host \
 43                            where users.group_id = user_group.group_id \
 44                                 and users.host_id = user_host.host_id;")
 45         res = cur.fetchall()
 46         self.__result = res
 47         cur.close()
 48         conn.close()
 49         # print reCount
 50         # print res
 51         # print "host list: "
 52         # for i in res:
 53         #    print "\t%s\t%s\t%s" % (i[0], i[1], i[2])
 54 
 55     def operation(self):
 56         print "host list: "
 57         for i in self.__result:
 58             print "\t%s\t%s\t%s" % (i[0], i[1], i[2])
 59         
 60         hostname = str(raw_input("your host: "))
 61         user = str(raw_input("your name: "))
 62         password = str(raw_input("your password: "))
 63 
 64         # login to remote server
 65         sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
 66         sock.connect((hostname, self.port))
 67         tran = paramiko.Transport(sock)
 68         tran.start_client()
 69         tran.auth_password(user, password)
 70 
 71         chan = tran.open_session()
 72         # 获取一个终端
 73         chan.get_pty()
 74         # 激活终端
 75         chan.invoke_shell()
 76         oldtty = termios.tcgetattr(sys.stdin)
 77         try:
 78             tty.setraw(sys.stdin.fileno())
 79             chan.settimeout(0.0)
 80             f = open("record", "a")
 81             while True:
 82                 r, w, e = select.select([chan, sys.stdin], [], [], 1)
 83                 if chan in r:
 84                     try:
 85                         x = chan.recv(1024)
 86                         if len(x) == 0:
 87                             print '\r\n*** EOF\r\n',
 88                             f.close()
 89                             break
 90                         sys.stdout.write(x)
 91                         sys.stdout.flush()
 92                     except socket.timeout:
 93                         pass
 94                 if sys.stdin in r:
 95                     x = sys.stdin.read(1)
 96                     if len(x) == 0:
 97                         break
 98                     f.write(x)
 99                     chan.send(x)
100 
101         finally:
102             # 重新设置终端属性
103             termios.tcsetattr(sys.stdin, termios.TCSADRAIN, oldtty)
104 
105         chan.close()
106         tran.close()
107 
108     def run(self):
109         self.__get_login_from_mysql()
110         self.operation()
111 
112 mj = MyJump()
113 mj.run()
简易堡垒机实现

 

 

 

数据库操作

Python 操作 Mysql 模块的安装

linux:
    yum install MySQL-python
window:
    https://files.cnblogs.com/files/wupeiqi/py-mysql-win.zip

 

Python MySQL API

插入数据、删除数据、修改数据,多是在cursor处执行SQL语句。

 1 import MySQLdb
 2   
 3 conn = MySQLdb.connect(host='127.0.0.1',user='root',passwd='1234',db='mydb')
 4   
 5 cur = conn.cursor()
 6   
 7 reCount = cur.execute('insert into UserInfo(Name,Address) values(%s,%s)',('alex','usa'))
 8 # reCount = cur.execute('insert into UserInfo(Name,Address) values(%(id)s, %(name)s)',{'id':12345,'name':'wupeiqi'})
 9   
10 conn.commit()
11   
12 cur.close()
13 conn.close()
14   
15 print reCount
单次插入数据
 1 import MySQLdb
 2 
 3 conn = MySQLdb.connect(host='127.0.0.1',user='root',passwd='1234',db='mydb')
 4 
 5 cur = conn.cursor()
 6 
 7 li =[
 8      ('alex','usa'),
 9      ('sb','usa'),
10 ]
11 reCount = cur.executemany('insert into UserInfo(Name,Address) values(%s,%s)',li)
12 
13 conn.commit()
14 cur.close()
15 conn.close()
16 
17 print reCount
批量插入数据
 1 #!/usr/bin/python  
 2 # import MySQL module  
 3 import MySQLdb  
 4 # get user input  
 5 name = raw_input("Please enter a name: ")  
 6 # connect  
 7 conn = MySQLdb.connect(host="localhost", user="nobody", passwd="nobody", conn="qestar", unix_socket="/tmp/mysql.sock")  
 8 # create a cursor  
 9 cursor = conn.cursor()  
10 # execute SQL statement  
11 cursor.execute("INSERT INTO test (nama) VALUES (%s)", name)  
12 # get ID of last inserted record  
13 print "ID of last record is ", int(cursor.lastrowid) #最后插入行的主键ID  
14 print "ID of inserted record is ", int(conn.insert_id()) #最新插入行的主键ID,conn.insert_id()一定要在conn.commit()之前,否则会返回0  
15 conn.commit()
cur.lastrowid,主键ID

查询数据

 1 # ############################## fetchone/fetchmany(num)  ##############################
 2  
 3 import MySQLdb
 4  
 5 conn = MySQLdb.connect(host='127.0.0.1',user='root',passwd='1234',db='mydb')
 6 cur = conn.cursor()
 7  
 8 reCount = cur.execute('select * from UserInfo')
 9  
10 print cur.fetchone()
11 print cur.fetchone()
12 cur.scroll(-1,mode='relative')
13 print cur.fetchone()
14 print cur.fetchone()
15 cur.scroll(0,mode='absolute')
16 print cur.fetchone()
17 print cur.fetchone()
18  
19 cur.close()
20 conn.close()
21  
22 print reCount
查询数据---fetchone/fetchmany
 1 # ############################## fetchall  ##############################
 2  
 3 import MySQLdb
 4  
 5 conn = MySQLdb.connect(host='127.0.0.1',user='root',passwd='1234',db='mydb')
 6 #cur = conn.cursor(cursorclass = MySQLdb.cursors.DictCursor)
 7 cur = conn.cursor()
 8  
 9 reCount = cur.execute('select Name,Address from UserInfo')
10  
11 nRet = cur.fetchall()
12  
13 cur.close()
14 conn.close()
15  
16 print reCount
17 print nRet
18 for i in nRet:
19     print i[0],i[1]
查询数据---fetchall

 

 

 

posted on 2016-02-29 20:51  曦字号  阅读(215)  评论(0)    收藏  举报

导航