初学python之day9

一、python学习之堡垒机实例

paramiko模块


1.安装

1)找到python3.5下的Scripts目录

2)打开cmd,切换到Scripts目录下

3)执行 pip3.5.exe install paramiko

(如果报错,则执行pip install --upgrade pip 更下pip然后再重新执行步骤3)

执行完3)后安装完成

2.验证是否安装成功

在cmd下进入python模式,输入import paramiko,如果无报错,则执行成功

3.实例

1)SSHClient

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

两种连接方式:

1、基于用户名密码的连接:

import paramiko

# 创建SSH对象
ssh = paramiko.SSHClient()
# 允许连接不在know_hosts文件中的主机
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())                                                    首次登录必须加这句话,否则会报错
# 连接服务器
ssh.connect(hostname=‘c1.salt.com‘, port=22, username=‘wupeiqi‘, password=‘123‘)

# 执行命令
stdin, stdout, stderr = ssh.exec_command(‘df‘)
# 获取命令结果
result = stdout.read()

# 关闭连接
ssh.close()

SSH封装transport:

import paramiko

transport = paramiko.Transport((‘hostname‘, 22))
transport.connect(username=‘tianxin‘, password=‘123‘)

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

stdin, stdout, stderr = ssh.exec_command(‘df‘)
print stdout.read()

transport.close()

2、基于公钥的连接

好处:使用公钥私钥连接,可以避免输入用户名和密码,两台机器直接连接

注意:不要把私钥发给别人

import paramiko

private_key = paramiko.RSAKey.from_private_key_file(‘/home/auto/.ssh/id_rsa‘)

# 创建SSH对象
ssh = paramiko.SSHClient()
# 允许连接不在know_hosts文件中的主机
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# 连接服务器
ssh.connect(hostname=‘c1.salt.com‘, port=22, username=‘wupeiqi‘, key=private_key)

# 执行命令
stdin, stdout, stderr = ssh.exec_command(‘df‘)
# 获取命令结果
result = stdout.read()

# 关闭连接
ssh.close()

SSH封装transport:

import paramiko

private_key = paramiko.RSAKey.from_private_key_file(‘/home/auto/.ssh/id_rsa‘)

transport = paramiko.Transport((‘hostname‘, 22))
transport.connect(username=‘wupeiqi‘, pkey=private_key)

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

stdin, stdout, stderr = ssh.exec_command(‘df‘)

transport.close()

2)SFTPClient

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

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

import paramiko

transport = paramiko.Transport((‘hostname‘,22))
transport.connect(username=‘wupeiqi‘,password=‘123‘)

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

transport.close()

2、基于公钥的上传下载

import paramiko

private_key = paramiko.RSAKey.from_private_key_file(‘/home/auto/.ssh/id_rsa‘)

transport = paramiko.Transport((‘hostname‘, 22))
transport.connect(username=‘wupeiqi‘, pkey=private_key )

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

transport.close()

二、python学习之进程与线程

1.线程

1)定义

线程是操作系统能够进行运算调度的最小单位。它被包含在进程之中,是进程中的实际运作单位。一条线程指的是进程中一个单一顺序的控制流,一个进程中可以并发多个线程,每条线程并行执行不同的任务

2)Python Treading模块

Python Treading模块调用方式有两种:

1、直接调用

import threading
import time

def sayhi(num): #定义每个线程要运行的函数

print("running on number:%s" %num)

time.sleep(3)

if __name__ == ‘__main__‘:

t1 = threading.Thread(target=sayhi,args=(1,)) #生成一个线程实例
t2 = threading.Thread(target=sayhi,args=(2,)) #生成另一个线程实例

t1.start() #启动线程
t2.start() #启动另一个线程

print(t1.getName()) #获取线程名
print(t2.getName())

2、继承式调用

import threading
import time

class MyThread(threading.Thread):
def __init__(self,num):
threading.Thread.__init__(self)
self.num = num

def run(self):#定义每个线程要运行的函数

print("running on number:%s" %self.num)

time.sleep(3)

if __name__ == ‘__main__‘:

t1 = MyThread(1)
t2 = MyThread(2)
t1.start()
t2.start()

3、Join & Daemon(守护线程)

特点:当主线程结束时,无论守护线程是否执行完,都会立即停止

#_*_coding:utf-8_*_
__author__ = ‘Alex Li‘

import time
import threading

def run(n):

print(‘[%s]------running----\n‘ % n)
time.sleep(2)
print(‘--done--‘)

def main():
for i in range(5):
t = threading.Thread(target=run,args=[i,])
t.start()
t.join(1)
print(‘starting thread‘, t.getName())

m = threading.Thread(target=main,args=[])
m.setDaemon(True) #将main线程设置为Daemon线程,它做为程序主线程的守护线程,当主线程退出时,m线程也会退出,由m启动的其它子线程会同时退出,不管是否执行完任务
m.start()
m.join(timeout=2)
print("---main thread done----")

4、线程锁(互斥锁Mutex)

作用:当多个线程都对同一份公共数据进行操作,为了避免多个线程对同一份数据同时操作时,就使用线程锁,当一个线程对数据操作完后,另一个线程再继续对这份数据进行操作

import time
import threading

def addNum():
global num #在每个线程中都获取这个全局变量
print(‘--get num:‘,num )
time.sleep(1)
lock.acquire() #修改数据前加锁
num -=1 #对此公共变量进行-1操作
lock.release() #修改后释放

num = 100 #设定一个共享变量
thread_list = []
lock = threading.Lock() #生成全局锁
for i in range(100):
t = threading.Thread(target=addNum)
t.start()
thread_list.append(t)

