python开发模块基础:collections模块&paramiko模块

一,collections模块

在内置数据类型(dict、list、set、tuple)的基础上,collections模块还提供了几个额外的数据类型:Counter、deque、defaultdict、namedtuple和OrderedDict等。
1.namedtuple: 生成可以使用名字来访问元素内容的tuple
2.deque: 双端队列,可以快速的从另外一侧追加和推出对象
3.Counter: 计数器,主要用来计数
4.OrderedDict: 有序字典
5.defaultdict: 带有默认值的字典

 1 #!/usr/bin/python env
 2 #_*_coding:utf-8_*_
 3 
 4 # 1.namedtuple (重点)
 5 from collections import namedtuple
 6 Ponit = namedtuple('Ponit',['x','y','z'])
 7 p = Ponit(1,2,5)
 8 print(p.x)
 9 print(p.y)
10 print(p.z)
11 
12 # 2.deque
13 '''
14 使用list存储数据时,按索引访问元素很快,但是插入和删除元素就很慢了,因为list是线性存储,数据量大的时候,插入和删除效率很低
15 deque是为了高效实现插入和删除操作的双向列表,适合用于队列和栈:
16 '''
17 from collections import deque
18 q = deque(['a', 'b', 'c'])
19 q.append('x')
20 q.appendleft('y')
21 # print(q)
22 #deque(['y', 'a', 'b', 'c', 'x'])
23 # deque除了实现list的append()和pop()外,还支持appendleft()和popleft(),这样就可以非常高效地往头部添加或删除元素
24 
25 # 3.OrderedDict (重点)消耗内存
26 '''
27 使用dict时,Key是无序的。在对dict做迭代时,我们无法确定Key的顺序。
28 如果要保持Key的顺序,可以用OrderedDict:
29 '''
30 from collections import OrderedDict
31 d = dict([('a', 1), ('b', 2), ('c', 3)])
32 print(d)
33 #d dict的Key是无序的
34 #{'a': 1, 'c': 3, 'b': 2}
35 od = OrderedDict([('a', 1), ('b', 2), ('c', 3)])
36 print(od)
37 #od OrderedDict的Key是有序的
38 #OrderedDict([('a', 1), ('b', 2), ('c', 3)])
39 
40 # 注意,OrderedDict的Key会按照插入的顺序排列,不是Key本身排序
41 od = OrderedDict()
42 od['z'] = 1
43 od['y'] = 2
44 od['x'] = 3
45 od.keys() # 按照插入的Key的顺序返回
46 #['z', 'y', 'x']
47 
48 # 4.defaultdict (重点)(带默认的字典,就是当这个)
49 # 有如下值集合 [11,22,33,44,55,66,77,88,99,90...],将所有大于 66 的值保存至字典的第一个key中,将小于 66 的值保存至第二个key的值中。
50 # 普通代码,需要判断这个key,vales存在不存在
51 values = [11, 22, 33,44,55,66,77,88,99,90]
52 my_dict = {}
53 for value in  values:
54     if value>66:
55         if my_dict.has_key('k1'):
56             my_dict['k1'].append(value)
57         else:
58             my_dict['k1'] = [value]
59     else:
60         if my_dict.has_key('k2'):
61             my_dict['k2'].append(value)
62         else:
63             my_dict['k2'] = [value]
64 
65 # 使用dict时,如果引用的Key不存在,就会抛出KeyError。如果希望key不存在时,返回一个默认值,就可以用defaultdict:
66 # 进阶版本   会给返回默认的参数,用了匿名函数的原理
67 from collections import defaultdict
68 values = [11, 22, 33,44,55,66,77,88,99,90]
69 my_dict = defaultdict(list)
70 for value in  values:
71     if value>66:
72         my_dict['k1'].append(value)
73     else:
74         my_dict['k2'].append(value)
75 
76 #匿名函数
77 from collections import defaultdict
78 def func():
79     return 'N/A'
80 my_dict = defaultdict(func)
81 print(my_dict['k'])
82 
83 # 5.Counter
84 # Counter类的目的是用来跟踪值出现的次数。它是一个无序的容器类型,以字典的键值对形式存储,其中元素作为key,其计数作为value。计数值可以是任意的Interger(包括0和负数)。Counter类和其他语言的bags或multisets很相似。
85 from collections import Counter
86 c = Counter('abcdeabcdabcaba')
87 print(c)
88 # 输出:Counter({'a': 5, 'b': 4, 'c': 3, 'd': 2, 'e': 1})
89 # http://www.cnblogs.com/Eva-J/articles/7291842.html

 

二,paramiko模块

1. 介绍:

paramiko是一个用于做远程控制的模块,使用该模块可以对远程服务器进行命令或文件操作,值得一说的是,fabric和ansible内部的远程管理就是使用的paramiko来现实。

2. 下载安装

pip3 install paramiko #在python3中
pycrypto,由于 paramiko 模块内部依赖pycrypto,所以先下载安装pycrypto #在python2中
pip3 install pycrypto
pip3 install paramiko
注:如果在安装pycrypto2.0.1时发生如下错误
        command 'gcc' failed with exit status 1...
可能是缺少python-dev安装包导致
如果gcc没有安装,请事先安装gcc
在python2中

3. 使用

SSHClient

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

基于用户名密码连接:

import paramiko

# 创建SSH对象
ssh = paramiko.SSHClient()
# 允许连接不在know_hosts文件中的主机
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# 连接服务器
ssh.connect(hostname='120.92.84.249', port=22, username='root', password='xxx')

