各位大神好,本人初入python,对一些原理和概念了解不够。目前遇到一个问题,但查不出原因在哪,请各位大神帮忙:
我简单写了一个python的程序,目的是监测VPN的连接状态,当VPN出现中断时,就发送邮件。代码如下:
import smtplib #smtp服务器
from email.mime.text import MIMEText #邮件文本
import os
import os.path
import time
from subprocess import run
import time
import socket
def CurrentTime(): #获取当前时间并格式化
t = time.gmtime()
Time = time.strftime("%Y-%m-%d %H:%M:%S",t)
return Time
def email(content): #定义发送邮件
subject = "Connection Status"
body = content
sender = "test1234@163.com"#发送方
receiver = "test1234@163.com"#接收方
password = "TESTEMAILADDRESS" #授权码
message = MIMEText(content,"plain","utf-8")
#content 发送内容 "plain"文本格式 utf-8 编码格式
message['Subject'] = subject #邮件标题
message['To'] = receiver #收件人
message['From'] = sender #发件人
smtp = smtplib.SMTP_SSL("smtp.163.com",994) #实例化smtp服务器
smtp.login(sender,password)#发件人登录
smtp.sendmail(sender,[receiver],message.as_string()) #as_string 对 message 的消息进行了封装
smtp.close()
def ping(command): #定义ping某一固定的IP地址,具体IP地址在主函数中定义
ping = run(command,shell=True)
if ping.returncode == 0:
content = "VPN Connected"
time.sleep(1)
else:
content = "VPN Disconnected"
return content
def GetIPAddr():
hostname = socket.gethostname()
ipaddr = socket.gethostbyname(hostname)
return ipaddr
def Writelog(file): #将主函数执行结果写日志
f = open("log.txt","a+")
f.write("VPN Connection Status:"+file+'\n')
f.close()
def main():
while True:
command = "ping 10.215.48.1"
PING_RESULT = ping(command)
if PING_RESULT == "VPN Disconnected":
content = PING_RESULT+'\n'+CurrentTime()+'\n'+GetIPAddr()
email(content)
print(content)
Writelog(content)
else:
content = PING_RESULT+'\n'+CurrentTime()+'\n'+GetIPAddr()
print(content)
Writelog(content)
main()
Python程序的版本是3.7.3,然后我用Pyinstaller对程序进行打包,Pyinstaller的版本是3.6,但是打包好的程序执行不正常,While True的循环不被执行……有各位大神知道是怎么回事吗?好多代码都是粘的,缺乏基础知识,如有指点,感激涕零!