paramiko与MySQL数据库

一、paramiko

1、利用paramiko连接远端服务器

import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname='192.168.72.132',port=22,username='root',password='start33333')
stdin,stdout,stderr = ssh.exec_command('ls -l')    #句柄
print stdout.read()
ssh.close()
基于用户名和密码进行连接
import paramiko
transport = paramiko.Transport(('192.168.72.132',22))
transport.connect(username='root',password='start33333')
ssh = paramiko.SSHClient()
ssh._transport=transport
stdin,stdout,stderr = ssh.exec_command('ls -l')
print stdout.read()
transport.close()
利用connect类中的transport方法进行连接

2、sftp

import paramiko
transport = paramiko.Transport(('192.168.72.132',22))
transport.connect(username='root',password='start33333')
sftp = paramiko.SFTPClient.from_transport(transport)
sftp.put('123','/tmp/111')
sftp.get('remote_path','locate_path')
transport.close()
sftp上传或下载

3、paramiko实现修改远程机器配置文件

步骤:a、本地生成文件uuid.ha;b、uuid上传到服务器; c、备份 ha.cnf--->ha.cnf.bak;   d、uuid.ha--->ha.cnf;    f、reload

上述步骤应该一部完成,使用sftpclient和sshclient命令操作;

import paramiko
import uuid
class Haproxy(object):
    def __init__(self):
        self.host = '192.168.72.220'
        self.port =22
        self.username = 'root'
        self.pwd = 'start33333'
    def create_file(self):
        file_name = str(uuid.uuid4())
        with open(file_name,'w') as f:
            f.write('Charles')
        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)
        sftp.put(file_name,'/home/Charles/123.py')

    def rename(self):
        ssh = paramiko.SSHClient()
        ssh._transport=self.__transport
        stdin,stdout,stderr = ssh.exec_command('mv /home/Charles/123.py /home/Charles/456.py')
        result = stdout.read()
        ssh.close()

ha = Haproxy()
ha.run()
文件上传于修改

 4、paramiko实现持续性连接

import paramiko
tran = paramiko.Transport(('192.168.72.220',22))
tran.start_client()
tran.auth_password('Charles','start33333')    #给予密码的认证
chan = tran.open_session()    #打开一个通道
chan.get_pty()
chan.invoke_shell()   #激活器

import sys,select,socket
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 '
***EOF
',
                break
            sys.stdout.write(x)
            sys.stdout.flush()
        except socket.timeout:
            pass
        if sys.stdin in readable:
            inp = sys.stdin.readline()
            chan.sendall(inp)
    chan.close()
    tran.close()
实现持续性连接
#上述代码存在的问题,按tab键不能补全,只有回车键发挥发送数据;
#解决方式:1、改变默认终端;由行--->stdin变为按字符--->stdin;2、点击一次,向终端发送一次;即远程登录之后,改为原始模式,退出到本地之后,改为标准模式;

import paramiko
tran = paramiko.Transport(('192.168.72.220',22))
tran.start_client()
tran.auth_password('Charles','start33333')
chan = tran.open_session()
chan.get_pty()
chan.invoke_shell()
import select
import sys
import socket
import termios
import tty
oldtty = termios.tcgetattr(sys.stdin)
try:
    # 为tty设置新属性
    # 默认当前tty设备属性:
    #   输入一行回车,执行
    #   CTRL+C 进程退出,遇到特殊字符,特殊处理。

    # 这是为原始模式,不认识所有特殊符号
    # 放置特殊字符应用在当前终端,如此设置,将所有的用户输入均发送到远程服务器
    tty.setraw(sys.stdin.fileno())
    chan.settimeout(0.0)

    while True:
        r, w, e = select.select([chan, sys.stdin], [], [], 1)
        if chan in r:
            try:
                x = chan.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
            chan.send(x)

finally:
    termios.tcsetattr(sys.stdin, termios.TCSADRAIN, oldtty)
chan.close()
tran.close()
修改默认终端

 5、paramiko实现连续性连接服务器之记录操作日志

#!/usr/bin/env python
# _*_ coding:utf-8 _*_
import paramiko
tran = paramiko.Transport(('192.168.72.132',22))
tran.start_client()
tran.auth_password('root','start33333')
chan = tran.open_session()
chan.get_pty()
chan.invoke_shell()
import select
import sys
import socket
import termios
import tty
oldtty = termios.tcgetattr(sys.stdin)
try:
    tty.setraw(sys.stdin.fileno())
    chan.settimeout(0.0)
    f = open('record','a')   #记录操作日志的文件
    while True:
        r, w, e = select.select([chan, sys.stdin], [], [], 1)
        if chan in r:
            try:
                x = chan.recv(1024)
                if len(x) == 0:
                    print '
