Python学习day9

一、堡垒机

1.ssh.py实例:

#Author:Fred
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()

2.ssh_ftp.py:
#Author:Fred
import paramiko

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

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

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

transport.close()

3.ssh_rass.py:
#Author:Fred
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()

二、进程与线程

  程序并不能单独运行,只有将程序装载到内存中,系统为它分配资源才能运行,而这种执行的程序就称之为进程。程序和进程的区别就在于:程序是指令的集合,它是进程运行的静态描述文本;进程是程序的一次执行活动,属于动态概念。在多道编程中,我们允许多个程序同时加载到内存中,在操作系统的调度下,可以实现并发地执行。这是这样的设计,大大提高了CPU的利用率。进程的出现让每个用户感觉到自己独享CPU,因此,进程就是为了在CPU上实现多道编程而提出的。

  

  进程有很多优点,它提供了多道编程,让我们感觉我们每个人都拥有自己的CPU和其他资源,可以提高计算机的利用率。很多人就不理解了,既然进程这么优秀,为什么还要线程呢?其实,仔细观察就会发现进程还是有很多缺陷的,主要体现在两点上:

  • 进程只能在一个时间干一件事,如果想同时干两件事或多件事,进程就无能为力了。

  • 进程在执行的过程中如果阻塞,例如等待输入,整个进程就会挂起,即使进程中有些工作不依赖于输入的数据,也将无法执行。

例如,我们在使用qq聊天, qq做为一个独立进程如果同一时间只能干一件事,那他如何实现在同一时刻 即能监听键盘输入、又能监听其它人给你发的消息、同时还能把别人发的消息显示在屏幕上呢?你会说,操作系统不是有分时么?但我的亲,分时是指在不同进程间的分时呀, 即操作系统处理一会你的qq任务,又切换到word文档任务上了,每个cpu时间片分给你的qq程序时,你的qq还是只能同时干一件事呀。再直白一点, 一个操作系统就像是一个工厂,工厂里面有很多个生产车间,不同的车间生产不同的产品,每个车间就相当于一个进程,且你的工厂又穷,供电不足,同一时间只能给一个车间供电,为了能让所有车间都能同时生产,你的工厂的电工只能给不同的车间分时供电,但是轮到你的qq车间时,发现只有一个干活的工人,结果生产效率极低,为了解决这个问题,应该怎么办呢?。。。。没错,你肯定想到了,就是多加几个工人,让几个人工人并行工作,这每个工人,就是线程!

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

线程与进程的区别:

  1. Threads share the address space of the process that created it; processes have their own address space.
  2. Threads have direct access to the data segment of its process; processes have their own copy of the data segment of the parent process.
  3. Threads can directly communicate with other threads of its process; processes must use interprocess communication to communicate with sibling processes.
  4. New threads are easily created; new processes require duplication of the parent process.
  5. Threads can exercise considerable control over threads of the same process; processes can only exercise control over child processes.
  6. Changes to the main thread (cancellation, priority change, etc.) may affect the behavior of the other threads of the process; changes to the parent process does not affect child processes.

1.test1.py:
#Author:Fred #最简单的并行线程
import threading,time

def run(n):
print("task",n)
time.sleep(2)
print("task done",n)
start_time = time.time()
t_objs = []
for i in range(50):
t = threading.Thread(target=run,args=("t-%s" %i,))
t.start()
t_objs.append(t)

# for t in t_objs: #循环线程实例列表,等待所有线程执行完毕
# t.join()
print("-------all threads has finished..")
print("cost:",time.time() - start_time)
# run("t1")
# run("t2")

2.test2.py:
#Author:Fred #最简单的并行线程
import threading,time

class MyThread(threading.Thread):
def __init__(self,n,sleep_time):
super(MyThread,self).__init__()
self.n = n
self.sleep_time = sleep_time

def run(self):
print("running task",self.n)
time.sleep(self.sleep_time)
print("task done,",self.n)

t1 = MyThread("t1",2)
t2 = MyThread("t2",4)

t1.start()
t2.start()

t1.join()
t2.join()
print("main thread...")

3.test3.py:
#Author:Fred #最简单的并行线程
import threading,time

def run(n):
print("task",n)
time.sleep(2)
print("task done",n,threading.current_thread())
start_time = time.time()
t_objs = []
for i in range(50):
t = threading.Thread(target=run,args=("t-%s" %i,))
t.setDaemon(True) #把当前线程设置为守护线程,一定要在start之前
t.start()
t_objs.append(t) #为了不阻塞后面线程的启动,不在这里join,先放到一个列表里