for t in thread_list: #等待所有线程执行完毕
t.join()

print(‘final num:‘, num )

5、RLock(递归锁)

实现:在大锁中添加若干个小锁

import threading,time

def run1():

    print("grab the first part data")

    lock.acquire()

    global num

    num +=1

    lock.release()

    return num

def run2():

    print("grab the second part data")

    lock.acquire()

    global  num2

    num2+=1

    lock.release()

    return num2

def run3():

    lock.acquire()

    res = run1()

    print(‘--------between run1 and run2-----‘)

    res2 = run2()

    lock.release()

    print(res,res2)

if __name__ == ‘__main__‘:

    num,num2 = 0,0

    lock = threading.RLock()

    for in range(10):

        = threading.Thread(target=run3)

        t.start()

while threading.active_count() != 1:

    print(threading.active_count())

else:

    print(‘----all threads done---‘)

    print(num,num2)

6.Semaphore(信号量)

作用:可以允许一定数量的线程更改数据

import threading,time

def run(n):

    semaphore.acquire()

    time.sleep(1)

    print("run the thread: %s\n" %n)

    semaphore.release()

if __name__ == ‘__main__‘:

    num= 0

    semaphore  = threading.BoundedSemaphore(5#最多允许5个线程同时运行

    for in range(20):

        = threading.Thread(target=run,args=(i,))

        t.start()

while threading.active_count() != 1:

    pass #print threading.active_count()

else:

    print(‘----all threads done---‘)

    print(num)

2.进程

定义:进程就是为一个程序的执行提供所有的资源

时间: 2024-08-26 08:33:39

初学python之day9的相关文章

初学 Python(十一)——切片

初学 Python(十一)--切片 初学 Python,主要整理一些学习到的知识点,这次是切片. #-*- coding:utf-8 -*- ''''' 切片 ''' L = ['name','age','sex','address','company'] #取前2个 print L[0:2] print L[:2] #取倒数第一个 print L[-1] #取后两个 print L[-2:] #取倒数第二个 print L[-2:-1] print len(L) #隔一个数取一次,从第一个数开

初学 Python(十三)——匿名函数

初学 Python,主要整理一些学习到的知识点,这次是匿名函数. # -*- coding:utf-8 -*- #关键字lambda定义的函数都是匿名函数 #做对象 f = lambda x,y:x+y print f(1,2) #做参 print reduce(lambda x,y:x+y,[1,2,3,4,5,6]) #做返回值 def build(x,y): return lambda:x*x+y*y g = build(1,2) print g print g()

初学Python

初学Python 1.Python初识 life is short you need python--龟叔名言 Python是一种简洁优美语法接近自然语言的一种全栈开发语言,由"龟叔"编写开发一种易学易懂高效的语言. Python提供丰富的接口和模块,便于使用其他语言细化,性能提升对要求较高的软件. 以上简单描述了一下Python语言的优点,缺点我就不写了,因为不需要对比,强大的语言自会解决现在几个劣势. 针对于初学者版本选择的问题,因为现在国内大多数在使用2.X版本,个人建议使用3.

【初学python】错误SSLError: [Errno 1] _ssl.c:504:的解决记录

最近在实习公司学习使用python做web自动化测试,其中使用到httplib这个模板,主要用于与待测试界面建立HTTP连接,发送数据请求,接收请求状态码和查询数据,验证功能.但是新版本的web界面改成使用https协议,原来的测试用例都变成无法跑通的状态. 将协议从HTTP改成HTTPS后,报以下错误: SSLError: [Errno 1] _ssl.c:504: error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown proto

初学Python(九)——函数

初学Python(九)--函数 初学Python,主要整理一些学习到的知识点,这次是函数. 函数定义: # -*- coding:utf-8 -*- #函数的定义 def my_function(x): if x>0: return x elif x<0: return -x else: pass #函数的调用 a = my_function(-1) b = my_function(2) c = my_function(0) print a,b,c #空函数,pass为占位符 def empt

初学 Python(十四)——生成器

初学 Python(十四)--生成器 初学 Python,主要整理一些学习到的知识点,这次是生成器. # -*- coding:utf-8 -*- ''''' 生成式的作用: 减少内存占有,不用一次性 创建list中所有的元素,而 是在需要的时候创建 ''' #创建generator有2种方式 #第一种将列表表达式中的[]改为()即可 g = (x*x for x in range(10)) print g for n in g: print n #第二种,关键字yield def fab(ma

初学 Python(十二)——高阶函数

初学 Python(十二)--高阶函数 初学 Python,主要整理一些学习到的知识点,这次是高阶函数. #-*- coding:utf-8 -*- ''''' 话说高阶函数: 能用函数作为参数的函数 称为高阶函数 ''' #函数作参 def f(x): return x*x #map函数为内置函数,意思为将第二个参数的list作用到f函数中 #最后的结果为一个list print map(f,[1,2,3,4,5]) #reduce函数为内置函数,意思将第二参数的序列作用到add函数值 #将结

初学Python(八)——迭代

初学Python(八)——迭代 初学Python,主要整理一些学习到的知识点,这次是迭代. # -*- coding:utf-8 -*- from collections import Iterable ''''' 迭代 ''' L = ['af','st','at','psst','beta'] D = {1:'af',2:'st',3:'at',4:'psst',5:'beta'} S = 'helloworld' #数组 for item in L: print item #字典 for

Check iO:初学Python

The end of other For language training our Robots want to learn about suffixes. In this task, you are given a set of words in lower case. Check whether there is a pair of words, such that one word is the end of another (a suffix of another). For exam