Python之路:堡壘機實例以及數據庫操作


一、堡壘機前戲

開發堡壘機之前,先學習Python的paramiko模塊,該模塊基於SSH用於連接遠程服務器並執行相關操作。

SSHClient

用於連接遠程服務器並執行基本命令

基於用戶名密碼連接:

#!/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()
SSHClient 封裝 Transport

 基於公鑰密鑰連接:

# !/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 ', key=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()
SSHClient 封裝 Transport

SFTPClient

用於連接遠程服務器並執行上傳下載

基於用戶名密碼上傳下載

# !/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()
# !/usr/bin/env  python
#
 --*--coding:utf-8 --*--
import paramiko
import uuid
class Haproxy(object):
     def  __init__(self):
        self.host =  ' 192.168.1.30 '
        self.port = 22
        self.username =  ' wulaoer '
        self.pwd =  ' 123456 '
        self. __k = None

     def create_file(self):
        file_name = str(uuid.uuid4())
        with open(file_name, ' w ') as f:
            f.write( ' dn ')
         return file_name

     def run(self):
        self.connect()
        self.upload()
        self.rename()
        self.close()

     def connect(self):
        transport = paramiko.Transport((self.host,self.port))
        transport.connect(username=self.username,password=self.pwd)
        self. __transport = transport

     def close(self):

        self. __transport.close()

     def upload(self):
         #  連接,上傳
        file_name = self.create_file()

        sftp = paramiko.SFTPClient.from_transport(self. __transport)
         #  將location.py 上傳至服務器 /tmp/test.py
        sftp.put(file_name,  ' /home/wulaoer/wwwwwwwwww.py ')

     def rename(self):

        ssh = paramiko.SSHClient()
        ssh._transport = self. __transport
         #  執行命令
        stdin, stdout, stderr = ssh.exec_command( ' mv /home/wulaoer/wwwwwwwwww.py /home/wulaoer/lllllllllll.py ')
         #  獲取命令結果
        result = stdout.read()


ha = Haproxy()
ha.run()
Demo
二、堡壘機的實現

實現思路:

堡壘機執行流程:

1、管理員為用戶在服務器上創建帳號(將公鑰放置服務器,或者使用用戶名密碼)

2、用戶登錄堡壘機,輸入堡壘機用戶名密碼,現實當前用戶管理的服務器列表

3、用戶選擇服務器,並自動登錄

4、執行操作並同時將用戶操作記錄 

 注:配置.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基本使用

1、數據庫操作

show databases;   # 查看數據庫
use [databasename];   # 切換數據或者進入數據庫
create database  [name];  # 新建數據庫

 2、數據表操作

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`) 
) ; 
View Code

 3、數據庫操作

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
# 查看整個表

 4、其他

主鍵
外鍵
左右連接

更多mysql操作萌點這里

 Python MySQL API

一、插入數據

# !/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

二、刪除數據

# !/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

 三、修改數據

# !/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

 四、查看數據

# !/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]

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM