Python Paramiko模块与MySQL数据库操作

Python Paramiko模块与MySQL数据库操作

2018年05月24日 15:38:52 天健胡马灵越鸟 阅读数:291更多

所属专栏: Python

Paramiko模块批量管理:
通过调用ssh协议进行远程机器的批量命令执行.

要使用paramiko模块那就必须先安装这个第三方模块,仅需要在本地上安装相应的软件(python以及PyCrypto),对远程服务器没有配置要求,对于连接多台服务器,进行复杂的连接操作特别有帮助。

一、安装:

1:安装gcc和python-devel 

  1. yum install gcc gcc-c++ python-devel     #安装所需环境

2:  paramiko依赖pycrypto模块,要先下载pycrypto安装 

  1. wget http://ftp.dlitz.net/pub/dlitz/crypto/pycrypto/pycrypto-2.6.tar.gz

解压后进入主目录执行下面命令: 

  1. python setup.py build
  2. python setup.py install

3:下载paramiko进行安装 

  1. wget http://www.lag.net/paramiko/download/paramiko-1.7.7.1.tar.gz

解压后进入主目录执行下面命令

 
  1. python setup.py build
  2. python setup.py install

4: 修改配置

在python的命令行模式下面导入模块,进行测试:

 
  1. import paramiko

结果提示错误如下:

 
  1. Traceback (most recent call last):
  2. File "<stdin>", line 1, in <module>
  3. File "/usr/lib/python2.6/site-packages/paramiko-1.7.7.1-py2.6.egg/paramiko/__init__.py", line 69, in<module>
  4. from transport import SecurityOptions, Transport
  5. File "/usr/lib/python2.6/site-packages/paramiko-1.7.7.1-py2.6.egg/paramiko/transport.py", line 32, in<module>
  6. from paramiko import util
  7. File "/usr/lib/python2.6/site-packages/paramiko-1.7.7.1-py2.6.egg/paramiko/util.py", line 32, in<module>
  8. from paramiko.common import *
  9. File "/usr/lib/python2.6/site-packages/paramiko-1.7.7.1-py2.6.egg/paramiko/common.py", line 98, in<module>
  10. from Crypto import Random
  11. File "/usr/lib64/python2.6/site-packages/Crypto/Random/__init__.py", line 29, in <module>
  12. from Crypto.Random import _UserFriendlyRNG
  13. File "/usr/lib64/python2.6/site-packages/Crypto/Random/_UserFriendlyRNG.py", line 38, in <module>
  14. from Crypto.Random.Fortuna import FortunaAccumulator
  15. File "/usr/lib64/python2.6/site-packages/Crypto/Random/Fortuna/FortunaAccumulator.py", line 39, in<module>
  16. import FortunaGenerator
  17. File "/usr/lib64/python2.6/site-packages/Crypto/Random/Fortuna/FortunaGenerator.py", line 34, in<module>
  18. from Crypto.Util.number import ceil_shift, exact_log2, exact_div
  19. File "/usr/lib64/python2.6/site-packages/Crypto/Util/number.py", line 56, in <module>
  20. if _fastmath is not None and not _fastmath.HAVE_DECL_MPZ_POWM_SEC:
  21. AttributeError: 'module' object has no attribute 'HAVE_DECL_MPZ_POWM_SEC'

解决方法:

进入/usr/lib64/python2.6/site-packages/Crypto/Util/number.py ,注解下面两行

 
  1. #if _fastmath is not None and not _fastmath.HAVE_DECL_MPZ_POWM_SEC:
  2. # _warn("Not using mpz_powm_sec. You should rebuild using libgmp >= 5 to avoid timing attack vulnerability.", PowmInsecureWarning)

二、paramiko模块:

SSHClient

用于连接远程服务器并执行基本命令

