Python scans the surviving host

Source: Internet
Author: User
Tags integer division

案例1:简化除法判断案例2:分析apache访问日志案例3:扫描存活主机案例4:利用多线程实现ssh并发访问

1 Case 1: Simplifying Division judgment
1.1 Questions

The main requirements for writing mydiv.py scripts are as follows:

提示用户输入一个数字作为除数如果用户按下Ctrl+C或Ctrl+D则退出程序如果用户输入非数字字符,提示用户应该输入数字如果用户输入0,提示用户0不能作为除数

1.2 Solutions

Using the IF statement to determine if the divisor is appropriate, you need to write multiple statements. With exception handling, can be in line with the first, the wrong to say the logic. The division operation is executed directly in a try statement, which is handled according to the resulting exception.

In addition, CTRL + C or ctrl+d can only be caught by exception.

The syntax for exception trapping is as follows:

try:    Aexcept:    Belse:    Cfinally:    D

Put the statement that could occur in the a inside execution, if there is an exception to execute the B statement, no exception to execute the C statement. The D statement executes regardless of whether an exception occurs.

When catching an exception, you can use multiple except statements, each of which captures an exception, with each exception given a different processing method. You can also put multiple exceptions behind the same except statement, but it is important to note that multiple exceptions are written on the same line, so be sure to enclose them in parentheses and put them into tuples.
1.3 Steps

The implementation of this case needs to follow the steps below.

Step one: Write a script

#!/usr/bin/env pythonimport  syswhile True:    try:        result = 100 / int(raw_input(‘enter a number: ‘))    except (ValueError, ZeroDivisionError), e:   #将异常原因保存在变量e中        print "invalid input:", e        continue    except  (EOFError, KeyboardInterrupt):        sys.exit(1)    breakprint  result

Step two: Test script execution

[[email protected] bin]# ./mydiv.pyenter a number: 0invalid input: integer division or modulo by zeroenter a number: abcinvalid input: invalid literal for int() with base 10: ‘abc‘enter a number: 333

2 Case 2: Analyzing Apache access logs
2.1 Questions

Write scripts for analyzing Apache logs, the main requirements are as follows:

统计每个客户端访问apache服务器的次数将统计信息通过字典的方式显示出来分别统计客户端是Firefox和MSIE的访问次数分别使用函数式编程和面向对象编程的方式实现

2.2 Solutions

Regular expressions are a very powerful tool when it comes to text processing. Match the IP address of the client, you can use the meta-character of the regular expression, and the matching string can directly use the surface meaning of the character.

The entry-level programmer's writing, using the order of the structure, directly written. Although this approach can produce results, the code is difficult to reuse. Refer to step one.

The advanced notation can be programmed in a functional style for later use. Refer to step two.

Finally, you can also use the programming approach of OOP to define a statistical class that takes a regular expression as its Data property. Define a method to search for the number of occurrences of a regular expression from the specified file and deposit it into a dictionary. Refer to step three.
2.3 Steps

The implementation of this case needs to follow the steps below.

Step One: Simple implementation

[[email protected] bin]# vim countweb.py#!/usr/bin/env pythonimport relogfile = ‘/var/log/httpd/access_log‘cDict = {}patt_ip = ‘^\d+\.\d+\.\d+\.\d+‘         #定义匹配IP地址的正则表达式with open(logfile) as f:    for eachLine in f:        m = re.search(patt_ip, eachLine)        if m is not None:            ipaddr = m.group()            #如果IP地址已在字典中,将其值加1,否则初始值设置为1            cDict[ipaddr] = cDict.get(ipaddr, 0) + 1print cDict

Step two: Using functional programming to implement

[[email protected] bin]# vim countweb2.py!/usr/bin/env pythonimport redef countPatt(patt, fname):   #定义可以在指定文件中搜索指定字符串的函数    cDict = {}    with open(fname) as f:        for eachLine in f:            m = re.search(patt, eachLine)            if m is not None:                k = m.group()                cDict[k] = cDict.get(k, 0) + 1    return cDictdef test():    logfile = ‘/var/log/httpd/access_log‘    patt_ip = ‘^\d+\.\d+\.\d+\.\d+‘    print countPatt(patt_ip, logfile)    patt_br = ‘Firefox|MSIE‘    print countPatt(patt_br, logfile)if __name__ == ‘__main__‘:    test()

