Python automated operation and maintenance 1

[ TOC]

0 x00 Quick Start####

System basic information####

psutil-System Performance Information Module#####

psutil is a cross-platform library used to retrieve information about processes running in Python and system utilization (CPU, memory, disk, network, sensors). Support platform:

Download and use:

pip install psutil
>>> help(psutil)

Use Cases:

#! /usr/bin/env python3
# - *- coding:utf-8-*-
# Function: system basic information module collection
import psutil
import datetime
from subprocess import PIPE

def Memory():
 mem = psutil.virtual_memory()
 swap = psutil.swap_memory()
 total =round(mem.total /pow(1024,3),2)
 free =round(mem.available /pow(1024,3),2)
 use = total - free
 print("System memory information:")print("\tTotal:{1:.2f} {0} \n\tUse:{2:.2f} {0} \n\tFree: {3:.2f} {0} \
   \ n\tMemory usage percentage:{4:.2f}% \n".format("GB",total,use,free,mem.percent))  #Format data
 print("\tswapTotal:{1:.2f} {0} \n\tswapUse:{2:.2f} {0} \n\tswapFree: {3:.2f} {0} \
   \ n\T swap partition usage percentage:{4:.2f}% \n".format("GB",swap.total /pow(1024,3),swap.used /pow(1024,3),swap.free /pow(1024,3),swap.percent))  #Format data

def Cpu():
 cpu = psutil.cpu_times()
 cpucount = psutil.cpu_count()print("System processor information:")print("\tUser:{1:.2f} \n\
  Sysetm:{2:.2f} \n\
  idle: {3:.2f} \n\
  CPU logic number:{4:d} \n\t".format("",cpu.user,cpu.system,cpu.idle,cpucount))  #Format data

def Disk():
 disk = psutil.disk_partitions();
 diskio = psutil.disk_io_counters()print("System disk information:")for i in disk:print(i.device,i.fstype,i.opts,end="\n")
  diskname = psutil.disk_usage(i.device)
  diskvalue =[]for j in diskname:
   diskvalue.append(j)print("Total: {1:.2f}{0} Used: {2:.2f}{0} Free: {3:.2f}{0}100% disk usage:{4:.2f}%\n".format("GB",diskvalue[0]/pow(1024,3),diskvalue[1]/pow(1024,3),diskvalue[2]/pow(1024,3),diskvalue[3]))print("Disk IO information: Read:",diskio.read_count," Read_time: ",diskio.read_time,"\tWrite:",diskio.write_count," Write_time: ",diskio.write_time,"\n")       

def Net():
 ip = psutil.net_if_addrs()
 netio = psutil.net_io_counters()print("System network card information:")for i in ip:print("\t",i,end="\t")for x in ip[i]:print(x.address,end="  ")print("")print("\n\t Bytes_sent : {0:d}  Bytes_recv : {1:d} \n\t packets_sent(Send packet) : {2:d}  packets_recv(Receive packet):{3:d}\n".format(netio.bytes_sent,netio.bytes_recv,netio.packets_sent,netio.packets_recv))
    

def Info():
 users = psutil.users()print("System user information:")for i in users:print("\t",i,end=" ")print("\tSystem on time:",datetime.datetime.fromtimestamp(users[0].started).strftime("%Y-%m-%d %H:%M:%S"))print("\t Start-up time:",datetime.datetime.fromtimestamp(psutil.boot_time()).strftime("%Y-%m-%d %H:%M:%S"),end="\n\n")

def Process():print("System process information:")
 pid = psutil.pids();for pidnum in pid:print("\t",psutil.Process(pidnum).pid,":",psutil.Process(pidnum).name())

# System performance information: memory/ CPU /Disk/The internet/Miscellaneous
def systemPerformance():Cpu()Memory()Disk()Net()Info()Process()
   
 # Popen via psutil()Method to start the application,Can track all relevant information about the program running
 p = psutil.Popen(["python","-c","print('Hello World!')"],stdout=PIPE)print(p)print(p.username(),p.communicate())if __name__ =="__main__":systemPerformance()