基于用户名密码连接:

 
  1. #!/usr/bin/env python
  2. # encoding: utf-8
  3.  
  4. import paramiko
  5.  
  6. #记录日志
  7. paramiko.util.log_to_file('paramiko.log')
  8. #创建SSH对象
  9. ssh = paramiko.SSHClient()
  10. # 允许连接不在know_hosts文件中的主机
  11. ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  12. # 连接远程主机
  13. ssh.connect(hostname='10.10.100.100',port=22,username='root',password='******')
  14. #执行命令(输入,输出,错误返回结果)
  15. stdin,stdout,stderr=ssh.exec_command('free -m')
  16. #读取stdout命令结果
  17. result = stdout.read()
  18. #输出并打印出结果.
  19. print result
  20. # 关闭连接 
 
  1. SSHClient 封装 Transport:
 
  1. import paramiko
  2.  
  3. paramiko.util.log_to_file('paramilo.log')
  4. transport = paramiko.Transport(('10.10.100.110', 22))
  5. transport.connect(username='www', password='***')
  6.  
  7. ssh = paramiko.SSHClient()
  8. ssh._transport = transport
  9.  
  10. stdin, stdout, stderr = ssh.exec_command('df -Th')
  11. print stdout.read()
  12.  
  13. transport.close()

SSHClient 封装 Transport

三、使用Key连接远程:

本机生成key :ssh-keygen

 
  1. #!/usr/bin/env python
  2. # encoding: utf-8
  3.  
  4. import paramiko
  5. private_key = paramiko.RSAKey.from_private_key_file('/home/www/.ssh/id_rsa')  #本机私钥文件
  6.  
  7. # 创建SSH对象
  8. ssh = paramiko.SSHClient()
  9. # 允许连接不在know_hosts文件中的主机
  10. ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  11. # 连接服务器
  12. ssh.connect(hostname='ip', port=22, username='www', pkey=private_key)
  13. # 执行命令
  14. stdin, stdout, stderr = ssh.exec_command('df')
  15. # 获取命令结果
  16. result = stdout.read()
  17. # 关闭连接
  18. ssh.close()
 
  1. import paramiko
  2.  
  3. private_key = paramiko.RSAKey.from_private_key_file('/home/www/.ssh/id_rsa')
  4. transport = paramiko.Transport(('hostname', 22))
  5. transport.connect(username='www', pkey=private_key)
  6. ssh = paramiko.SSHClient()
  7. ssh._transport = transport
  8. stdin, stdout, stderr = ssh.exec_command('df')
  9. transport.close()

SSHClient 封装 Transport

SFTPClient

用于连接远程服务器并执行上传下载

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

 
  1. import paramiko
  2.  
  3. transport = paramiko.Transport(('hostname',22))
  4. transport.connect(username='www',password='****')
  5. sftp = paramiko.SFTPClient.from_transport(transport)
  6. # 将location.py 上传至服务器 /tmp/test.py
  7. sftp.put('/tmp/parmiko1.py', '/tmp/test.py')
  8. # 将remove_path 下载到本地 local_path
  9. sftp.get('remove_path', 'local_path')
  10.  
  11. transport.close()

基于公钥密钥上传下载:

 
  1. import paramiko
  2.  
  3. private_key = paramiko.RSAKey.from_private_key_file('/home/www/.ssh/id_rsa')
  4. transport = paramiko.Transport(('hostname', 22))
  5. transport.connect(username='www', pkey=private_key )
  6. sftp = paramiko.SFTPClient.from_transport(transport)
  7. # 将location.py 上传至服务器 /tmp/test.py
  8. sftp.put('/tmp/paramiko1.py', '/tmp/test.py')
  9. # 将remove_path 下载到本地 local_path
  10. sftp.get('remove_path', 'local_path')
  11. transport.close