# 执行命令
stdin, stdout, stderr = ssh.exec_command('df')
# 获取命令结果
result = stdout.read()
print(result.decode('utf-8'))
# 关闭连接
ssh.close()
import paramiko

transport = paramiko.Transport(('120.92.84.249', 22))
transport.connect(username='root', password='xxx')

ssh = paramiko.SSHClient()
ssh._transport = transport

stdin, stdout, stderr = ssh.exec_command('df')
res=stdout.read()
print(res.decode('utf-8'))

transport.close()
SSHClient 封装 Transport

基于公钥密钥连接:

客户端文件名:id_rsa

服务端必须有文件名:authorized_keys(在用ssh-keygen时,必须制作一个authorized_keys,可以用ssh-copy-id来制作)

import paramiko

private_key = paramiko.RSAKey.from_private_key_file('/tmp/id_rsa')

# 创建SSH对象
ssh = paramiko.SSHClient()
# 允许连接不在know_hosts文件中的主机
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# 连接服务器
ssh.connect(hostname='120.92.84.249', port=22, username='root', pkey=private_key)

# 执行命令
stdin, stdout, stderr = ssh.exec_command('df')
# 获取命令结果
result = stdout.read()
print(result.decode('utf-8'))
# 关闭连接
ssh.close()
View Code
import paramiko

private_key = paramiko.RSAKey.from_private_key_file('/tmp/id_rsa')

transport = paramiko.Transport(('120.92.84.249', 22))
transport.connect(username='root', pkey=private_key)

ssh = paramiko.SSHClient()
ssh._transport = transport

stdin, stdout, stderr = ssh.exec_command('df')
result=stdout.read()
print(result.decode('utf-8'))

transport.close()
SSHClient 封装 Transport 
import paramiko
from io import StringIO

key_str = """-----BEGIN RSA PRIVATE KEY-----
MIIEoQIBAAKCAQEAsJmFLrSeCumJvga0Gl5O5wVOVwMIy2MpqIyQPi5J87dg89a4
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Q/J1eQ/YkDfmznH+ok6YjHkGlgLsRuXHW
GdcDCwuzBUCWh76LHC1EytUCKnloa3qy8jfjWnMlHgrd3FtDILrC+C7p1Vj2FAvm
qVz0moiTpioPL8twp9MCgYEAin49q3EyZFYwxwdpU7/SJuvq750oZq0WVriUINsi
A6IR14oOvbqkhb94fhsY12ZGt/N9uosq22H+anms6CicoQicv4fnBHDFI3hCHE9I
pgeh50GTJHUA6Xk34V2s/kp5KpThazv6qCw+QubkQExh660SEdSlvoCfPKMCi1EJ
TukCgYAZKY1NZ2bjJyyO/dfNvMQ+etUL/9esi+40GUGyJ7SZcazrN9z+DO0yL39g
7FT9NMIc2dsmNJQMaGBCDl0AjO1O3b/wqlrNvNBGkanxn2Htn5ajfo+LBU7yHAcV
7w4X5HLarXiE1mj0LXFKJhdvFqU53KUQJXBqR6lsMqzsdPwLMJg==
-----END RSA PRIVATE KEY-----"""

private_key = paramiko.RSAKey(file_obj=StringIO(key_str))
transport = paramiko.Transport(('120.92.84.249', 22))
transport.connect(username='root', pkey=private_key)

ssh = paramiko.SSHClient()
ssh._transport = transport

stdin, stdout, stderr = ssh.exec_command('df')
result = stdout.read()
print(result.decode('utf-8'))
transport.close()

print(result)
基于私钥字符串进行连接

SFTPClient

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

基于用户名密码上传下载

import paramiko
 
transport = paramiko.Transport(('120.92.84.249',22))
transport.connect(username='root',password='xxx')
 
sftp = paramiko.SFTPClient.from_transport(transport)
# 将location.py 上传至服务器 /tmp/test.py
sftp.put('/tmp/id_rsa', '/etc/test.rsa')
# 将remove_path 下载到本地 local_path
sftp.get('remove_path', 'local_path')
 
transport.close()
View Code

基于公钥密钥上传下载

import paramiko

private_key = paramiko.RSAKey.from_private_key_file('/tmp/id_rsa')

transport = paramiko.Transport(('120.92.84.249', 22))
transport.connect(username='root', pkey=private_key )

sftp = paramiko.SFTPClient.from_transport(transport)
# 将location.py 上传至服务器 /tmp/test.py
sftp.put('/tmp/id_rsa', '/tmp/a.txt')
# 将remove_path 下载到本地 local_path
sftp.get('remove_path', 'local_path')

transport.close()
View Code
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import paramiko
import uuid

class Haproxy(object):

    def __init__(self):
        self.host = '172.16.103.191'
        self.port = 22
        self.username = 'root'
        self.pwd = '123'
        self.__k = None

    def create_file(self):
        file_name = str(uuid.uuid4())
        with open(file_name,'w') as f:
            f.write('sb')
        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)
        # 将location.py 上传至服务器 /tmp/test.py
        sftp.put(file_name, '/home/root/tttttttttttt.py')

    def rename(self):

        ssh = paramiko.SSHClient()
        ssh._transport = self.__transport
        # 执行命令
        stdin, stdout, stderr = ssh.exec_command('mv /home/root/tttttttttttt.py /home/root/ooooooooo.py')
        # 获取命令结果
        result = stdout.read()


ha = Haproxy()
ha.run()
Demo 

 

posted @ 2017-08-09 21:56  liqianlong  阅读(619)  评论(0编辑  收藏  举报