*** EOF
',
                    f.close()    #返回为空,没有返回时关闭文件
                    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
            if x == '	':
                pass
            else:
                f.write(x)
            chan.send(x)

finally:
    termios.tcsetattr(sys.stdin, termios.TCSADRAIN, oldtty)
chan.close()
tran.close()
paramiko实现持续性连接之记录操作日志

以上操作都是在linux机器上完成的,也可以在windows平台上完成,具体在那种平台上执行,可以参考paramiko源码包中的demo文件夹下的demo.py和interactive.py文件设置;

6、paramiko实现堡垒机的功能(利用demo.py和interactive.py实现)

#将上述两个文件拷贝到本地
#!/usr/bin/env python
# _*_ coding:utf-8 _*_
import os,sys
msg = """33[42;1mWelcome to using Charles's auditing system!33[0m"""
print msg
host_dic = {
    'Charles':'192.168.72.132',
}
while True:
    for hostname,ip in host_dic.items():
        print hostname,ip
    try:
        host = raw_input('please choose one server to login:').strip()
        if host == 'quit':
            print 'Goodbye!'
            break
    except KeyboardInterrupt:
        sys.exit(0)
    except EOFError:
        sys.exit(0)
    if len(host) == 0:continue
    if not host_dic.has_key(host):
        print 'No host matched,try again!'
        continue
    print '33[32;1mGoing to connect33[0m',host_dic[host]
    os.system("python demo.py %s" %host_dic[host])
View Code

7、MySQL数据库操作

import MySQLdb
conn = MySQLdb.connect(host='192.168.72.240',user='root',passwd='start33333',db='S11day11')
cur = conn.cursor()

reCount = cur.execute('insert into students(name,sex,age) values(%s,%s,%s)',('Charles','male',23))

conn.commit()
cur.close()
conn.close()
print reCount
插入数据
import MySQLdb
conn = MySQLdb.connect(host='192.168.72.240',user='root',passwd='start33333',db='S11day11')
cur = conn.cursor()
li = [
    ('wahaha','male',18),
    ('xixi','female',20)
]

reCount = cur.executemany('insert into students(name,sex,age) values(%s,%s,%s)',li)

conn.commit()
cur.close()
conn.close()
print reCount
插入多行数据
import MySQLdb
conn = MySQLdb.connect(host='192.168.72.240',user='root',passwd='start33333',db='S11day11')
cur = conn.cursor()
reCount = cur.execute('select * from S11day11.students')
print cur.fetchone()    #一个fetchone拿一条数据,指针往下执行一条
print cur.fetchone()
cur.scroll(1,mode='absolute')    
#cur.scroll(-1,mode='relative')    #指针向上偏移
print cur.fetchone()
print cur.fetchall()     #拿到指针位置以下的全部数据,获取数据的格式全部为元组
conn.commit()
cur.close()
conn.close()
print reCount
数据查询
import MySQLdb
conn = MySQLdb.connect(host='192.168.72.240',user='root',passwd='start33333',db='S11day11')
#cur = conn.cursor()
cur = conn.cursor(cursorclass = MySQLdb.cursors.DictCursor)
reCount = cur.execute('select * from S11day11.students')
print cur.fetchone()
print cur.fetchone()
cur.scroll(1,mode='absolute')
print cur.fetchone()
print cur.fetchall()
conn.commit()
cur.close()
conn.close()
print reCount


{'age': 0, 'sex': 'male', 'tel': '-', 'id': 1L, 'name': 'alex'}
{'age': 30, 'sex': 'male', 'tel': '-', 'id': 2L, 'name': 'alex'}
{'age': 30, 'sex': 'male', 'tel': '-', 'id': 2L, 'name': 'alex'}
({'age': 23, 'sex': 'male', 'tel': '-', 'id': 3L, 'name': 'Charles'}, {'age': 18, 'sex': 'male', 'tel': '-', 'id': 4L, 'name': 'wahaha'}, {'age': 20, 'sex': 'fema', 'tel': '-', 'id': 5L, 'name': 'xixi'})
5
修改游标,数据格式改变
原文地址:https://www.cnblogs.com/cqq-20151202/p/5280382.html