Python paramiko模块使用实例:

 
  1. #!/usr/bin/env python
  2. #coding:utf-8
  3. import paramiko
  4.  
  5. print """iplist.txt
  6.  
  7. 10.10.100.127 user1 user1@123
  8. 10.10.100.128 user1 user1@123
  9. 10.10.100.129 user1 user1@123
  10. 10.10.100.130 user1 user1@123
  11. """
  12.  
  13. def param_login():
  14. # paramiko.util.log_to_file('paramiko.log')
  15. # s = paramiko.SSHClient()
  16. # s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  17. # try:
  18. # s.connect(hostname=ip,port=22,username=username,password=passwd)
  19. # stdin, stdout, stderr = s.exec_command('free -m')
  20. # print u"ip地址是%s的执行结果为:" %(ip),"\n",stdout.read()
  21. # except:
  22. # return "None"
  23. # s.close()
  24.  
  25. #SSHClient 封装 Transport:
  26. paramiko.util.log_to_file('paramilo.log')
  27. try:
  28. transport = paramiko.Transport((ip, 22))
  29. transport.connect(username=username, password=passwd)
  30. ssh = paramiko.SSHClient()
  31. ssh._transport = transport
  32. stdin, stdout, stderr = ssh.exec_command('df -Th')
  33. print u"\033[32;1mip地址是%s的执行结果为:\033[0m" %(ip),"\n",stdout.read()
  34. except:
  35. return "None"
  36.  
  37. transport.close()
  38.  
  39. #用于连接远程服务器并执行上传下载
  40. def sshftp():
  41. transport = paramiko.Transport((ip,22))
  42. transport.connect(username=username,password=passwd)
  43. sftp = paramiko.SFTPClient.from_transport(transport)
  44. # 将本地/tmp/目录下文件上传至服务器/tmp目录下并改名
  45. sftp.put('/tmp/1.txt', '/tmp/2.txt')
  46. # 将remove_path 下载到本地 local_path
  47. #sftp.get('remove_path', 'local_path')
  48. sftp.get('/tmp/2.txt','/tmp/2.txt')
  49. transport.close()
  50.  
  51. if __name__ == "__main__":
  52. with open('iplist.txt','r') as userlist:
  53.  
  54. for i in userlist.readlines(): #循环读取文件
  55. m = i.strip() #去除空行
  56. #print m
  57. ip,username,passwd = m.split()
  58. param_login()
  59. sshftp()

登录机器并执行命令

 
  1. #!/usr/bin/env python
  2. #coding:utf-8
  3.  
  4. import sys
  5. import time
  6. import paramiko
  7.  
  8. class paramiko_ssh(object):
  9. def __init__(self,hostname,username,passwd):
  10. self.Hostname = hostname
  11. self.port = 22
  12. self.Username = username
  13. self.Passwd = passwd
  14. def ssh_login(self):
  15. #SSHClient 封装 Transport:
  16. paramiko.util.log_to_file('paramilo.log')
  17. try:
  18. transport = paramiko.Transport((self.Hostname, 22))
  19. transport.connect(username=self.Username, password=self.Passwd)
  20. ssh = paramiko.SSHClient()
  21. ssh._transport = transport
  22. stdin, stdout, stderr = ssh.exec_command('df -Th')
  23. print u"\033[32;1mip地址是%s的执行结果为:\033[0m" %(self.Hostname),"\n",stdout.read()
  24. except:
  25. return "None"
  26. time.sleep(3)
  27. sys.exit()
  28.  
  29. transport.close()
  30.  
  31. #用于连接远程服务器并执行上传下载
  32. def sshftp(self):
  33. transport = paramiko.Transport((self.Hostname,22))
  34. transport.connect(username=self.Username,password=self.Passwd)
  35. sftp = paramiko.SFTPClient.from_transport(transport)
  36. #将本地/tmp/目录下文件上传至服务器/tmp目录下并改名
  37. sftp.put('/tmp/1.txt', '/tmp/2.txt')
  38. # 将remove_path 下载到本地 local_path
  39. #sftp.get('remove_path', 'local_path')
  40. sftp.get('/tmp/2.txt','/tmp/2.txt')
  41. transport.close()
  42.  
  43. if __name__ == "__main__":
  44. with open('iplist.txt','r') as userlist:
  45.  
  46. for i in userlist.readlines(): #循环读取文件
  47. m = i.strip() #去除空行
  48. #print m
  49. hostname,username,passwd = m.split()
  50. p = paramiko_ssh(hostname,username,passwd)
  51. p.ssh_login()
  52. p.sshftp()

通过类执行登录操作

Python的paramiko模块块基于SSH用于连接远程服务器并执行相关操作. 堡垒机就是基于盖模块而开发的.

实现思路:

堡垒机执行流程:

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

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

未完代写.........................

Python 操作 Mysql 模块的安装:

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

SQL基本使用

1、数据库操作

 
  1. show databases;
  2. use [databasename];
  3. create database [name];

