前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >0基础上手python、PHP编程,域自助服务台,具备第三方APP提醒,自助改密解锁等功能

0基础上手python、PHP编程,域自助服务台,具备第三方APP提醒,自助改密解锁等功能

作者头像
王忘杰
发布2023-08-21 19:41:38
2081
发布2023-08-21 19:41:38
举报
文章被收录于专栏:王忘杰的小屋

王工自研域自助服务台架构图,具备长期未改密企业微信提醒、自助改密解锁等功能 全面对标宁盾微软AD自助修改密码解决方案 https://www.nington.com/solution-adpassword/ 每年可为公司节省5W-10W元

说明 王工域控为windows2022,Self Service Password搭建在OracleLinux8上,python版本为python3最新版本,PHP为OracleLinux8默认源中的PHP7

预览 通知改密

自助改密

架构解析: 1、域控上域账户维护pager属性(寻呼机),修改为企业微信ID 2、域控运行扫描脚本,通过计算上次修改密码时间,超过指定日期,进行企业微信提醒;如果未维护pager属性,写入日志 3、Self Service Password域控自助服务台二次开发,改为企业微信接收验证码改密 4、进行企业微信提醒时,先查询redis缓存,如果access_token不存在,则获取一次,如果存在,直接使用,缓存5400秒自动过期。 5、建立企业微信应用,可参考我的zabbix文章

搭建前提 1、已维护域控pager属性为企业微信userid,此信息需要企业微信管理员后台查询。 2、已正确部署Self Service Password,可以看我之前的文章。 3、已部署redis,建议使用docker部署,一定要设置redis密码 4、已为php增加php-redis扩展

docker一键部署redis 红帽系系统默认为podman替代docker

代码语言:javascript
复制
podman pull redis
podman run --restart=always -p 6379:6379 --name myredis -d redis  --requirepass passwd@123

扫描脚本: 扫描脚本同样有两部分组成,第一部分是powershell脚本,用于获取域用户信息 可指定OU、可自定义要获取的用户属性,生成的文件放在C盘根目录下1.txt,与python脚本对应 adgetuser.ps1

代码语言:javascript
复制
Get-ADUser -Filter 'Name -like "*"' -SearchBase "OU=测试组,OU=用户OU,DC=90apt,DC=com" -Properties * | Select-Object name,passwordlastset,pager > c:/1.txt

运行结果

代码语言:javascript
复制

name   passwordlastset     pager      
----   ---------------     -----      
王忘杰1   2023/5/18 16:39:05  WangWangJie1     
王忘杰2 2022/9/26 16:50:41  WangWangJie2

第二部分是扫描通知脚本,由主python文件和配置文件ad.config组成,运行后生成errlog.txt日志文件 ad.config

属性说明 corpid: appsecret: agentid: content:内容1 content1:内容2 content2:内容3 admin:闲置属性 ip:redis地址 port:redis端口 passwd:redis密码 passwddate:密码多少天未修改进行提醒

代码语言:javascript
复制
{
"corpid" : "xxxx",
"appsecret" : "xxxx",
"agentid" : "xxxx",
"content" : "亲爱的 ",
"content1" : " 域用户 :\n您的计算机域账户已经超过 ",
"content2" : " 天没有修改密码了(电脑登录密码),请您立即更改。\n重置密码过程请遵循以下原则:\n○密码长度最少 8 位;\n○密码中不可出现公司和本人中英文拼写\n○密码符合复杂性需求(大写字母、小写字母、数字和符号四种中必须有三种)\n操作方式:\n您可以通过 自助密码服务台http://xx/修改密码,在公司内网中,手机、笔记本、台式机均可访问",
"admin" : "xxxx",
"ip" : "xxxx",
"port" : "xxxx",
"passwd" : "xxxx",
"passwddate" : xx
}

主python文件

代码语言:javascript
复制
import requests,json,redis,time,logging
from datetime import datetime, timedelta

def get_weixintoken():
   #获取微信token
   token_url = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=' + config[0] + '&corpsecret=' + config[1]
   req = requests.get(token_url)
   accesstoken = req.json()['access_token']
   return accesstoken

def get_redistoken():
   readredis = redis.Redis(connection_pool=redis.ConnectionPool(host=config[7],port=config[8],password=config[9],decode_responses=True))
   if readredis.get('key') == None:
      readredis.set('key', get_weixintoken(),ex=5400)
      return (readredis.get('key'))
   else:
      return readredis.get('key')

