前言:

测试环境ubuntu18.04
在两台服务器之间安装iperf3

apt install iperf3 -y

放脚本的服务器上必须安装了python3,且安装了paramiko模块

apt install python -y
apt install python3-pip -y
pip3 install paramiko

#代码:

import smtplib,paramiko,os,sys
from email.header import Header
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

hostname = "10.10.30.49"  # 服务器的ip
port = 33001  # 服务器的端口
username = "root"  # 服务器的用户名
password = "%79@b!aqeTDtx"  # 用户名对应的密码

# smtp服务器信息
smtp_server = 'mail.southbaytech.co'
server_port = 25

# 发送方信息
sender = 'cherry_xu@southbaytech.co'
mail_password = 'xxxxxx'

# 收件人地址,列表可发给多人
receivers = ['cherry_xu@southbaytech.co']

if(os.system('ping -c 2 -W 1 %s' %hostname)==0):
    #ssh远程登录目标服务器
    ssh = paramiko.SSHClient()
    policy = paramiko.AutoAddPolicy()
    ssh.set_missing_host_key_policy(policy)
    ssh.connect(
        hostname, #服务器的ip
        port, #服务器的端口
        username, #服务器的用户名
        password #用户名对应的密码
    )
    stdin,stdout,stderr = ssh.exec_command('iperf3 -s -i 2',get_pty=True)
    stdin.close()
    os.system('iperf3 -c %s -u -i 2 -b 200M | tee /tmp/result.txt' %hostname)
    file=open('/tmp/result.txt','r')
    text=file.readlines()
    file.close()

    # 实例化,先添加正文内容
    msg = MIMEMultipart()
    msg.attach(MIMEText('服务器之间的速度测试', 'plain', 'utf-8'))

    # 添加附件1
    att1 = MIMEApplication(open('/tmp/result.txt', 'rb').read(), 'utf-8')
    att1['Content-Disposition'] = 'attachment; filename="result.txt"'  # filename随便起,是接收到的附件显示名称
    # att1["Content-Type"] = 'application/octet-stream'  Content-Type默认为application/octet-stream
    msg.attach(att1)

    # 邮件头信息
    msg['From'] = Header(sender) # 发件人
    msg['To'] = Header(', '.join(receivers)) # 发到哪里,参数为字符串
    msg['Subject'] = Header(text[1]) # 邮件标题

    # 发送邮件的操作
    server=smtplib.SMTP(smtp_server,server_port)
    try:
        server.starttls()
        server.login(sender, mail_password)  # 登录发信邮箱
        server.sendmail(sender, receivers, msg.as_string()) # 发送邮件
        print('邮件发送成功')

    except smtplib.SMTPException:
        print('邮件发送失败')
    ssh.close()
else:
    ping_result = os.popen('ping -c 2 -W 1 %s' % hostname).read()
    # 实例化,先添加正文内容
    msg = MIMEMultipart()
    msg.attach(MIMEText(ping_result, 'plain', 'utf-8'))
    # 邮件头信息
    msg['From'] = Header(sender) # 发件人
    msg['To'] = Header(', '.join(receivers)) # 发到哪里,参数为字符串
    msg['Subject'] = Header('与目标服务器链接失败') # 邮件标题

    # 发送邮件的操作
    server=smtplib.SMTP(smtp_server,server_port)
    try:
        server.starttls()
        server.login(sender, mail_password)  # 登录发信邮箱
        server.sendmail(sender, receivers, msg.as_string()) # 发送邮件
        print('邮件发送成功')

    except smtplib.SMTPException:
        print('邮件发送失败')

#静默执行脚本

nohup python3 new_speed.py > /dev/null 2>&1 &

写入crontab中

vim /etc/crontab
0  8    * * *   root    nohup python3 new_speed.py > /dev/null 2>&1 &