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('www','man',18,'')
  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='127.0.0.1',user='root',passwd='',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='127.0.0.1',user='root',passwd='',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='127.0.0.1',user='root',passwd='',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='127.0.0.1',user='root',passwd='',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='127.0.0.1',user='root',passwd='',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='127.0.0.1',user='root',passwd='',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='127.0.0.1',user='root',passwd='',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安装完成!

 

Python Paramiko模块与MySQL数据库操作的更多相关文章

  1. [Python] 学习笔记之MySQL数据库操作

    1 Python标准数据库接口DB-API介绍 Python标准数据库接口为 Python DB-API,它为开发人员提供了数据库应用编程接口.Python DB-API支持很多种的数据库,你可以选择 ...

  2. python笔记二(mysql数据库操作)

    python2.x使用MySQLdb python3.x使用pymysql代替MySQLdb 不过我使用的是python3.5,MySQLdb还是可以在python3.5使用的. #!/usr/bin ...

  3. python 2 如何安装 MySQL 数据库操作库

    我试了好几种网上的办法,在 windows 10 VS2017 环境下不是缺了头文件,就是缺 .lib,反正十分繁琐,以后我也懒得搞了,都用 annaconda 来搞定就好了,时间宝贵. 在 控制台中 ...

  4. Python进行MySQL数据库操作

    最近开始玩Python,慢慢开始喜欢上它了,以前都是用shell来实现一些自动化或者监控的操作,现在用Python来实现,感觉更棒,Python是一门很强大的面向对象语言,所以作为一个运维DBA或者运 ...

  5. python之(mysql数据库操作)

    前言:关心3步骤(此文章只针对python自动化根基展开描述) 什么是mysql数据库操作?  答:利用python对mysql数据库进行增, 删, 改, 查 操作 为什么要用python对mysql ...

  6. Python/MySQL(四、MySQL数据库操作)

    Python/MySQL(四.MySQL数据库操作) 一.数据库条件语句: case when id>9 then ture else false 二.三元运算: if(isnull(xx)0, ...

  7. Python数据存储 — MySQL数据库操作

    本地安装MySQL 调试环境python3.6,调试python操作mysql数据库,首先要在本地或服务器安装mysql数据库. 安装参考:https://mp.csdn.net/postedit/8 ...

  8. python程序中使用MySQL数据库

    目录 python程序中使用MySQL数据库 1 pymysql连接数据库 2 sql 注入 3 增删改查操作 4 pymysql使用总结 python程序中使用MySQL数据库 1.python中使 ...

  9. python paramiko模块学习分享

    python paramiko模块学习分享 paramiko是用python语言写的一个模块,遵循SSH2协议,支持以加密和认证的方式,进行远程服务器的连接.paramiko支持Linux, Sola ...

随机推荐

  1. 如何让ie 7 支持box-shadow

    box-shadow是一个很好用并且也常用的css 3属性,但是,如果我们要保证它能在ie 8及更低的版本下运行的话,需要借助一些其他的插件或文件.在这里我主要讲一下,如何用PIE.htc来解决ie ...

  2. Java多线程与并发库高级应用-线程池

    线程池 线程池的思想  线程池的概念与Executors类的应用 > 创建固定大小的线程池 > 创建缓存线程池 > 创建单一线程池(如何实现线程死掉后重新启动?) 关闭线程池 > ...

  3. Leetcode Integer Replacement

    Given a positive integer n and you can do operations as follow: If n is even, replace n with n/2. If ...

  4. 【caffe】epoch,[batch_size],iteration的含义

    @tags caffe 概念 一个epoch表示"大层面上的一次迭代",也就是指,(假定是训练阶段)处理完所有训练图片,叫一个epoch 但是每次训练图片可能特别多,内存/显存塞不 ...

  5. 【BZOJ-1009】GT考试 KMP+DP+矩阵乘法+快速幂

    1009: [HNOI2008]GT考试 Time Limit: 1 Sec  Memory Limit: 162 MBSubmit: 2745  Solved: 1694[Submit][Statu ...

  6. 设置CentOS6.5时钟同步

    一.测试ntp服务 # rpm -q ntp ntp-4.2.4p8-2.el6.x86_64 // 这表示已安装了,如果没有安装,这是空白. 二./etc/ntp.conf 红色部分是修改的. 配置 ...

  7. 百度地图学习(Ⅰ)-Android端地图的显示及简单应用

    ps:(1.地图应用一定要在真机测试: 2.Design By:Android Stdio: 3.百度地图官方参考链接(http://developer.baidu.com/map/index.php ...

  8. Unity 联网小测试(WWW)

    研究了很多联网的方式,甚至把TCP/IP,shock,HTTP的关系都搞清楚了,终于弄明白怎么在Unity中用GET或POST的方式通信了,还是有点小激动的,但是不排除有更好的方式,听说Unity还是 ...

  9. AngularJs angular.Module模块接口配置

    angular.Module Angular模块配置接口. 方法: provider(name,providerType); name:服务名称. providerType:创建一个服务的实例的构造函 ...

  10. Appium for IOS testing on Mac

    一:环境 1.Mac OS X 10.9.1 2.Xcod 5.0.2 3.Appium 1.3.6 下载地址:https://bitbucket.org/appium/appium.app/down ...