2、数据表操作

 
  1. show tables;
  2.  
  3. create table students
  4. (
  5. id int not null auto_increment primary key, #自动增长,主键
  6. name char(8) not null,
  7. sex char(4) not null,
  8. age tinyint unsigned not null,
  9. tel char(13) null default "-"
  10. );
 
  1. CREATE TABLE `wb_blog` (
  2. `id` smallint(8) unsigned NOT NULL,
  3. `catid` smallint(5) unsigned NOT NULL DEFAULT ',
  4. `title` varchar(80) NOT NULL DEFAULT '',
  5. `content` text NOT NULL,
  6. PRIMARY KEY (`id`),
  7. UNIQUE KEY `catename` (`catid`)
  8. ) ;

3、数据操作:

 
  1. insert into students(name,sex,age,tel) values(')
  2.  
  3. delete from students where id =2;
  4.  
  5. update students set name = 'toom' where id =1;
  6.  
  7. select * from students

4、其他

 
  1. 主键     主键是表里面唯一识别记录的字段,一般是id
  2. 外键     外键是该表与另一个表之间联接的字段 ,必须为另一个表中的主键 用途是确保数据的完整性
  3. 左右连接    分左连接,右连接,内连接

Python MySQL API

一、插入数据

 
  1. import MySQLdb
  2.  
  3. # 打开数据库连接
  4. conn = MySQLdb.connect(host=',db='mydb')
  5. # 使用cursor()方法获取操作游标
  6. cur = conn.cursor()
  7. # 使用execute方法执行SQL语句#reCount = cur.execute("create table UserInfo(id int,name varchar(20),nat varchar(30))") 创建表.
  8. reCount = cur.execute('insert into UserInfo(Name,Address) values(%s,%s)',('toom','usa'))
  9. #提交sql语句
  10. conn.commit()
  11. # 关闭数据库连接
  12. cur.close()conn.close()
  13. print reCount
  14.  
  15. #execute(self, query, args)
 
  1. #执行单条sql语句,接收的参数为sql语句本身和使用的参数列表,返回值为受影响的行数
 
  1. executemany(self, query, args)
 
  1. #执行单挑sql语句,但是重复执行参数列表里的参数,返回值为受影响的行数,可以一次插入多条值
 
  1. import MySQLdb
  2.  
  3. conn = MySQLdb.connect(host=',db='mydb')
  4. cur = conn.cursor()
  5. li =[
  6. ('www','usa'),
  7. ('toom','jpan'),
  8. ]
  9. reCount = cur.executemany('insert into UserInfo(Name,Address) values(%s,%s)',li)
  10. conn.commit()
  11. cur.close()
  12. conn.close()
  13. print reCount

批量插入数据

注意:cur.lastrowid

二、删除数据:

 
  1. import MySQLdb
  2.  
  3. conn = MySQLdb.connect(host=',db='mydb')
  4. cur = conn.cursor()
  5. reCount = cur.execute('delete from UserInfo where id=1')
  6. conn.commit() #提交数据
  7. cur.close()   #关闭游标
  8. conn.close()  #关闭数据库连接
  9.  
  10. print reCount

三、修改数据

 
  1. import MySQLdb
  2.  
  3. conn = MySQLdb.connect(host=',db='mydb')
  4.  
  5. cur = conn.cursor()
  6.  
  7. reCount = cur.execute('update UserInfo set Name = %s',('alin',))#reCount = cur.execute('update UserInfo set sex="man" where Name="alin"') 将Name名是alin的用户的sex改成“man”,set部分将改变.
  8.  
  9. conn.commit()
  10. cur.close()
  11. conn.close()
  12.  
  13. print reCount

四、查数据

 
  1. # ############################## fetchone/fetchmany(num) ##############################
  2.  
  3. import MySQLdb
  4.  
  5. conn = MySQLdb.connect(host=',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
  23.  
  24. # ############################## fetchall ##############################
  25.  
  26. import MySQLdb
  27.  
  28. conn = MySQLdb.connect(host=',db='mydb')
  29. #cur = conn.cursor(cursorclass = MySQLdb.cursors.DictCursor)
  30. cur = conn.cursor()
  31.  
  32. reCount = cur.execute('select Name,Address from UserInfo')
  33.  
  34. nRet = cur.fetchall()
  35.  
  36. cur.close()
  37. conn.close()
  38.  
  39. print reCount
  40. print nRet
  41. for i in nRet:
  42. print i[0],i[1]
  43.  
  44. # ############################## fetchmany ##############################
  45.  
  46. import MySQLdb
  47.  
  48. conn = MySQLdb.connect(host=',db='mydb')
  49. #cur = conn.cursor(cursorclass = MySQLdb.cursors.DictCursor)
  50. cur = conn.cursor()
  51.  
  52. reCount = cur.execute('select Name,Address from UserInfo')
  53. #读出表中的所有数据
  54. info = cur.fetchmany(reCount)
  55. for ii in info:
  56. print ii
  57. cur.close()
  58. conn.commit()
  59. conn.close()

cursor方法执行与返回值

cursor方法提供两类操作:1.执行命令,2.接收返回值 。
cursor用来执行命令的方法:

 
  1. #cursor用来执行命令的方法:callproc(self, procname, args) //用来执行存储过程,接收的参数为存储过程名和参数列表,返回值为受影响的行数
  2. execute(self, query, args) //执行单条sql语句,接收的参数为sql语句本身和使用的参数列表,返回值为受影响的行数
  3. executemany(self, query, args) //执行单挑sql语句,但是重复执行参数列表里的参数,返回值为受影响的行数
  4. nextset(self) //移动到下一个结果集
  5.  
  6. #cursor用来接收返回值的方法:
  7. fetchall(self) //接收全部的返回结果行.
  8. fetchmany(self, size=None) //接收size条返回结果行.如果size的值大于返回的结果行的数量,则会返回cursor.arraysize条数据
  9. fetchone(self) //返回一条结果行
  10. scroll(self, value, mode='relative') //移动指针到某一行.如果mode='relative',则表示从当前所在行移动value条,如果mode='absolute',则表示从结果集的第一行移动value条
  11. rowcount //这是一个只读属性,并返回执行execute()方法后影响的行数

另附MySQL安装:

  yum库安装MySQL

  系统CenOS6.4

1.查看CentOS自带mysql是否已安装

 
  1. yum list installed | grep mysql

2.若有自带安装的mysql,如何卸载CentOS系统自带mysql数据库?  

 
  1. yum -y remove mysql-*

3.查看yum库上的mysql版本信息(CentOS系统需要正常连接网络)。

 
  1. yum list | grep mysql 或 yum -y list mysql*

4.使用yum安装mysql数据库。

 
  1. yum -y install mysql-server mysql mysql-devel

注:安装mysql只是安装了数据库,只有安装mysql-server才相当于安装了客户端。

5.查看刚安装mysql数据库版本信息。 

 
  1. rpm -qi mysql-server

至此,MySQL安装完成!

 

 

转自:https://www.bbsmax.com/A/amd0Mgnkzg/

Python运维自动化开发之Paramiko模块

阅读数 1362

Python运维自动化开发之Paramiko模块原创 2017-11-21 李振良 DevOps大咖  本章讲解使用Python语言的paramiko模块编写服务器批量管理脚本,可完成一些常规任务,例...博文来自: cc297322716的专栏

python3 实现多线程ssh 批量远程执行命令

阅读数 1096

需要模块:paramikopip3installparamikoimportparamikoimportsysimportgetpassdefrcmd(host,password,cmd,port=2...博文来自: A_Gorilla的博客

Python paramiko 模块详解与SSH主要功能模拟

阅读数 1261

我们知道,通过SSH服务可以远程连接到Linux服务器,查看上面的日志状态,批量配置远程服务器,文件上传,文件下载等,Python的paramiko模块同样实现了这一功能。首先我们需要安装这一模块,p...博文来自: u014028063的博客

 

pythonparamiko模块

阅读数 509

paramiko是一个用于做远程控制的模块,使用该模块可以对远程服务器进行命令或文件操作,paramiko是用python语言写的一个模块,遵循SSH2协议,支持以加密和认证的方式,进行远程服务器的连...博文来自: forever_wen的博客

Python3学习(十九):python Paramiko模块的离线安装与使用详解

阅读数 1843

一、背景如果我们想要远程拷贝服务器上面的文件,或者对远程服务器进行相关操作的话,使用paramiko可以很好的解决以上问题。它仅需要在本地上安装相应的软件(python、PyCrypto、ecdsa)...博文来自: liao392781的博客

python paramiko模块实现sftp传输如何提速

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值