3 Case 3: scanning the surviving host
3.1 Questions

The main requirements for writing a script to scan a surviving host are as follows:

调用系统的ping命令进行扫描扫描教室环境下所有存活的主机采用多线程的方式编写方案

The system () function of the OS module can invoke the Systems command whose return value is the system command exit code, that is, if the system command executes successfully, returns 0, if not executed successfully, returns a non-0 value.

This example scans the host, can call the System ping command, through the exit code to determine whether to ping the host. If executed sequentially, each ping operation consumes a few seconds, and all 254 addresses require more than 10 minutes. With multi-threading, you can ping the 254 addresses at the same time, and the result is to shorten the execution time to about 10 seconds.
3.2 Steps

The implementation of this case needs to follow the steps below.

Step one: Write a script

[[email protected] bin]# vim mtping.py#!/usr/bin/env pythonimport subprocessimport threadingimport sysdef ping(ip):    result = subprocess.call("ping -c2 %s &> /dev/null" % ip, shell=True)    if result:        print "%s:down" % ip    else:        print "%s:up" % ipif __name__ == ‘__main__‘:    if len(sys.argv) != 2:        print "Usage: %s subnet" % sys.argv[0]        sys.exit(1)    net_list = sys.argv[1].split(‘.‘)    net = ‘.‘.join(net_list[:-1])    ips = ("%s.%s" % (net, i) for i in range(1, 255))    for ip in ips:        t = threading.Thread(target=ping, args=(ip,))        t.start()

Step two: Test script execution

[[email protected] bin]# python mtping.py 172.40.51.0

The script accepts command-line arguments and can ping all IP addresses in the network segment as long as a given network segment is in effect.
4 Case 4: SSH concurrent access with multithreading
4.1 Questions

The main requirements for writing an SSH client script are as follows:

在文件中取出所有远程主机IP地址在shell命令行中接受远程服务器IP地址文件、远程服务器密码以及在远程主机上执行的命令通过多线程实现在所有的远程服务器上并发执行命令方案

The Paramiko module of Python can realize the function of SSH client, and it is easy to use. But when there are so many servers, it can take a lot of time to perform exactly the same simple operations on each server.

Concurrent access can be achieved through SSH plus multi-threading. In order to make the program more flexible, the commands to be executed are provided in the form of positional parameters.
4.2 Steps

The implementation of this case needs to follow the steps below.

Step one: Write a script

[[email protected] bin]# vim remote_comm.py#!/usr/bin/env pythonimport paramikoimport osimport sysimport Threadingdef Remote_comm (host, password, comm): SSH = Paramiko. Sshclient () Ssh.set_missing_host_key_policy (Paramiko. Autoaddpolicy ()) Ssh.connect (host, username= ' root ', Password=password) stdin, stdout, stderr = Ssh.exec_command (comm ) out = Stdout.read () Err = Stderr.read () if Out:print "[%s:out]:%s"% (host, out), if ERR:PR int "%s:error:%s", (host, err), Ssh.close () if __name__ = = ' __main__ ': If Len (sys.argv)! = 4:print "Usage:%        s ipfile password ' comm ' "% sys.argv[0] sys.exit (1) ipfile = sys.argv[1] If not Os.path.isfile (ipfile): Print "No such file:%s"% ipfile sys.exit (2) password = sys.argv[2] Comm = sys.argv[3] with open (ipfile As Fobj:for line in Fobj:ip = Line.strip () t = Threading. Thread (Target=remote_comm, args= (IP, password, comm)) T.sTart () 

Step two: Test script execution

[[email protected] bin]# python remote_comm.py ipaddr.txt tedu.cn ‘useradd bob‘

The script accepts command-line arguments, where Ipaddr.txt is the file that holds all the remote host IP addresses, with one row for each IP address in the file. Tedu.cn is the password for the remote host (all remote host passwords need to be consistent). The final command needs to be written in quotation marks.

After the example executes successfully, a user named Bob is created on all remote hosts.

Python scans the surviving host

Related Article

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.