First, the Python Learning Fortress Machine instance
Paramiko Module
1. Installation
1) Find the scripts directory under python3.5
2) Open cmd, switch to Scripts directory
3) Execute Pip3.5.exe install Paramiko
(If an error occurs, perform pip install--upgrade Pip and then re-execute step 3)
After execution 3) installation is complete
2. Verify that the installation is successful
Enter the python mode under CMD, enter import Paramiko, if there is no error, the execution succeeds
3. Example
1) sshclient
Role: Used to connect to a remote server and execute basic commands
Two ways to connect:
1, based on the user name password connection:
Import Paramiko
# Create an SSH object
SSH = Paramiko. Sshclient ()
# Allow connections to hosts that are not in the Know_hosts file
Ssh.set_missing_host_key_policy (Paramiko. Autoaddpolicy ()) First login must add this sentence, or it will be an error
# Connection Server
Ssh.connect (hostname= ' c1.salt.com ', port=22, username= ' Wupeiqi ', password= ' 123 ')
# Execute Command
stdin, stdout, stderr = Ssh.exec_command (' df ')
# Get command results
result = Stdout.read ()
# Close Connection
Ssh.close ()
SSH Package 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. Public-key-based connections
Benefit: You can avoid entering a user name and password by using the public key connection, the two machines are connected directly
Note: Do not send the private key to someone else
Import Paramiko
Private_key = Paramiko. Rsakey.from_private_key_file ('/home/auto/.ssh/id_rsa ')
# Create an SSH object
SSH = Paramiko. Sshclient ()
# Allow connections to hosts that are not in the Know_hosts file
Ssh.set_missing_host_key_policy (Paramiko. Autoaddpolicy ())
# Connection Server
Ssh.connect (hostname= ' c1.salt.com ', port=22, username= ' Wupeiqi ', Key=private_key)
# Execute Command
stdin, stdout, stderr = Ssh.exec_command (' df ')
# Get command results
result = Stdout.read ()
# Close Connection
Ssh.close ()
SSH Package 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
Function: Used to connect to remote server and perform upload and download
1, based on the user name password upload download:
Import Paramiko
Transport = Paramiko. Transport (' hostname ', 22)
Transport.connect (username= ' Wupeiqi ', password= ' 123 ')
SFTP = Paramiko. Sftpclient.from_transport (transport)
# upload location.py to the server/tmp/test.py
Sftp.put ('/tmp/location.py ', '/tmp/test.py ')
# download Remove_path to local Local_path
Sftp.get (' Remove_path ', ' Local_path ')
Transport.close ()
2. Public key-based upload and download
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)
# upload location.py to the server/tmp/test.py
Sftp.put ('/tmp/location.py ', '/tmp/test.py ')
# download Remove_path to local Local_path
Sftp.get (' Remove_path ', ' Local_path ')
Transport.close ()
ii. the process and thread of Python learning
1. Threads
1) definition
A thread is the smallest unit that the operating system can perform operations on. It is included in the process and is the actual operating unit of the process. A thread refers to a single sequential control flow in a process in which multiple threads can be concurrently, each thread performing different tasks in parallel
2) Python treading module
Python treading modules are called in two ways:
1. Call directly
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. Inherited calls
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 (daemon thread)
Feature: When the main thread is finished, it stops immediately regardless of whether the daemon is executed
#_ *_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线程, which is the daemon thread for the main thread of the program, and when the main thread exits, the M threads exit, and other sub-threads initiated by M exit at the same time, regardless of whether the task is completed or not
M.start ()
M.join (timeout=2)
Print ("---main thread done----")
4. Thread lock (mutex mutex)
Function: When multiple threads operate on the same common data, in order to prevent multiple threads from operating concurrently on the same piece of data, the thread lock is used, and when one thread finishes working on the data, the other continues to manipulate the data.
Import time
Import threading
Def addnum ():
Global Num #在每个线程中都获取这个全局变量
Print ('--get num: ', num)
Time.sleep (1)
Lock.acquire () #修改数据前加锁
Num-=1 #对此公共变量进行-1 operation
Lock.release () #修改后释放
num = #设定一个共享变量
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 (Recursive lock)
Implementation: Add several small locks in a large lock
importthreading,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)6.Semaphore (semaphore)
role: Can allow a certain number of threads to change data
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)
2. Process
Definition: A process is the provision of all resources for the execution of a program
Beginner Python's Day9