# for t in t_objs:
# t.join()

time.sleep(2)
print("-------all threads has finished..",threading.current_thread(),threading.active_count())
print("cost:",time.time() - start_time)
# run("t1")
# run("t2")

三、线程锁
1.加锁版本lock.py:
#Author:Fred #最简单的并行线程
import threading,time

def run(n):
lock.acquire() #获取一把锁,3.0以上无所谓
global num
num += 1
lock.release()

lock = threading.Lock()
num = 0
t_objs = [] #存线程实例
for i in range(50):
t = threading.Thread(target=run,args=("t-%s" %i,))
t.setDaemon(True) #把当前线程设置为守护线程,一定要在start之前
t.start()
t_objs.append(t) #为了不阻塞后面线程的启动,不在这里join,先放到一个列表里

for t in t_objs:
t.join()

print("-------all threads has finished..",threading.current_thread(),threading.active_count())
print("num",num)

2.递归锁rlock.py:
#Author:Fred
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 i in range(10):
t = threading.Thread(target=run3)
t.start()

while threading.active_count() != 1:
print(threading.active_count())
else:
print('----all threads done---')
print(num,num2)

3.信号量.pysemaphore:
#Author:Fred
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 i in range(20):
t = 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)

4.红灯绿灯event.py:
#Author:Fred
import time,threading

event = threading.Event()
def lighter():
count = 0
event.set() #先设为绿灯
while True:
if count > 5 and count < 10:#改成红灯
event.clear() #吧标志位清除
print("\033[41;1mred light is on...\033[0m")
elif count > 10:
event.set() #变成绿灯
count = 0
else:
print("\033[42;1mgreen light is on...\033[0m")
time.sleep(1)
count += 1
def car(name):
while True:
if event.is_set():#代表绿灯
print("[%s] running..."% name)
time.sleep(1)
else:
print("[%s] sees red light,waiting..." % name)
event.wait()
print("\033[34;1m[%s] green light is on,start going...\033[0m"% name)

light = threading.Thread(target=lighter,)
light.start()

car1 = threading.Thread(target=car,args=("Tesla",))
car1.start()

四、队列queue
#Author:Fred

import queue

q = queue.PriorityQueue()

q.put((10,"alex"))
q.put((-1,"crh"))
q.put((3,"hy"))
q.put((6,"ws"))
print(q.get())
print(q.get())
print(q.get())
print(q.get())

五、生产者消费者实例.py:

在并发编程中使用生产者和消费者模式能够解决绝大多数并发问题。该模式通过平衡生产线程和消费线程的工作能力来提高程序的整体处理数据的速度。

为什么要使用生产者和消费者模式

在线程世界里,生产者就是生产数据的线程,消费者就是消费数据的线程。在多线程开发当中,如果生产者处理速度很快,而消费者处理速度很慢,那么生产者就必须等待消费者处理完,才能继续生产数据。同样的道理,如果消费者的处理能力大于生产者,那么消费者就必须等待生产者。为了解决这个问题于是引入了生产者和消费者模式。

什么是生产者消费者模式

生产者消费者模式是通过一个容器来解决生产者和消费者的强耦合问题。生产者和消费者彼此之间不直接通讯,而通过阻塞队列来进行通讯,所以生产者生产完数据之后不用等待消费者处理,直接扔给阻塞队列,消费者不找生产者要数据,而是直接从阻塞队列里取,阻塞队列就相当于一个缓冲区,平衡了生产者和消费者的处理能力。

#Author:Fred
import threading,time,queue
q = queue.Queue(maxsize=10)
def Producer(name):
count = 1
while True:
q.put("骨头%s" %count)
print("生产了骨头",count)
count += 1
time.sleep(2)
def Consumer(name):
while True:
print("[%s] 取到 [%s] 并且吃了它..." %(name,q.get()))
time.sleep(1)

p = threading.Thread(target=Producer,args=("Alex",))
c = threading.Thread(target=Consumer,args=("crh",))
c1 = threading.Thread(target=Consumer,args=("ws",))
p.start()
c.start()
c1.start()



posted @ 2019-12-18 23:11  ZzXx1210  阅读(280)  评论(0)    收藏  举报