一、paramiko

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

import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname='192.168.72.132',port=,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',))
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',))
transport.connect(username='root',password='start33333')
sftp = paramiko.SFTPClient.from_transport(transport)
sftp.put('','/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 =
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',))
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,],[],[],)
if chan in readable:
try:
x = chan.recv()
if len(x) == :
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)
chan.close()
tran.close()

实现持续性连接

#上述代码存在的问题,按tab键不能补全,只有回车键发挥发送数据;
#解决方式:、改变默认终端;由行--->stdin变为按字符--->stdin;、点击一次,向终端发送一次;即远程登录之后,改为原始模式,退出到本地之后,改为标准模式; import paramiko
tran = paramiko.Transport(('192.168.72.220',))
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], [], [], )
if chan in r:
try:
x = chan.recv()
if len(x) == :
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()
if len(x) == :
break
chan.send(x) finally:
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, oldtty)
chan.close()
tran.close()

修改默认终端

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

#!/usr/bin/env python
# _*_ coding:utf- _*_
import paramiko
tran = paramiko.Transport(('192.168.72.132',))
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], [], [], )
if chan in r:
try:
x = chan.recv()
if len(x) == :
print '\r\n*** EOF\r\n',
f.close() #返回为空,没有返回时关闭文件
break
sys.stdout.write(x)
sys.stdout.flush()
except socket.timeout:
pass
if sys.stdin in r:
x = sys.stdin.read()
if len(x) == :
break
if x == '\t':
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- _*_
import os,sys
msg = """\033[42;1mWelcome to using Charles's auditing system!\033[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()
except EOFError:
sys.exit()
if len(host) == :continue
if not host_dic.has_key(host):
print 'No host matched,try again!'
continue
print '\033[32;1mGoing to connect\033[0m',host_dic[host]
os.system("python demo.py %s" %host_dic[host])

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',)) 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',),
('xixi','female',)
] 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(,mode='absolute')
#cur.scroll(-,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(,mode='absolute')
print cur.fetchone()
print cur.fetchall()
conn.commit()
cur.close()
conn.close()
print reCount {'age': , 'sex': 'male', 'tel': '-', 'id': 1L, 'name': 'alex'}
{'age': , 'sex': 'male', 'tel': '-', 'id': 2L, 'name': 'alex'}
{'age': , 'sex': 'male', 'tel': '-', 'id': 2L, 'name': 'alex'}
({'age': , 'sex': 'male', 'tel': '-', 'id': 3L, 'name': 'Charles'}, {'age': , 'sex': 'male', 'tel': '-', 'id': 4L, 'name': 'wahaha'}, {'age': , 'sex': 'fema', 'tel': '-', 'id': 5L, 'name': 'xixi'})

修改游标,数据格式改变

paramiko与MySQL数据库的更多相关文章

  1. python之实现基于paramiko和mysql数据库的堡垒机

    一.堡垒机结构 堡垒机执行流程: 管理员为用户在服务器上创建账号(将公钥放置服务器,或者使用用户名密码) 用户登陆堡垒机,输入堡垒机用户名密码,现实当前用户管理的服务器列表 用户选择服务器,并自动登陆 ...

  2. Python Paramiko模块与MySQL数据库操作

    Paramiko模块批量管理:通过调用ssh协议进行远程机器的批量命令执行. 要使用paramiko模块那就必须先安装这个第三方模块,仅需要在本地上安装相应的软件(python以及PyCrypto), ...

  3. Python之操作Redis、 RabbitMQ、SQLAlchemy、paramiko、mysql

    一.Redis Redis是一个开源的使用ANSI C语言编写.支持网络.可基于内存亦可持久化的日志型.Key-Value数据库,并提供多种语言的API.Redis是一个key-value存储系统.和 ...

  4. MySQL数据库再回首

    前言: 数据库是程序员的数据源泉,加上近期 要开发DB可视化.性能分析的功能 重新回顾一下MySQL知识,以下是笔记: MySQL架构 MySQL基础理论 1.什么是关系型数据库? 关系型数据库,这个 ...

  5. nodejs进阶(6)—连接MySQL数据库

    1. 建库连库 连接MySQL数据库需要安装支持 npm install mysql 我们需要提前安装按mysql sever端 建一个数据库mydb1 mysql> CREATE DATABA ...

  6. 当忘记mysql数据库密码时如何进行修改

    因为长时间没有使用数据库了,或者把密码改完之后就忘了数据库密码,不能正常进入数据库,也无法修改密码,有一个简单的常用修改密码方式: 1.首先找到和打开mysql.exe和mysqld.exe所在的文件 ...

  7. MySQL数据库和InnoDB存储引擎文件

    参数文件 当MySQL示例启动时,数据库会先去读一个配置参数文件,用来寻找数据库的各种文件所在位置以及指定某些初始化参数,这些参数通常定义了某种内存结构有多大等.在默认情况下,MySQL实例会按照一定 ...

  8. 一起学微软Power BI系列-使用技巧(1)连接Oracle与Mysql数据库

    说起Oracle数据库,以前没用过Oracle不知道,但是这1年用Oracle后,发现真的是想狂吐槽,特别是那个.NET驱动和链接字符串,特别奇葩.总归是和其他数据库不一样,标新立异,不知道为何.另外 ...

  9. CentOS下mysql数据库常用命令总结

    mysql数据库使用总结 本文主要记录一些mysql日常使用的命令,供以后查询. 1.更改root密码 mysqladmin -uroot password 'yourpassword' 2.远程登陆 ...

随机推荐

  1. Gridview 分多页时导出excel的解决方案

    在开发会遇到将gridview中的数据导入到excel 这样的需求,当girdview有多页数据时按照一般的方式导出的数据只可能是当前页的数据,后几页的数据还在数据库内,没有呈现到页面上,传统的方式是 ...

  2. WeX5 - AJAX跨域调用相关知识-CORS和JSONP

    http://docs.wex5.com/ajax-cross-domain/ 1.什么是跨域 跨域问题产生的原因,是由于浏览器的安全机制,JS只能访问与所在页面同一个域(相同协议.域名.端口)的内容 ...

  3. office2016与visio2016不能“并存”的问题分析

    现象: 先安装了office2016专业增强版,再安装visio2016时出现提示 搜集了相关资料,可以通俗的理解为:已经安装了离线客户端版的office后,不能再安装在线版visio. 之后,将of ...

  4. SQLServer的学习场景(关于row_number()和COALESCE()的使用)

    --使用Sql语句,统计出每辆汽车每天行驶的里程数(不是总里程) 以下为脚本 CREATE TABLE [dbo].[CarData]([CarID] [int] NULL,[Mileage] [in ...

  5. windows下安装php5.5的redis扩展

    windows下开发用的xampp集成的环境,想装个php-redis扩展,扩展的github地址:  https://github.com/nicolasff/phpredis php_redis. ...

  6. unix&linux大学教程 目录

    第1章unix简介 第2章什么是linux?什么是unix 第3章unix连接 第4章开始使用unix 第5章gui:图形用户界面 第6章unix工作环境 第7章unix键盘使用 第8章能够立即使用的 ...

  7. VS2013,VS2015设置类模板文件表头

    一般VS的类模板文件是放在C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\ItemTemplatesCache\CSha ...

  8. Android 通过广播获取网络状态

    Android系统网络连接状态的改变会发一个广播,注册一个广播接收者,实时动态的检测网络状态,及时提醒用户,优化用户体验.          本文仅提供WIFI 状态的检测作为参考,其他网络连接方式请 ...

  9. DELL PowerEdge 2950更换告警硬盘

    硬盘为SAS300G15K,四块,3#告警,打算还掉,在R900上找到一块对应的硬盘直接换下. 进入控制台后发现硬盘阵列里还是只有三块硬盘,物理磁盘倒是有四块,新插上的一块状态为“外部”,其他状态是“ ...

  10. ZOJ 3481. Expand Tab

    题目:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=4278 题意: 给出一些文本片段,把文本中的 Tab 字符根据配置,替换成 ...