1 #########執行命令 2 import paramiko 3 # 建立SSH對象 4 ssh = paramiko.SSHClient() 5 # 容許鏈接不在know_hosts(~/.ssh/known_hosts)文件中的主機 6 ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) 7 # 鏈接服務器 8 ssh.connect(hostname='c1.salt.com', port=22, username='wupeiqi', password='123') 9 # 執行命令 10 stdin, stdout, stderr = ssh.exec_command('df') 11 # 獲取命令結果 12 result = stdout.read() 13 # 關閉鏈接 14 ssh.close() 15 16 #########SSHClient封裝Transport 17 import paramiko 18 transport = paramiko.Transport(('hostname', 22)) 19 transport.connect(username='wupeiqi', password='123') 20 ssh = paramiko.SSHClient() 21 ssh._transport = transport 22 stdin, stdout, stderr = ssh.exec_command('df') 23 print(stdout.read()) 24 transport.close()
1 #########執行命令 2 import paramiko 3 private_key = paramiko.RSAKey.from_private_key_file('/home/auto/.ssh/id_rsa') 4 # 建立SSH對象 5 ssh = paramiko.SSHClient() 6 # 容許鏈接不在know_hosts文件中的主機 7 ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) 8 # 鏈接服務器 9 ssh.connect(hostname='c1.salt.com', port=22, username='wupeiqi', key=private_key) 10 # 執行命令 11 stdin, stdout, stderr = ssh.exec_command('df') 12 # 獲取命令結果 13 result = stdout.read() 14 # 關閉鏈接 15 ssh.close() 16 17 #########SSHClient 封裝 Transport 18 import paramiko 19 private_key = paramiko.RSAKey.from_private_key_file('/home/auto/.ssh/id_rsa') 20 transport = paramiko.Transport(('hostname', 22)) 21 transport.connect(username='wupeiqi', pkey=private_key) 22 ssh = paramiko.SSHClient() 23 ssh._transport = transport 24 stdin, stdout, stderr = ssh.exec_command('df') 25 transport.close() 26 27 #########基於私鑰字符串進行鏈接 28 import paramiko 29 from io import StringIO 30 31 key_str = """-----BEGIN RSA PRIVATE KEY----- 32 MIIEpQIBAAKCAQEAq7gLsqYArAFco02/55IgNg0r7NXOtEM3qXpb/dabJ5Uyky/8 33 NEHhFiQ7deHIRIuTW5Zb0kD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FGQfgaFoKfaawoYeH 50 C2XasVUsVviBn8kPSLSVBPX4JUfQmA6h8HsajeVahxN1U9e0nYJ0sYDQFUMTS2t8 51 RT57+WK/0ONwTWHdu+KnaJECgYEAid/ta8LQC3p82iNAZkpWlGDSD2yb/8rH8NQg 52 9tjEryFwrbMtfX9qn+8srx06B796U3OjifstjJQNmVI0qNlsJpQK8fPwVxRxbJS/ 53 pMbNICrf3sUa4sZgDOFfkeuSlgACh4cVIozDXlR59Z8Y3CoiW0uObEgvMDIfenAj 54 98pl3ZkCgYEAj/UCSni0dwX4pnKNPm6LUgiS7QvIgM3H9piyt8aipQuzBi5LUKWw 55 DlQC4Zb73nHgdREtQYYXTu7p27Bl0Gizz1sW2eSgxFU8eTh+ucfVwOXKAXKU5SeI 56 +MbuBfUYQ4if2N/BXn47+/ecf3A4KgB37Le5SbLDddwCNxGlBzbpBa0= 57 -----END RSA PRIVATE KEY-----""" 58 59 private_key = paramiko.RSAKey(file_obj=StringIO(key_str)) 60 transport = paramiko.Transport(('10.0.1.40', 22)) 61 transport.connect(username='wupeiqi', pkey=private_key) 62 ssh = paramiko.SSHClient() 63 ssh._transport = transport 64 stdin, stdout, stderr = ssh.exec_command('df') 65 result = stdout.read() 66 transport.close() 67 print(result)
1 import paramiko 2 transport = paramiko.Transport(('hostname',22)) 3 transport.connect(username='wupeiqi',password='123') 4 sftp = paramiko.SFTPClient.from_transport(transport) 5 # 將location.py 上傳至服務器 /tmp/test.py 6 sftp.put('/tmp/location.py', '/tmp/test.py') 7 # 將remove_path 下載到本地 local_path 8 sftp.get('remove_path', 'local_path') 9 transport.close()
1 import paramiko 2 private_key = paramiko.RSAKey.from_private_key_file('/home/auto/.ssh/id_rsa') 3 transport = paramiko.Transport(('hostname', 22)) 4 transport.connect(username='wupeiqi', pkey=private_key ) 5 sftp = paramiko.SFTPClient.from_transport(transport) 6 # 將location.py 上傳至服務器 /tmp/test.py 7 sftp.put('/tmp/location.py', '/tmp/test.py') 8 # 將remove_path 下載到本地 local_path 9 sftp.get('remove_path', 'local_path') 10 transport.close()
1 import threading 2 import time 3 4 def run(n): 5 print("task ",n ) 6 time.sleep(2) 7 print("task done",n,,threading.current_thread()) 8 9 start_time = time.time() 10 t_objs = [] #存線程實例 11 for i in range(50): 12 t = threading.Thread(target=run,args=("t-%s" %i ,))
t.setDaemon(True) #把當前線程設置爲守護線程,必須在線程start以前設置 13 t.start() 14 t_objs.append(t) #爲了避免阻塞後面線程的啓動,不在這裏join,先放到一個列表裏 15 16 for t in t_objs: #循環線程實例列表,等待全部線程執行完畢 17 t.join() 18 19 print("----------all threads has finished...",threading.current_thread(),threading.active_count()) 20 print("cost:",time.time() - start_time)
1 import threading 2 import time 3 4 class MyThread(threading.Thread): 5 def __init__(self,n,sleep_time): 6 super(MyThread,self).__init__() 7 self.n = n 8 self.sleep_time = sleep_time 9 def run(self): 10 print("runnint task ",self.n ) 11 time.sleep(self.sleep_time) 12 print("task done,",self.n ) 13 14 15 t1 = MyThread("t1",2) 16 t2 = MyThread("t2",4) 17 18 t1.start() 19 t2.start() 20 21 t1.join() #=wait() 22 t2.join() 23 24 print("main thread....")
1 import threading 2 import time 3 4 def run(n): 5 lock.acquire() #修改數據前加鎖 6 global num 7 num +=1 8 time.sleep(1) 9 lock.release() #修改後釋放 10 11 12 lock = threading.Lock() #生成全局鎖(互斥鎖) 13 num = 0 #設定一個共享變量 14 t_objs = [] #存線程實例 15 for i in range(50): 16 t = threading.Thread(target=run,args=("t-%s" %i ,)) 17 t.start() 18 t_objs.append(t) #爲了避免阻塞後面線程的啓動,不在這裏join,先放到一個列表裏 19 20 for t in t_objs: #循環線程實例列表,等待全部線程執行完畢 21 t.join() 22 23 print("----------all threads has finished...",threading.current_thread(),threading.active_count()) 24 25 print("num:",num)
1 import threading, time 2 3 def run1(): 4 print("grab the first part data") 5 lock.acquire() 6 global num 7 num += 1 8 lock.release() 9 return num 10 11 def run2(): 12 print("grab the second part data") 13 lock.acquire() 14 global num2 15 num2 += 1 16 lock.release() 17 return num2 18 19 def run3(): 20 lock.acquire() 21 res = run1() 22 print('--------between run1 and run2-----') 23 res2 = run2() 24 lock.release() 25 print(res, res2) 26 27 num, num2 = 0, 0 28 lock = threading.RLock() #遞歸鎖 29 for i in range(10): 30 t = threading.Thread(target=run3) 31 t.start() 32 33 while threading.active_count() != 1: 34 print(threading.active_count()) 35 else: 36 print('----all threads done---') 37 print(num, num2)
1 import threading, time 2 3 def run(n): 4 semaphore.acquire() 5 time.sleep(1) 6 print("run the thread: %s\n" % n) 7 semaphore.release() 8 9 if __name__ == '__main__': 10 semaphore = threading.BoundedSemaphore(5) # 最多容許5個線程同時運行 11 for i in range(22): 12 t = threading.Thread(target=run, args=(i,)) 13 t.start() 14 while threading.active_count() != 1: 15 pass 16 else: 17 print('----all threads done---')
1 import time 2 import threading 3 4 event = threading.Event() 5 6 def lighter(): 7 count = 0 8 event.set() #先設置綠燈 9 while True: 10 if count >5 and count < 10: #改爲紅燈 11 event.clear() #把標誌位清了 12 print("red light is on....") 13 elif count >10: 14 event.set() #變綠燈 15 count = 0 16 else: 17 print("green light is on....") 18 time.sleep(1) 19 count +=1 20 print(count) 21 def car(name): 22 while True: 23 if event.is_set(): #表明綠燈 24 print("[%s] running..."% name ) 25 time.sleep(1) 26 else: 27 print("[%s] sees red light , waiting...." %name) 28 event.wait() 29 print("[%s] green light is on, start going..." %name) 30 31 32 light = threading.Thread(target=lighter,) 33 light.start() 34 35 car1 = threading.Thread(target=car,args=("Tesla",)) 36 car1.start()
1 from queue import Queue #LILO隊列 2 #基本FIFO隊列 先進先出 FIFO即First in First Out,先進先出 3 #maxsize設置隊列中,數據上限,小於或等於0則不限制,容器中大於這個數則阻塞,直到隊列中的數據被消掉 4 q = Queue(maxsize=0) 5 #寫入隊列數據 6 q.put(0) 7 q.put(1) 8 q.put(2) 9 #返回隊列大小 10 print(q.qsize()) 11 #若是隊列爲空,返回True 12 print(q.empty()) 13 #若是隊列滿了,返回True,大小與maxsize的值對應 14 print(q.full()) 15 #不等待,直接獲取數據,如隊列爲空,則不等待隊列放入信息後取出數據,直接報錯 16 print(q.get_nowait()) 17 #不等待,直接寫入數據,如隊列已滿,則不等待隊列信息取出後再放入,直接報錯 18 q.put_nowait(3) 19 #輸出當前隊列全部數據 20 print(q.queue) 21 #刪除隊列數據,並返回該數據 22 q.get() 23 #輸也全部隊列數據 24 print(q.queue)
1 from queue import LifoQueue #LIFO隊列 2 #LIFO即Last in First Out,後進先出。與棧的相似,使用也很簡單,maxsize用法同上 3 lq = LifoQueue(maxsize=0) 4 #隊列寫入數據 5 lq.put(0) 6 lq.put(1) 7 lq.put(2) 8 #輸出隊列全部數據 9 print(lq.queue) 10 #刪除隊尾數據,並返回該數據 11 lq.get() 12 #輸出隊列全部數據 13 print(lq.queue)
1 from queue import PriorityQueue #優先隊列 2 # 存儲數據時可設置優先級的隊列,優先級設置數越小等級越高 3 pq = PriorityQueue(maxsize=0) 4 #寫入隊列,設置優先級 5 pq.put((9,'a')) 6 pq.put((7,'c')) 7 pq.put((1,'d')) 8 #輸出隊例所有數據 9 print(pq.queue) 10 #取隊例數據,能夠看到,是按優先級取的。 11 pq.get() 12 pq.get() 13 print(pq.queue)
1 from collections import deque #雙端隊列 2 #雙邊隊列 3 dq = deque(['a','b']) 4 #增長數據到隊尾 5 dq.append('c') 6 #增長一組數據到隊尾 7 dq.extend(['d','e']) 8 #增長數據到隊頭 9 dq.appendleft('f') 10 #增長一組數據到隊頭 11 dq.extendleft(['g','h']) 12 #指定位置插入 13 dq.insert(2,'i') 14 #輸出隊列全部數據 15 print(dq) 16 #移除隊尾並返回 17 print(dq.pop()) 18 #移除隊頭並返回 19 print(dq.popleft()) 20 #循環右移2次並返回 21 print(dq.rotate(2)) 22 #循環左移3次並返回 23 print(dq.rotate(-3))