python 远程服务器获取服务器资源并在服务器异常时自动邮件通知

  • Paramiko 

Paramiko利用Python C扩展进行了低级加密(Cryptography),但它本身是围绕SSH网络概念的纯Python接口。它包含了SSHClientTransport两种连接方式。如果需要在远程服务器上进行文件传输等操作时,使用Transport连接

class ssh_connect():

    def __init__(self, info):
        """
        初始化SSH并连接
        Arguments
            info {list} -- 远程服务器信息【服务器ip, 用户名, 端口(int), 密码】
        """
        ip, user, port, password = info
        self.ssh = paramiko.SSHClient()
        self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        self.ssh.connect(hostname=ip, port=port, username=user, password=password)

    def command(self, ucommand):
        """
        执行命令语句
        Arguments
            ucommand {str} -- 命令语句
        """
        stdin, stdout, stderr = self.ssh.exec_command(ucommand)
        res, err = stdout.read(), stderr.read()
        result = res if res else err
        return result.decode()
  • yagmail

yagmail是一个python实现自动发送邮件的库。自动发送功能需要先开启邮箱的SMTP服务。

class Mail:

    def __init__(self, email, password):
        """
        初始化邮箱/类似登录
        Arguments:
            email {str} -- 发送者邮箱
            password {str} -- 邮箱的授权码
        """
        self.email = email
        self.password = password
        self.yag = yagmail.SMTP(
            host='smtp.qq.com', user=self.email,
            password=self.password, smtp_ssl=True
        )

    def sendmail(self, msg, title, receivers):
        """
        发送邮件
        Arguments:
            msg {str} -- 邮件正文
            title {str} -- 邮件标题
            receivers {list} -- 邮件接收者,数组
        """

        try:
            self.yag.send(receivers, title, msg)
            print("邮件发送成功")

        except BaseException as e:
            print(e)
            print("Error: 无法发送邮件")

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值