python--第十一天总结(paramiko 及数据库操作)

堡垒机前戏

开发堡垒机之前,先来学习Python的paramiko模块,该模块机遇SSH用于连接远程服务器并执行相关操作

实现思路

堡垒机执行流程

  1. 管理员为用户在服务器上创建账号(将公钥放置服务器,或者使用用户名密码)

  2. 用户登陆堡垒机,输入堡垒机用户名密码,现实当前用户管理的服务器列表

  3. 用户选择服务器,并自动登陆

  4. 执行操作并同时将用户操作记录

注:配置.brashrc实现ssh登陆后自动执行脚本,如:/usr/bin/python /root/menu.py

    但为了防止用户ctrl+c退出脚本依然留在系统,可以在下面加入一行exit。

    脚本中捕获except EOFError和 Kerboard Interrupt:不要continue,直接写退出sys.exit(0)。

实现过程简介

以下代码其实是paramiko源码包里demo.py的精简

步骤一,实现用户登陆

import getpass
  
user = raw_input('username:')
pwd = getpass.getpass('password')
if user == 'root' and pwd == '123':
    print '登陆成功'
else:
    print '登陆失败'
步骤二,根据用户获取相关服务器列表

    
dic = {
    'alex': [
        '172.16.103.189',
        'c10.puppet.com',
        'c11.puppet.com',
    ],
    'eric': [
        'c100.puppet.com',
    ]
}
  
host_list = dic['alex']
  
print 'please select:'
for index, item in enumerate(host_list, 1):
    print index, item
  
inp = raw_input('your select (No):')
inp = int(inp)
hostname = host_list[inp-1]
port = 22
步骤三,根据用户名、私钥登陆服务器

    
import paramiko
import os
 
tran=paramiko.Transport(('192.168.136.8',22))
tran.start_client()
#用户名密码方式
tran.auth_password('root','123456')
#私钥认证方式
# default_path = os.path.join(os.environ['HOME'], '.ssh', 'id_rsa')
# key = paramiko.RSAKey.from_private_key_file(default_path)
# tran.auth_publickey('root', key)
#打开一个通道
channel=tran.open_session()
#获取一个终端
channel.get_pty()
#激活器
channel.invoke_shell()
 
####终端操作,用下面的《终端操作》三种操作模式替换此段代码####
# 利用sys.stdin,肆意妄为执行操作
# 用户在终端输入内容,并将内容发送至远程服务器
# 远程服务器执行命令,并将结果返回
# 用户终端显示内容
###################################################
 
channel.close()
tran.close()
终端操作

以下代码其实是paramiko源码包里interactive.py的内容,前两种模式是在linux下执行,模式三适用于windows。
操作模式一:(linux)

用select监听channel句柄变化进行通讯,一行一行发送,即只有用户按了回车键,才发送。

关于通信结束,客户端返回一个空值(输入‘exit’就是空值),就是关闭连接的信号。

终端操作

以下代码其实是paramiko源码包里interactive.py的内容,适用于交互执行,前两种模式是在linux下执行,模式三适用于windows。

操作模式一:(linux)    
import select
import sys
import socket
while True:
    #监视用户输入和服务器返回的数据
    #sys.stdin处理用户输入
    #channel是之前创建的通道,用于接收服务器返回信息和发送信息,相当于socket句柄
    readable,writeable,error=select.select([channel,sys.stdin,],[],[],1)
    #只要 channel,stdin,两个句柄其中之一变化就......
    if channel in readable:
        try:
            x=channel.recv(1024)
            if len(x)==0:
                print '
*** EOF
',
                break
            sys.stdout.write(x)
            sys.stdout.flush()
        except socket.timeout:
            pass
    if sys.stdin in readable:
        inp=sys.stdin.readline()
        channel.sendall(inp)
操作模式二:(linux)

原始终端模式tty,一个字符发送一次,能有tab补齐等的效果,断开连接之前再切换回标准终端模式,不然堡垒机的tty会有问题。


    
import select
import sys
import socket
import termios  #只在linux下支持
import tty
 