System monitoring####

dnspython-domain name polling business monitoring#####

Description: Commonly used DNS resolution is that one domain name corresponds to one IP address, but through DNS polling technology, one domain name corresponds to multiple IPs;

actual case:
[+ View on Github](https://github.com/WeiyiGeek/Study-Promgram/blob/master/Python3/Python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90% E7%BB%B4/dnsmonitorweb.py)

#! /usr/bin/env python
# - *- coding: utf-8-*-
# @ File : dnsmonitorweb.py.py
# @ CreateTime :2019/7/1016:58
# @ Author : WeiyiGeek
# @ Function :Realize DNS domain name polling service monitoring
# @ Software: PyCharm

import dns.resolver
import os
import urllib.request
import ssl

iplist=[]
domain="www.qq.com.cn"

def get_ip(domain=""):try:
  A = dns.resolver.query(domain,'A')
 except Exception as e:print("DNS resolver error : %s "%str(e))return False
 for i in A.response.answer:for j in i.items:if j.address not in iplist:
    iplist.append(j.address)print("DNS A record:%s"%j)return True

def checkweb(ipaddr):
 url ="http://"+ipaddr
 content =""try:
  response = urllib.request.urlopen(url,timeout=5,context=ssl._create_unverified_context())  #Define http link timeout time of 15 seconds,Support https request
 except Exception as e:print("[URL request error]: \n%s"%str(e))finally:print("Request URL:", response.geturl())print("status code:", response.getcode())print("Return message header:\n%s"%response.info())ifint(response.getcode())==200:print(ipaddr +" [alive]")else:print(ipaddr +" [Error]")if __name__ =='__main__':ifget_ip(domain) and len(iplist)>0:for ip in iplist:checkweb(ip)else:print("Monitoring completed")else:print("DNS Resolver Error!")

WeiyiGeek.web example

File comparison####

File content difference comparison#####

(1) difflib module
Description: As a standard library module of Python, difflib is used to compare the differences between files and output the results to HTML documents;

# '- ': In the head is indicated in a sequence, but not included in the second sequence line,When it's at the bottom, it means extra difference;
# '+': At the head is indicated in the two sequences, but not included in the first sequence line
# ' ': The two sequences are identical
# '?': Marks the incremental difference between two sequence lines
# '^': Mark the difference between two sequence lines

Actual case: (this method can be used to compare the differences of linux configuration files)

#! /usr/bin/env python
# - *- coding: utf-8-*-
# @ File : difflibfile.py
# @ CreateTime :2019/7/1117:34
# @ Author : WeiyiGeek
# @ Function :Achieve string comparison between two texts
# @ Software: PyCharm

import difflib

t1 ="""text1
this is a demo!
front not diff file 
add string
"""

t2 ="""text2
this is a demo!
front diff file
del string
"""
    
def main():
 t1line = t1.splitlines()  #Segmented by behavior
 t2line = t2.splitlines()

 # Example 1.Output to the shell
 diff = difflib.Differ()  #Create a Differ object
 result = diff.compare(t1line,t2line)
 # print("\n".join(list(result)))  #Ibid
 for i inlist(result):     #Slowly output results to standard input
  print(i)

 ## Output result##
 # - text1
    # ?^
    #
 # + text2
    # ?^
    #
 # this is a demo!

 # - front not diff file
    # ?-----
    #
 # + front diff file  #There is no incremental difference here
 # - add string
    # ?-^
    #
 # + del string
    # ?^^

 # Example 2.Produce beautiful and contrast HTML documents
 d = difflib.HtmlDiff()withopen("diff.html",'w+')as f:
  f.writelines(d.make_file(t1line,t2line))if __name__ =='__main__':main()

WeiyiGeek.difflib example

(2) filecmp module
Description: filecmp is Python's own module, which can realize the difference comparison function of files/directories/traverse subdirectories;
For example, in the report, the output target directory is more than the original file or subdirectory, even if the file has the same name, it will be judged whether it is the same file (content-level comparison);

Three operation methods of filecmp:

(1) Single file comparison: filecmp.cmp(f1,f2[,shallow]) #Compare f1,Are f2 files the same True/Fasle
 - shallow: The default is True, which means not based on os.stat()The method returns the basic information of the file for comparison and judgment such as access and modification time,If Fasle is based on(2)Multi-file comparison: filecmp.cmp(dir1,dir2,common[,shallow]) #Compare the files in the two directories and return three lists which are match, mismatch and error
- common :The list indicates the files to be compared[f1,f2,f3,f4]-Matching contains a list of matched files, otherwise it does not match. The error list represents a list of files that do not exist in the directory and the file list that cannot be compared due to permissions.

[ dir1]
ee38a408f20702ccc05fb39a04ee251c  f1
1139929 d8855ced585631c0e3fe8ad8d  f2
c35957891d72c0c32b53a01911224e13  f3

[ dir2]
ee38a408f20702ccc05fb39a04ee251c  f1
9939929 d8855ced625631c0e3fe8ad8d  f2
c35957891d72c0c32b53a01911224e13  f4

# Results of the(['f1'],['f2'],['f3'])(3)Directory comparison: dircmp(a,b[,ignore [,hide]]) #Create a directory comparison object, supporting recursion will show the matching files including files in the a directory and subdirectories where ab exists
- ignore :File name ignore list['RCS',cvs,'tags']- hide :Hide list default[os.curdir,os.pardir]
# python -c "import os;print (os.curdir,os.pardir)"
# ('.','..')

Supplementary note:

actual case:

#! /usr/bin/env python
# - *- coding: utf-8-*-
# @ File : filedircmp.py
# @ CreateTime :2019/7/1210:21
# @ Author : WeiyiGeek
# @ Function :file/Comparison between directories
# @ Software: PyCharm

import filecmp
import pprint

file1 ="./diff.html"
file2 ="./difflibfile.py"
dir1 ="../"
dir2 ="../../"

def main():
 # Example 1.File comparison is different
 print("Are the files the same:%s"%str(filecmp.cmp(file1,file2,False)))print("Are the files the same:%s"%str(filecmp.cmp(file1,file2,True)))

 # Example 2.Realize directory difference comparison function
 # Compare the contents of the current specified directory
 dirobj = filecmp.dircmp(dir1,dir2,['diff.html']) #Directory comparison, ignore test.py file
 print("\n[*]  report ")
 dirobj.report()

 # Compare the contents of the current specified directory and the first-level subdirectory
 print("\n[*]  report partial closure ")
 dirobj.report_partial_closure()

 # Recursively compare the contents of all specified directories
 print("\n[*]  report full closure ")
 dirobj.report_full_closure()

 # For other attributes of the dircmp class, refer to the above
 print("dircmp class left_list attributes:"+str(dirobj.left_list))print("dircmp class left_only attribute:")
 pprint.pprint(dirobj.left_only)if __name__ =='__main__':main()

# Supplementary results:
dircmp class left_list attributes:['.gitignore','.idea','Day1','Day2','Day3','Day4','Day5','Day6','Day7','Python security platform construction','Python automated operation and maintenance']
dircmp class left_only attribute:
['. gitignore','.idea','Day1','Day2','Day3','Day4','Day5','Day6','Day7','Python security platform construction','Python automated operation and maintenance']

WeiyiGeek.filecmp example

Message sending

Email sending

smtplib send email module
Description: SMTP (Simple Mail Transfer Protocol) is a simple transfer protocol, which is a set of rules for mail transfer from source address to destination address.

② smtplib module: responsible for sending mail

# Instantiate object SMTP
SMTP = smtplib.SMTP(host='', port=0, local_hostname=None,[timeout,]source_address=None)   #Initialization returns a non-SSL smtp object default port 25
SMTP =  smtplib.SMTP_SSL(host='', port=0, local_hostname=None, keyfile=None, certfile=None,[timeout,]context=None, source_address=None) #Return an SSLsmtp object, default port 465

LMTP = smtplib.LMTP(host='', port=LMTP_PORT, local_hostname=None, source_address=None) #The LMTP protocol is very similar to ESMTP and is mainly based on a standard SMTP client.

# Exception thrown
exception smtplib.SMTPException  #A subclass of OSError, it is the base exception class for all other exceptions provided by this module.

exception smtplib.SMTPServerDisconnected  #This exception is thrown when the server accidentally disconnects, or when trying to use it before connecting the SMTP instance to the server.

exception smtplib.SMTPResponseException  #The base class for all exceptions containing SMTP error codes. These exceptions are generated when the SMTP server returns an error code.
# The error code is stored in the wrong smtp_In the code attribute, smtp_The error attribute is set to the error message.

exception smtplib.SMTPSenderRefused  #The sender address was rejected. In addition to the attributes set by all SMTPResponseException exceptions,' sender 'Set to the string rejected by the SMTP server.

exception smtplib.SMTPRecipientsRefused #All recipient addresses are rejected. The error of each recipient can be accessed through the attribute recipient. The attribute recipient is the same as the SMTP.sendmail()The returned dictionaries are in exactly the same order.

exception smtplib.SMTPDataError  #The SMTP server refused to accept the message data.

exception smtplib.SMTPConnectError  #An error occurred while establishing a connection with the server.
exception smtplib.SMTPAuthenticationError   #Error when establishing authentication with server

exception smtplib.SMTPHeloError  #The server rejected our HELO message.
exception smtplib.SMTPNotSupportedError  #The server does not support the command or option attempted.

# SMTP representative object
SMTP.connect(host='localhost', port=0)  #When the initialization is not set up host and default port=It needs to be set at 25. It is very common to use Unix sockets in LMTP, so our connect()Method must support this
SMTP.helo(name='') #Use HELO to identify yourself to the SMTP server. The hostname parameter defaults to the fully qualified domain name of the local host. The message returned by the server is stored as the helo of the object_resp attribute.
SMTP.ehlo(name='') #Use EHLO to identify yourself to the ESMTP server. The hostname parameter defaults to the fully qualified domain name of the local host.
SMTP.login(user, password,*, initial_response_ok=True)  #Log in to the SMTP server that requires authentication. The parameters are the username and password to be authenticated, and an exception is returned if it is wrong
SMTP.auth(mechanism, authobject,*, initial_response_ok=True) #For a list of supported authentication methods, see auth()
SMTP.starttls(keyfile=None, certfile=None, context=None) #Put SMTP connection in TLS(Transport layer security)mode. All subsequent smtpcommands will be encrypted. Then ehlo should be called again() 
SMTP.sendmail(from_addr, to_addrs, msg, mail_options=(), rcpt_options=())  #Mailing,msg can be a string containing characters in the ASCII range, or a byte string
SMTP.send_message(msg, from_addr=None, to_addrs=None, mail_options=(), rcpt_options=()) #This is calling sendmail()A convenient way to use email.The message represented by message. If from_addr is None or to_addrs is None, the address in msg will be extracted
SMTP.set_debuglevel(level)  #Set debug output level 1/true/2(In version 3.0add)
SMTP.quit() #Terminate the SMTP session and close the connection
SMTP.close()
# Customize personalized mail format method
•email.message  #Mail structure
 - email.message.EmailMessage()  #Return the object msg, construct the sending text and store it in the array
•email.parser  #Parse mail information

•email.mime #Create email and MIME objects from scratch(Support HTML)- email.mime.text.MIMEText(""" HTML """,_subtype='plain', _charset=None,*, policy=compat32)  #HTML/subtype:Text type(plain or html)/Character Encoding
 - email.mime.multipart.MIMEMultipart(_subtype='mixed', boundary=None, _subparts=None,*, policy=compat32,**_params) #Generate a MIME object containing multiple parts of the mail body,Three subtypes of subtype: mixed)(Message body with attachment),related(Build the embedded resource mail body),alternative(Construct a mail body in which plain text and hypertext coexist);- email.mime.audio.MIMEAudio(_audiodata, _subtype=None, _encoder=email.encoders.encode_base64,*, policy=compat32,**_params) #Create a message body containing audio data, audiodata raw binary audio data byte string;
 email.mime.image.MIMEImage(_imagedata, _subtype=None, _encoder=email.encoders.encode_base64,*, policy=compat32,**_params) #Create a message body containing image data, imagedata, a byte string of raw binary image data;

Module example:

# Example 1.The SMTP class supports the with statement. When you exit after this use, the SMTP QUIT command will be issued automatically (yes, to determine whether the connection is normal)
>>> with smtplib.SMTP("smtp.qq.com",25)as smtp: 
 smtp.noop()  #Port 25 non-SSL
 smtp.helo('[email protected]')(250, b'Ok')(250, b'smtp.qq.com')>>>with smtplib.SMTP_SSL("smtp.qq.com",465)as smtp:  
 smtp.noop()  #465 port SSL
 smtp.helo('[email protected]')(250, b'Ok')(250, b'smtp.qq.com')

# Exception thrown and helo identifies itself
>>> try:
 smtp = smtplib.SMTP("smtp.sina.com",25)
 smtp.helo('[email protected]')
 smtp.ehlo("[email protected]")
 smtp.quit('flag') 

except smtplib.SMTPException as connect:print("+ [ Error ]:"+connect)(250, b'smtp-5-123.smtpsmail.fmail.xd.sinanode.com')(221, b'smtp-5-123.smtpsmail.fmail.xd.sinanode.com')(250, b'smtp.sina.com\nPIPELINING\nSIZE 73400320\nSTARTTLS\nAUTH LOGIN PLAIN\nAUTH=LOGIN\nMAILCOMPRESS\n8BITMIME')

# Login and exception thrown
>>> smtp = smtplib.SMTP("smtp.qq.com",25)>>>try:
 res = smtp.login('[email protected]','itfbbfqxnbhda')print(res)
except smtplib.SMTPException as test:print("Error:"+str(test))
# Authentication is successful(235, b'Authentication successful')  

# Exception thrown
>>> smtp = smtplib.SMTP("smtp.qq.com",25)>>>try:
 res = smtp.login('[email protected]','itfbbfqxnbhda')print(res)
except smtplib.SMTPException as test:print("Error:"+str(test))

Error:(535, b'Error: \xc7\xeb\xca\xb9\xd3\xc3\xca\xda\xc8\xa8\xc2\xeb\xb5\xc7\xc2\xbc\xa1\xa3\xcf\xea\xc7\xe9\xc7\xeb\xbf\xb4: http://service.mail.qq.com/cgi-bin/help?subtype=1&&id=28&&no=1001256')

# Certification process
# SMTP(host,port)-> login
# SMTP()->connect(host,port)->ehlo('[email protected]')-> login
>>> smtp = smtplib.SMTP("smtp.qq.com",25)>>>try:
 res = smtp.login('[email protected]','iocztfbbfqxnbhda')print(res)
 smtp.close()
 smtp.connect("smtp.qq.com",25)
 smtp.ehlo("[email protected]")
 res = smtp.login('[email protected]','iocztfbbfqxnbhda')print(res)
except smtplib.SMTPException as test:print("Error:"+str(test))(235, b'Authentication successful')(220, b'smtp.qq.com Esmtp QQ Mail Server')(250, b'smtp.qq.com\nPIPELINING\nSIZE 73400320\nSTARTTLS\nAUTH LOGIN PLAIN\nAUTH=LOGIN\nMAILCOMPRESS\n8BITMIME')(235, b'Authentication successful')

Email sending example

import smtplib
from email.message import EmailMessage
msg =EmailMessage()
msg['Subject']='Login Smtp Succeeful'
msg['From']='WeiyiGEEK'
msg['To']='[email protected]'
msg.set_content("Test connection server(1)")
smtp = smtplib.SMTP("smtp.qq.com",25)try:
 res = smtp.login('WeiyiGEEK','iocztfbbfqxnbhda') 
 smtp.send_message(msg)print(res)
 smtp.close()
except smtplib.SMTPException as test:print("Error:"+str(test))

Actual case (1) Sending of text HTML information:

#! /usr/bin/env python
# - *- coding: utf-8-*-
# @ File : stmpDemo.py
# @ CreateTime :2019/7/2616:17
# @ Author : WeiyiGeek
# @ Function :Realize the sending of mail
# @ Software: PyCharm

import smtplib
import socket
from email.mime.text import MIMEText

SMTPHOST ="smtp.qq.com"
SMTPUSER =""
SMTPPASS ="jxgovvrd"
FROM =""
TO =""
Subject ="Test smtplib sending module"

def info():
 # Get computer name
 hostname = socket.gethostname()
 # Get local IP
 ip = socket.gethostbyname(hostname)return hostname + ip

def sendmail(From,To,boby):try:
  # server = smtplib.SMTP() #Create an SMTP object
  # server = smtplib.connect(SMTPHOST,"25") #Connect to the smtp host in non-SSL mode
  server = smtplib.SMTP_SSL(SMTPHOST)     #Connecting to the smtp host via SSL method uses port 465 by default
  # server.starttls()  #Enable secure transfer mode
  server.login(SMTPUSER, SMTPPASS)  #Account email verification
  server.sendmail(From, To, boby)
  server.quit()print("Successful! dindong")
 except Exception as e:print("[Failed to send]!:"+str(e))

def main():
 Content =info()+"\r\n I am a computer technology enthusiast, I am learning Python operation and maintenance"
 msg =MIMEText("""
 # Create a MIMEtext object and insert HTML content separately/Types of/text/Character Encoding,
 < table width="400" border="1px solid red"><th>No. 1</th><th>No. 2</th><tr><td>Host name</td><td>IP address</td><tr></table>"""+Content, "HTML" ,"UTF-8") #Assemble the main content of sendmail

 msg['Subject']= Subject  #Must be placed after MIMEText
 msg['From']= FROM
 msg['To']= TO
 sendmail(FROM, TO, msg.as_string())if __name__ =='__main__':main()

WeiyiGeek. Sending test

Practical case (2) Picture format and attachment file sending:

#! /usr/bin/env python
# - *- coding: utf-8-*-
# @ File : stmplibsimple3.py
# @ CreateTime :2019/7/3016:07
# @ Author : WeiyiGeek
# @ Function :Send screenshots and send emails in attachment format
# @ Software: PyCharm

import smtplib,os
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from PIL import ImageGrab

SMTPHOST ="smtp.qq.com"
SMTPUSER ="[email protected]"
SMTPPASS ="iocztfbbfqxnbhda"
SUBJECT = u"Screen shot sending and attachment format email sending test"
FROM = SMTPUSER
TO ="[email protected]"

def captrue():
 img = ImageGrab.grab(bbox=(0,0,1141,610))
 img.save('captrue.jpg','JPEG')
 os.system("ipconfig > ip.txt")

def addimg(src, imgid):"""
 Add picture and iD to mimeiMAGE object
 : param src:Picture path
 : param imgid:Picture id
 : return:Back to imgImage object
    """
 withopen(src,'rb')as img:
  msgimage =MIMEImage(img.read())  #Create a MIMEImage object to read the image content as a parameter
  msgimage.add_header('Content-ID', imgid) #Specify the content of the image file-ID,Used in img tag
  return msgimage  #Return MIMEImage object

def addacc():
 # Create a MIMEText object to attach the document to the email
 attach =MIMEText(open('./ip.txt','r').read(),"plain","utf-8")
 attach["Context-type"]="text/plain"  #Specify file type
 attach["Content-Disposition"]="attachment; filename='ip.txt'"  #Set download dialog
 return attach

def sendmain(msg):try:
  server = smtplib.SMTP_SSL(SMTPHOST)
  server.login(SMTPUSER, SMTPPASS)
  server.sendmail(FROM, TO, msg.as_string())
  server.quit()print("Mail sent successfully")
 except Exception as err:print("Failed to send:"+str(err))

def emailContent():
 message =MIMEMultipart('related')  #Create a MIMEutilpart object and use related to define the message body of the embedded resource
 msgtext =MIMEText("""
  < font color=red>Official website business attachment</font><table border="0" cellspacing="0" cellpadding="2"><tr bgcolor="#CECFAD" height="20" style="front-size:14px"><td colspan="2">System screenshot image sent by email</td></tr><tr><td><a href="www.weiyigeek.github.io"><img src="cid:captrue" alt="Python screenshot"></a></td></tr></table>""",'html','utf-8')  #The picture of the img tag is through Content-Referenced by ID
 message.attach(msgtext)
 message.attach(addimg("./captrue.jpg","captrue"))
 message.attach(addacc())
 message['Subject']= SUBJECT
 message['From']= FROM
 message['To']= TO
 sendmain(message)  #Mailing

def main():captrue()  #Screenshot
 emailContent() #Mail structure

if __name__ =='__main__':main()

WeiyiGeek. Send pictures and documents by email

# See also:
Module smtplib :SMTP(Simple Mail Transport Protocol) client
Module poplib :POP(Post Office Protocol) client
Module imaplib :IMAP(Internet Message Access Protocol) client
Module nntplib :NNTP(Net News Transport Protocol) client
Module mailboxTools :A tool for creating, reading, and managing message collections on disk using various standard formats.
Module smtpd  : SMTP server framework(primarily useful for testing)
 test environment

On the client.jaylin.Send mail on com:

# telnet mail.jaylin.com 25

Trying 192.168.1.9...

Connected to mail.jaylin.com(192.168.1.9).

Escape character is '^]'.220 mail.jaylin.com ESMTP Sendmail 8.13.8/8.13.8; Wed,21 Oct 200905:12:41+0800

EHLO mail.jaylin.com

250- mail.jaylin.com Hello [192.168.1.7], pleased to meet you

250- ENHANCEDSTATUSCODES

250- PIPELINING

250- 8 BITMIME

250- SIZE

250- DSN

250- ETRN

250- DELIVERBY

250 HELP

MAIL FROM:[email protected]2502.1.0[email protected] Sender ok

RCPT TO:[email protected]2502.1.5[email protected] Recipient ok

DATA

354 Enter mail, end with"." on a line by itself

SUBJECT xinxin

lala~.2502.0.0 n9KLCfJo004052 Message accepted for delivery

quit

2212.0.0 mail.jaylin.com closing connection

Connection closed by foreign host.

On the client.xin.Receive mail on com:# telnet mail.xin.com 110

Trying 192.168.2.11...

Connected to mail.xin.com(192.168.2.11).

Escape character is '^]'.+OK Dovecot ready.

User xin

+ OK

Pass ******+OK Logged in.

List

+ OK 12 messages:162126243619461956206841783987579738107371174212740.

retr 12+OK 740 octets

Return-Path:<[email protected]>

Received:from smarthost.jaylin.com(smarthost.jaylin.co [192.168.1.6](may be forged))

  by mail.xin.com(8.13.8/8.13.8)with ESMTP id n9KLDC2H004460

  for<[email protected]>; Wed,21 Oct 200905:13:12+0800

Received:from mail.jaylin.com(mail.jaylin.com [192.168.1.9])

  by smarthost.jaylin.com(8.13.8/8.13.8)with ESMTP id n9KLD7VC006062

  for<[email protected]>; Wed,21 Oct 200905:13:07+0800

Received:from mail.jaylin.com([192.168.1.7])

  by mail.jaylin.com(8.13.8/8.13.8)with ESMTP id n9KLCfJo004052

  for[email protected]; Wed,21 Oct 200905:12:54+0800

Date: Wed,21 Oct 200905:12:41+0800

From:[email protected]

Message-Id:<[email protected]>

 

SUBJECT xinxin

lala~.

quit

+ OK Logging out.

Connection closed by foreign host.

 

 

In order to verify that Smarthost is effective, let&#39;s check the three Sendmail servers/var/log/maillog log file.

Sender mail.jaylin.com:

Oct 2105:13:02 mail sendmail[4052]: n9KLCfJo004052:[email protected], size=21,class=0, nrcpts=1, msgid=<[email protected]>, proto=ESMTP, daemon=MTA, relay=[192.168.1.7]

Oct 2105:13:02 mail sendmail[4054]: n9KLCfJo004052:[email protected],[email protected](501/501), delay=00:00:08, xdelay=00:00:00, mailer=relay, pri=120021, relay=smarthost.jaylin.com [192.168.1.6], dsn=2.0.0, stat=Sent(n9KLD7VC006062 Message accepted for delivery)

Smarthost as Smarthost.jaylin.com:

Oct 2105:13:07 client1 sendmail[6062]: n9KLD7VC006062:from=<[email protected]>, size=304,class=0, nrcpts=1, msgid=<[email protected]>, proto=ESMTP, daemon=MTA, relay=mail.jaylin.com [192.168.1.9]

Oct 2105:13:07 client1 sendmail[6064]: n9KLD7VC006062: to=<[email protected]>, delay=00:00:00, xdelay=00:00:00, mailer=esmtp, pri=120304, relay=mail.xin.com.[192.168.2.11], dsn=2.0.0, stat=Sent(n9KLDC2H004460 Message accepted for delivery)

Recipient mail.xin.com:

Oct 2105:13:12 mail sendmail[4460]: n9KLDC2H004460:from=<[email protected]>, size=489,class=0, nrcpts=1, msgid=<[email protected]>, proto=ESMTP, daemon=MTA, relay=smarthost.jaylin.co [192.168.1.6](may be forged)

Oct 2105:13:12 mail sendmail[4461]: n9KLDC2H004460: to=<[email protected]>, delay=00:00:00, xdelay=00:00:00, mailer=local, pri=30702, dsn=2.0.0, stat=Sent

Oct 2105:13:35 mail dovecot: pop3-login: Login: user=<xin>, method=PLAIN, rip=::ffff:192.168.2.8, lip=::ffff:192.168.2.11

Oct 2105:13:41 mail dovecot:POP3(xin): Disconnected: Logged out top=0/0, retr=1/756, del=0/12, size=8497

Recommended Posts

Python automated operation and maintenance 2
Python automated operation and maintenance 1
Python file operation
Python and Go
python operation kafka
Python file and directory operation code summary
Linux overview of Python automated operation and maintenance and the ultimate guide to virtual machine installation and use
Python introspection and reflection
[python] python2 and python3 under ubuntu
Python operation yaml instructions
Python deconstruction and packaging
Python3 configuration and entry.md
Python introduction and environment installation
Python operation Excel merge cells
Python know crawler and anti crawler
centos7 install python3 and ipython
Centos 6.10 reinstall python and yum
Python open read and write
CentOS7 install python3 and pip3
Python data structure and algorithm
Python multi-process and multi-thread basics
CentOS 6.9 compile and install python
Quick start Python file operation
CentOS 6 compile and install python 3
Generators and iterators in Python
Python file read and write operations
Python and js interactive call method
Magic methods and uses of Python
Python judges positive and negative numbers
python ftp upload files and folders
Python crawler | Cognitive crawler request and response
CentOS7 installation and maintenance of Gitlab
Python implements string and number splicing
Python list comprehension operation example summary
Python file operation basic process analysis
Python function definition and parameter explanation
Implementation of python selenium operation cookie
CentOS quickly install Python3 and pip3
Mongodb and python interaction of python crawler
Install Python3 and ansible under CentOS8
Python processing PDF and CDF examples
Played with stocks and learned Python
Configure python3 environment on centos7 and
Some examples of python operation redis
Python reads and writes json files
Example operation of python access Alipay
Python implements username and password verification
Install Python3 and Py under CentOS7
The operation of python access hdfs
Python handles operation code to execl
Python basic syntax and number types
Python learning os module and usage