def post_weixin(userweixin,content):
   body = {
      "touser": userweixin,
      "msgtype": "text",
      "agentid": config[2],
      "text": {
         "content": content
      }
   }
   postweixin = requests.post(
      'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token='+get_redistoken(),data=json.dumps(body))
   return(postweixin.text)

def get_config():
   config = json.loads(open("ad.config", encoding='utf-8').read())
   return [config['corpid'],config['appsecret'],config['agentid'],config['content'],config['content1'],config['content2'],config['admin'],config['ip'],config['port'],config['passwd'],config['passwddate']]

def user_check():
   f = open("C:\\1.txt", "r", encoding='utf-16')
   lines = f.readlines()
   f = open('errlog.txt', 'w')
   for line in lines:
      try:
         x = line.replace("/", "-")
         y = x.split()
         time_1 = y[1]
         time_2 = time.strftime("%Y-%m-%d", time.localtime())
         time_1_struct = datetime.strptime(time_1, "%Y-%m-%d")
         time_2_struct = datetime.strptime(time_2, "%Y-%m-%d")
         day = (time_2_struct - time_1_struct).days
         userweixin = y[3]
         username= y[0]
         if day > config[10]:
            day = str(day)
            time.sleep(1)
            try:
               post = post_weixin(userweixin,config[3]+username+config[4]+day+config[5])
               postjson=json.loads(post)
               if postjson['errmsg'] != "ok":
                  f.write("发送失败,可能微信号错误 " + userweixin+"\n")

            except :
               None

         else:
            None
      except:
         f.write("没有微信号 "+ line)
   f.close()



config = get_config()
#post_weixin()
user_check()

脚本使用 编译为EXE文件,和ad.config,放在域控服务器通过定时任务运行即可。

Self Service Password企业微信脚本 项目目录/usr/share/self-service-password/ 配置文件/usr/share/self-service-password/conf/config.inc.local.php 配置文件中修改短信通知方式

代码语言:javascript
复制
## SMS
# Use sms
$use_sms = true;
# SMS method (mail, api)
$sms_method = "api";
$sms_api_lib = "lib/weixin.inc.php";
# GSM number attribute
$sms_attributes = array( "pager" );

编写企业微信通知脚本 /usr/share/self-service-password/lib/weixin.inc.php

代码语言:javascript
复制
<?php
//连接本地的 Redis 服务
function get_token(){
        $redis = new Redis();
        $redis->connect('修改用自己的IP地址', 修改用自己的端口);
        $redis->auth('修改用自己的redis密码');
        $key = $redis->get("key");
        if ($key)
        {
                return $key;
        }
        else
        {
                $url='https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=修改用自己的&corpsecret=修改用自己的';
                $jsondb = file_get_contents($url);
                $jsondb = json_decode($jsondb, true);
                $key = $jsondb['access_token'];
                $redis->set("key", $key);
                $redis->expire("key", 5400);
                return $key;
        }
}

function send_sms_by_api($mobile, $message) {
        $postdata = array(
    'touser' => "$mobile",
    'msgtype' => 'text',
    'agentid' => '修改用自己的',
        'text' => array(
        'content' => "$message"
        )

        );

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, 'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=' . get_token());
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postdata));
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $errmsg = json_decode(curl_exec($ch))->errmsg;
        if ($errmsg=="ok")
        {
                return 1;
        }
        else
        {
                return 0;
        }


}

?>

修改中文显示 比如把短信修改成企业微信,可直接修改语言文件

代码语言:javascript
复制
/usr/share/self-service-password/lang/zh-CN.inc.php

PHP安装redis扩展 https://www.vvave.net/archives/how-to-install-php-pecl-redis-on-centos8-official-repo-php.html

总结 简单

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2023-06-11,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 王忘杰的小屋 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
云数据库 Redis
腾讯云数据库 Redis(TencentDB for Redis)是腾讯云打造的兼容 Redis 协议的缓存和存储服务。丰富的数据结构能帮助您完成不同类型的业务场景开发。支持主从热备,提供自动容灾切换、数据备份、故障迁移、实例监控、在线扩容、数据回档等全套的数据库服务。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档