# 获取原tty属性
oldtty = termios.tcgetattr(sys.stdin)
try:
    # 为tty设置新属性
    # 默认当前tty设备属性:
    #   输入一行回车,执行
    #   CTRL+C 进程退出,遇到特殊字符,特殊处理。
 
    # 这是为原始模式,不认识所有特殊符号
    # 放置特殊字符应用在当前终端,如此设置,将所有的用户输入均发送到远程服务器
    tty.setraw(sys.stdin.fileno())  #设置为原始终端模式
    channel.settimeout(0.0)
 
    while True:
        # 监视 用户输入 和 远程服务器返回数据(socket)
        # 阻塞,直到句柄可读
        r, w, e = select.select([channel, sys.stdin], [], [], 1)
        if channel in r:
            try:
                x = channel.recv(1024)
                if len(x) == 0:
                    print '
*** EOF
',
                    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
            channel.send(x)
 
finally:
    # 重新设置终端属性
    termios.tcsetattr(sys.stdin, termios.TCSADRAIN, oldtty)
操作模式三:(windows)

def windows_shell(chan):
    import threading
 
    sys.stdout.write("Line-buffered terminal emulation. Press F6 or ^Z to send EOF.

")
 
    def writeall(sock):
        while True:
            data = sock.recv(256)
            if not data:
                sys.stdout.write('
*** EOF ***

')
                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
记录日志:

也记录了tab('	'),显示的不完整,解决思路:根据返回的结果进行处理,比较麻烦。

    
try:
    f=open('log','a')
    while True:
        if channel in r:
            try:
                if len(x)==0:
                    f.close()
        if sys.stdin in r:
            ......
            f.write(x)
finally:
    pass

数据库操作

Python 操作 Mysql 模块的安装

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

Python MySQL API

一、插入数据

 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

批量插入

import MySQLdb

conn = MySQLdb.connect(host='127.0.0.1',user='root',passwd='1234',db='mydb')

cur = conn.cursor()

li =[
     ('alex','usa'),
     ('sb','usa'),
]
reCount = cur.executemany('insert into UserInfo(Name,Address) values(%s,%s)',li)

conn.commit()
cur.close()
conn.close()

print reCount
View Code

注意:cur.lastrowid

二、删除数据

 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('delete from UserInfo')
 8  
 9 conn.commit()
10  
11 cur.close()
12 conn.close()
13  
14 print reCount

三、修改数据

import MySQLdb
 
conn = MySQLdb.connect(host='127.0.0.1',user='root',passwd='1234',db='mydb')
 
cur = conn.cursor()
 
reCount = cur.execute('update UserInfo set Name = %s',('alin',))
 
conn.commit()
cur.close()
conn.close()
 
print reCount

四、查数据

 1 import MySQLdb
 2  
 3 conn = MySQLdb.connect(host='127.0.0.1',user='root',passwd='1234',db='mydb')
 4 cur = conn.cursor()
 5  
 6 reCount = cur.execute('select * from UserInfo')
 7  
 8 print cur.fetchone()
 9 print cur.fetchone()
10 cur.scroll(-1,mode='relative')
11 print cur.fetchone()
12 print cur.fetchone()
13 cur.scroll(0,mode='absolute')
14 print cur.fetchone()
15 print cur.fetchone()
16  
17 cur.close()
18 conn.close()
19  
20 print reCount
21  
22  
23  
24 # ############################## fetchall  ##############################
25  
26 import MySQLdb
27  
28 conn = MySQLdb.connect(host='127.0.0.1',user='root',passwd='1234',db='mydb')
29 #此方法返回字典
30 #cur = conn.cursor(cursorclass = MySQLdb.cursors.DictCursor)
31 #默认返回元组
32 cur = conn.cursor()
33  
34 reCount = cur.execute('select Name,Address from UserInfo')
35  
36 nRet = cur.fetchall()
37  
38 cur.close()
39 conn.close()
40  
41 print reCount
42 print nRet
43 for i in nRet:
44     print i[0],i[1]
原文地址:https://www.cnblogs.com/wjx1/p/5134644.html