Exception + REMOTE Control Linux

Source: Internet
Author: User
Tags stdin

What is an exception

a=8950/0 Zerodivisioonerror:division by Zero

Print (a)

**************

b = [+]

c = b[2]

Print (b+c) indexerror:list index out of range

When the interpreter encounters an error (unenforceable) code, interrupts the execution of the current code, throws an exception object

Exception capture and handling

Example:

Entering 0 causes the exception of the current program to exit

While True:

num = input (' Input a number:)

Print (' 10000/%s =%s '% (Num,10000.0/int (num)))

Capturing an exception

Keyword Try ... except ...

Try:
b = 4/0

Except Zerodivisioonerror:

Print (' Handle zerodivisioonerror ')

The try code block indicates the scope, and if the code behind the error in the try is no longer executed

Except code block is exception-handling code

Capturing multiple-clock types of errors

Try:

Ohmy

b = 4/0

Except Zerodivisioonerror:

Print (' Handle zerodivisioonerror ')

except Nameerror;

Print (' Handle nameerror ')

Execution Result: Yes Nameerror

Get Exception Object

Exception information after capture to get details

Try

Ohmy

Except Nameerror as E:

Print (' Handle Nameerror: ', E)

E is the exception object

We can print out the specific error messages stored inside.

Catch all exceptions

Try

Ohmy

4/0

Except Exception as E:

Print (' Handle unkown exception: ', E)

Exception indicates all exceptions (parent class)

can be simply written

Try

Ohmy

Except

Print (' Handle unkown exception: ')

If you want to know the exception information

Import Traceback get exception information and line number and code call information for the log file

Try

Ohmy

Except

Print (' Handle unkown exception\n ' +\

Traceback.format_exc ())

Finally statement

Regardless of whether there is an exception, we will execute a piece of code

Try

b = 4/0

Ohmy

Except Zerodivisionerror:

Print (' Handle zerodivisionerror ')

Except Nameerror:

Print (' Handle nameerror ')

Except

Print (' Handle unkown exception ')

Finally

Print (' in finally ')

Finally, be sure to put it in the end for environmental cleanup

else without exception, to execute a piece of code

Try

Print (' Do something ')

Except Zerodivisionerror:

Print (' Handle zerodivisionerror ')

Except Nameerror:

Print (' Handle nameerror ')

Except

Print (' Handle unkown exception ')

Else

Print (' Haha, no exception ')

Finally

Print (' in finally ')

Else must be followed by all except blocks of code

In front of finally

function Call stack

Exception thrown from the call stack

Remote Control Linux

Often dealing with Linux:

Product operating environment, Internet industry: Web server, Web app,mobile APP, Communications Industry: AAA, BOSS, Business control ...

Often used to remotely operate Linux: Automatic installation of products to Linux, some steps of automated use cases, operations: environmental monitoring, automatic data acquisition, analysis

Python solutions: Paramiko, Pexpect

Install Paramiko execute the following command:

Pip Install Paramiko--default-timeout=60

Pip Install Paramiko-i https://pypi.douban.com/simple/

Linux host settings: Guaranteed to have a Linux host: Build their own virtual machine, if not temporarily use the cloud host, to ensure that the SSH service is open, with Putty connection

Sample code

Sshclicent

Import Paramiko

SSH = Paramiko. Sshclient () #创建SSHClient实例对象

Ssh.set_missing_host_key_policy (Paramiko. Autoaddpolicy ()) #调用方法, indicating that there is no public key to store the remote machine, allowing access to

Ssh.connect (HOSTNAME,PORT,USER,PASSWD) #连接远程机器, address, port (typically 22), username, password

Stdin,stdout,stderr = Ssh.exec_command ("mkdir abc;touch file1 file2;ls")

Print (Stdout.read ())

Ssh.close ()

Example

Import Paramiko

SSH = Paramiko. Sshclient () #创建SSHClient实例对象

Ssh.set_missing_host_key_policy (Paramiko. Autoaddpolicy ()) #调用方法, indicating that there is no public key to store the remote machine, allowing access to

Ssh.connect (HOSTNAME,PORT,USER,PASSWD) #连接远程机器, address, port (typically 22), username, password

cmd = ' mkdir abc ' #创建目录

Ssh.exec_command (CMD)

cmd = ' echo ' 1234 #命令跨行

5678

90abc ' >myfile

‘‘‘

Ssh.exec_command (CMD)

cmd = ' Cat myfile ' #获取命令的执行结果

Stdin,stdout,stderr = Ssh.exec_command (cmd)

Print (Stdout.read () +stedrr.read ())

Ssh.close ()

Exec_command each execution will open a new channel execution, the new environment is not in the last execution of the environment, so we can not multiple calls, to achieve the purpose of multiple executions

Can be executed with multiple commands, separated by semicolons

Get Data for analysis

For example, memory usage date +%y%m%d_%h%m%s;free

Transporting documents to remote machines

SFTP = Ssh.open_sftp ()

Sftp.put (' ftp1.py ', '/home/stt/ftp3.py ')

Sftp.close ()

Get Statistics RemoteThe available memory rate for the Linux host. Would you please install Paramiko first?: Execute pip Install Paramiko Please do your own Baidu search, install the virtual Machine Manager VirtualBox or Vmvareplayer, create64-bit virtual machine, installing CentOS image CETOS6.9: http:Mirrors.163.com/centos/6.9/isos/x86_64/centos-6.9-x86_64-bin-dvd1.isoPutty: HTTPS:The.earth.li/~sgtatham/putty/0.70/w32/putty-0.70-installer.msi then write a python program with the code file called memory. py, the code file is scheduled in the remoteThe Linux machine runs. The program does the following things: every5 Seconds to open file/proc/meminfo, the file contains the system memory usage information, the preceding lines are as followsMemtotal:1920648 KBMemfree:87788 KBBuffers:229704 KBCached:1180244 KB MemoryThe. Py program adds the values of Memfree, buffers, cached (the result is the amount of available memory). Then divide byThe value of Memtotal, which is the percentage of available memory (assigned to the variable avamem). The value of Avamem is deposited into the result file ret. txt. The above program runs all the time, every5 Seconds gets the timestamp of the avamem corresponding to the record once, in the following format20170315_12:10:0077%20170315_12:10: 05 74% 20170315_12 :10:10 70< Span class= "Pl-k" >% 20170315_12:10 : 15 72% then write a python program with the code file named Auto.py to the remote machine under the directory, remote in linux host Execute file Memory.py  5 minutes later, the remote file Memory.py execute the resulting file Ret.txt Content copy back to native                
Refer to the answer and turn down































memory.py
# Coding=utf8Import time# memtotal:1920648 KB# memfree:87788 KB# buffers:229704 KB# cached:1180244 KBDefGetContent (Linesfield):For lineIn lines:If fieldIn Line:value= Line.split (‘:‘)[1].split (' KB‘)[0].strip ()Returnint (value)# count is used to count on time to prevent running count=0WhileTrue:count+=1WithOpen'/proc/meminfo‘)As F:beginlines= F.readlines () [:8] Memtotal= GetContent (Beginlines,' Memtotal') Memfree= GetContent (Beginlines,' Memfree') buffers= GetContent (Beginlines,' Buffers') Cached= GetContent (Beginlines,' Cached‘)# Print Memtotal,memfree,buffers,cached# Don't forget * * memusage= (Memfree+ Buffers+ cached)*100.0/memtotal# Search Time Format memusage=‘%s %.2f%%' % (time.strftime ('%y%m%d_%h:%m:%s'), memusage) print (memusage) with Open (' ret.txt',' a') as f:f.write (memusage+'\ n') Time.sleep ( 5) # Prevent running if Count>:         break 
auto.py
# Coding=utf8Import Paramiko,timessh= Paramiko. Sshclient () Ssh.set_missing_host_key_policy (Paramiko. Autoaddpolicy ()) Ssh.connect ("120.26.96.231",22,"STT","stt0707")# Create your own name's directory DirName="Jcy"# first check if a directory with the same name already exists, if not, create stdin, stdout, stderr= Ssh.exec_command ("LS") dircontent= Stdout.read ()Print (dircontent)If DirNameIn Dircontent.splitlines ():Print‘{} already exists'. Format (dirName))ElsePrint' Make Dir{}'. Format (dirName)) Ssh.exec_command ("MkDir{}". Format (DirName))# Transfer Files SFTP= Ssh.open_sftp () sftp.put (' memory.py‘,‘{}/memory.py'. Format (dirName)) Sftp.close ()# Check if the file is transferred successfully, you can check whether the file exists machine, make a function ...# Execute Script# The network connection may be disconnected, given that there is no message for a long time. After searching the internet.# set a parameter to keep the connection transport= Ssh.get_transport () transport.set_keepalive (30)  Print ( "remote exec python memory.py") ssh.exec_ Command ( "CD %s; Python memory.py "% dirName" print ( "wait for the seconds ... 30) # transfer file SFTP = ssh.open_sftp () sftp.get ( ' {}/ret.txt< Span class= "Pl-pds" ". Format (dirName),  ' Ret.txt" Sftp.close () ssh.close ()             

Exception + remote control Linux

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.