顯示具有 Python3 標籤的文章。 顯示所有文章
顯示具有 Python3 標籤的文章。 顯示所有文章

2025年4月26日 星期六

PrivacyIDEA on Oracle Linux 9 - 500 Internal Server Error on Apache

 相關問題參考:

https://community.privacyidea.org/t/privacyidea-on-debian-12-500-internal-server-error-on-apache/3360/1

透過 Apache log 可看看出目前 mod_wsgi (Web Server Gateway Interface  [Python])的版本為何?

如 Python  3.9 的  wsgi 4.7.1 另 Python 3.12 則為 4.9.4 ,如下 log 所示:

 

Apache/2.4.62 (Oracle Linux Server) OpenSSL/3.2.2 mod_auth_gssapi/1.6.3 mod_wsgi/4.7.1 Python/3.9 configured -- resuming normal operations


Apache/2.4.62 (Oracle Linux Server) OpenSSL/3.2.2 mod_auth_gssapi/1.6.3 mod_wsgi/4.9.4 Python/3.12 configured -- resuming normal operations


相關資訊可以透過 dnf info 取得


[root@Oracle9 conf.modules.d]# dnf info mod_wsgi

Last metadata expiration check: 1:33:33 ago on Sun 27 Apr 2025 10:55:14 AM CST.

Available Packages

Name         : mod_wsgi

Version      : 4.7.1

Release      : 11.el9

Architecture : src

Size         : 705 k

Source       : None

Repository   : ol9_appstream

Summary      : A WSGI interface for Python web applications in Apache

URL          : https://modwsgi.readthedocs.io/

License      : ASL 2.0

Description  : The mod_wsgi adapter is an Apache module that provides a WSGI compliant

             : interface for hosting Python based web applications within Apache. The

             : adapter is written completely in C code against the Apache C runtime and

             : for hosting WSGI applications within Apache has a lower overhead than using

             : existing WSGI adapters for mod_python or CGI.




[root@Oracle9 conf.modules.d]# dnf info python3.12-mod_wsgi

Last metadata expiration check: 1:34:08 ago on Sun 27 Apr 2025 10:55:14 AM CST.

Installed Packages

Name         : python3.12-mod_wsgi

Version      : 4.9.4

Release      : 2.el9

Architecture : x86_64

Size         : 1.1 M

Source       : python3.12-mod_wsgi-4.9.4-2.el9.src.rpm

Repository   : @System

From repo    : ol9_appstream

Summary      : A WSGI interface for Python web applications in Apache

URL          : https://modwsgi.readthedocs.io/

License      : ASL 2.0 and CC-BY

Description  : The mod_wsgi adapter is an Apache module that provides a WSGI compliant

             : interface for hosting Python based web applications within Apache. The

             : adapter is written completely in C code against the Apache C runtime and

             : for hosting WSGI applications within Apache has a lower overhead than using

             : existing WSGI adapters for mod_python or CGI.


指定安裝

# dnf install python3.12-mod_wsgi.x86_64 


切換作業系統所使用的 Python 版本.


[root@Oracle9 conf.modules.d]# alternatives --config python3


There are 2 programs which provide 'python3'.


  Selection    Command

-----------------------------------------------

*+ 1           /usr/bin/python3.12

   2           /usr/bin/python3.11


Enter to keep the current selection[+], or type selection number:



[root@Oracle9 conf.modules.d]# python -V

Python 3.12.5

[root@Oracle9 conf.modules.d]# cat /opt/privacyidea/requirements.txt  | more

#

# This file is autogenerated by pip-compile with Python 3.12

# by the following command:

#

#    pip-compile --allow-unsafe --generate-hashes --output-file=requirements.txt

#

alembic==1.14.1 \

    --hash=sha256:1acdd7a3a478e208b0503cd73614d5e4c6efafa4e73518bb60e4f2846a37b1c5 \

    --hash=sha256:496e888245a53adf1498fcab31713a469c65836f8de76e01399aa1c3e90dd213

    # via flask-migrate

.......


pip install 

[privacyidea@Oracle9 ~]$  pip3 install mod_wsgi
Collecting mod_wsgi
  Using cached mod_wsgi-5.0.2.tar.gz (498 kB)
  Installing build dependencies ... done
  Getting requirements to build wheel ... done
  Preparing metadata (pyproject.toml) ... done
Building wheels for collected packages: mod_wsgi
  Building wheel for mod_wsgi (pyproject.toml) ... done
  Created wheel for mod_wsgi: filename=mod_wsgi-5.0.2-cp312-cp312-linux_x86_64.whl size=743647 sha256=539296f08235beaa861b605ab3957d6a9f06666a2eabb2895cc3b08e02934605
  Stored in directory: /opt/privacyidea/.cache/pip/wheels/20/ff/89/b795934127969d1eb6a9edb07d8fc96f484e45e2b6e2f6736d
Successfully built mod_wsgi
Installing collected packages: mod_wsgi
Successfully installed mod_wsgi-5.0.2


==> mod_wsgi-py312.cpython-312-x86_64-linux-gnu.so


# cp mod_wsgi-py312.cpython-312-x86_64-linux-gnu.so /etc/httpd/modules/

# vi /etc/httpd/conf.modules.d/10-wsgi-python3.conf


[root@Oracle9 httpd]# cat /etc/httpd/conf.modules.d/10-wsgi-python3.conf 

# NOTE: mod_wsgi_python3 can not coexist in the same apache process as

# mod_wsgi (python2).  Only load if mod_wsgi is not already loaded.


<IfModule !wsgi_module>

    #LoadModule wsgi_module modules/mod_wsgi_python3.so

    LoadModule wsgi_module modules/mod_wsgi-py312.cpython-312-x86_64-linux-gnu.so

</IfModule>


Apache log 

=> Apache/2.4.62 (Oracle Linux Server) OpenSSL/3.2.2 mod_auth_gssapi/1.6.3 mod_wsgi/5.0.2 Python/3.12 configured -- resuming normal operations



[root@Oracle9 httpd]# 


PrivacyIDEA  整合 Apache + mod_wsgi 能否正常運行

要確定 Apache 內的 privacyidea.conf 是否正確.  

# vi /etc/httpd/conf.d/privacyidea.conf 

還有   privacyideaapp.wsgi  及 pi.cfg 內容設定及相關權限/目錄等等設定.

[root@Oracle9 conf.d]# vi /etc/privacyidea/privacyideaapp.wsgi 

[root@Oracle9 conf.d]# cat  /etc/privacyidea/privacyideaapp.wsgi 
import sys
sys.stdout = sys.stderr
from privacyidea.app import create_app
application = create_app(config_name="production", config_file="/etc/privacyidea/pi.cfg")

[root@Oracle9 conf.d]# vi /etc/privacyidea/pi.cfg

[root@Oracle9 conf.d]# cat /etc/privacyidea/pi.cfg 
import logging
# The realm, where users are allowed to login as administrators
SUPERUSER_REALM = ['super', 'administrators']
# Your database
SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://pi_user:password@localhost/pi_db'
# This is used to encrypt the auth_token
# This is used to encrypt the admin passwords
# This is used to encrypt the token data and token passwords
PI_ENCFILE = '/etc/privacyidea/enckey'
# This is used to sign the audit log
PI_AUDIT_KEY_PRIVATE = '/etc/privacyidea/private.pem'
PI_AUDIT_KEY_PUBLIC = '/etc/privacyidea/public.pem'
PI_AUDIT_SQL_TRUNCATE = True
# The Class for managing the SQL connection pool
PI_ENGINE_REGISTRY_CLASS = "shared"
PI_AUDIT_POOL_SIZE = 20
#PI_LOGFILE = '/tmp/privacyidea.log'
PI_LOGFILE = '/var/log/privacyidea/privacyidea.log'
PI_LOGLEVEL = logging.INFO
PI_PEPPER = 'v9EW6gt1SGEHgpBQpznTmPtn'
SECRET_KEY = 'BnLflBoiKfc9HOJyFR2agAv9'
[root@Oracle9 conf.d]# 









2024年11月23日 星期六

Try Ansible & AWX with Oracle Linux 9.5

dnf install oracle-epel-release-el9.x86_64 -y 

dnf install ansible.noarch  ansible-core.x86_64  -y 

dnf install dnf-utils zip unzip git gcc gcc-c++ nodejs gettext device-mapper-persistent-data lvm2 bzip2 python3-pip wget  -y 


[root@ol95 ansible]# ansible --version 

ansible [core 2.14.17]

  config file = /etc/ansible/ansible.cfg

  configured module search path = ['/root/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']

  ansible python module location = /usr/lib/python3.9/site-packages/ansible

  ansible collection location = /root/.ansible/collections:/usr/share/ansible/collections

  executable location = /usr/bin/ansible

  python version = 3.9.19 (main, Sep 11 2024, 00:00:00) [GCC 11.5.0 20240719 (Red Hat 11.5.0-2.0.1)] (/usr/bin/python3)

  jinja version = 3.1.2

  libyaml = True

[root@ol95 ansible]# 



[root@ol95 ansible]# pwd

/etc/ansible

[root@ol95 ansible]# ll

total 8

-rw-r--r--. 1 root root  614 Oct 26 08:56 ansible.cfg

-rw-r--r--. 1 root root 1175 Oct 26 08:56 hosts

drwxr-xr-x. 2 root root    6 Oct 26 08:56 roles

[root@ol95 ansible]# 


Server + Node 

useradd devops 

su - devops 

ssh-keygen -t rsa  

cd ~

cd .ssh

cat id_rsa

cat id_rsa.pub


[devops@node1 ~]$ cd .ssh/

[devops@node1 .ssh]$ ll

total 8

-rw------- 1 devops devops 2602 Nov 23 12:09 id_rsa

-rw-r--r-- 1 devops devops  566 Nov 23 12:09 id_rsa.pub

[devops@node1 .ssh]$ vi authorized_keys

[devops@node1 .ssh]$ 


Server

vi /etc/ansible/ansible.cfg 

[defaults]

interpreter_python = auto_silent


vi /etc/ansible/hosts

[node]

node1  ansible_ssh_user=devops ansible_ssh_private_key_file=/home/devops/.ssh/id_rsa ansible_ssh_host=192.168.100.20


test

[root@ol95 installer]#   ansible node --list-host

  hosts (1):

    node1

[root@ol95 installer]# 


 ansible node1 -m ping

 ansible node1 -m shell -a "ip add | grep 192---


vi /etc/ansible/roles/playbook.yml 


- hosts: all

  become: yes


  tasks:


    - name: Install system updates for linux systems

      yum:

        name: '*'

        state: latest

        update_cache: yes.168.100"



[root@ol95 ansible]# ansible-playbook /etc/ansible/roles/playbook.yml 


PLAY [all] *************************************************************************************************************************************************************************************************************


TASK [Gathering Facts] *************************************************************************************************************************************************************************************************

ok: [node1]


TASK [Install system updates for linux systems] ************************************************************************************************************************************************************************

ok: [node1]


PLAY RECAP *************************************************************************************************************************************************************************************************************

node1                      : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   


[root@ol95 ansible]# 


===> Ansible CLI Demo End 

===========================

 ===> Ansible WEB UI Start 


 dnf config-manager --add-repo=https://download.docker.com/linux/centos/docker-ce.repo

 dnf remove -y runc

dnf install -y docker-ce --nobest

systemctl enable docker.service

 systemctl start docker.service

systemctl status docker.service

docker info


[root@ol95 installer]# pwgen -N 1 -s 40

lRE99RGu6rHwjKW7n3gyFHFCLERXc46EFG7ZKPjR

pip install docker

pip install docker-compose

pip install docker==6.1.3

pip install requests==2.31.0



cd /opt

wget https://github.com/ansible/awx/archive/refs/tags/17.1.0.zip

unzip 17.1.0.zip

cd /opt/awx-17.1.0/installer

[root@ol95 installer]# pwd

/opt/awx-17.1.0/installer

[root@ol95 installer]# ll

total 20

-rw-r--r-- 1 root root  172 Mar 10  2021 build.yml

-rw-r--r-- 1 root root  437 Mar 10  2021 install.yml

-rw-r--r-- 1 root root  518 Nov 23 15:30 inventory

drwxr-xr-x 7 root root   99 Mar 10  2021 roles

[root@ol95 installer]# 


vi  inventory

================================

localhost ansible_connection=local ansible_python_interpreter="/usr/bin/env python3"


[all:vars]

dockerhub_base=ansible

awx_task_hostname=awx

awx_web_hostname=awxweb

postgres_data_dir="/opt/myawx/pgdocker"

host_port=80

host_port_ssl=443

docker_compose_dir="/opt/myawx/awxcompose"

pg_username=awx

pg_password=awxpass

pg_database=awx

pg_port=5432

admin_user=admin

admin_password=password

create_preload_data=True

secret_key=lRE99RGu6rHwjKW7n3gyFHFCLERXc46EFG7ZKPjR

awx_official=true

project_data_dir=/opt/myawx/projects


====================

ansible-playbook -i inventory install.yml



docker ps



[root@ol95 ~]#    docker ps

CONTAINER ID   IMAGE                COMMAND                  CREATED       STATUS       PORTS                                     NAMES

6b8175957a67   ansible/awx:17.1.0   "/usr/bin/tini -- /u…"   4 hours ago   Up 2 hours   8052/tcp                                  awx_task

31b242c48f79   ansible/awx:17.1.0   "/usr/bin/tini -- /b…"   4 hours ago   Up 2 hours   0.0.0.0:80->8052/tcp, [::]:80->8052/tcp   awx_web

2b996f3365cf   redis                "docker-entrypoint.s…"   4 hours ago   Up 2 hours   6379/tcp                                  awx_redis

bf8e0975fa68   postgres:12          "docker-entrypoint.s…"   4 hours ago   Up 2 hours   5432/tcp                                  awx_postgres

[root@ol95 ~]# 



docker exec -it awx_task bash


useradd awx 


usermod -aG wheel awx


docker exec -it awx_web bash


useradd awx 


usermod -aG wheel awx



bash-4.4# pwd

/var/lib/awx/projects/update

bash-4.4# ls -la

total 8

drwxr-xr-x 2 awx awx  44 Nov 23 10:29 .

drwxrwxrwx 3 awx awx  20 Nov 23 10:29 ..

-rwxrwxrwx 1 awx awx 172 Nov 23 08:33 playbook.yml

-rwxrwxrwx 1 awx awx 172 Nov 23 09:28 update.yml

bash-4.4# 

bash-4.4# exit
exit
[root@ol95 installer]# netstat -antlp | grep LISTEN
tcp        0      0 127.0.0.1:6010          0.0.0.0:*               LISTEN      5645/sshd: tony.che 
tcp        0      0 127.0.0.1:631           0.0.0.0:*               LISTEN      868/cupsd           
tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN      2335/docker-proxy   
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      869/sshd: /usr/sbin 
tcp        0      0 127.0.0.1:4330          0.0.0.0:*               LISTEN      2010/pmlogger       
tcp        0      0 127.0.0.1:44321         0.0.0.0:*               LISTEN      1277/pmcd           
tcp6       0      0 ::1:631                 :::*                    LISTEN      868/cupsd           
tcp6       0      0 ::1:4330                :::*                    LISTEN      2010/pmlogger       
tcp6       0      0 ::1:6010                :::*                    LISTEN      5645/sshd: tony.che 
tcp6       0      0 :::80                   :::*                    LISTEN      2351/docker-proxy   
tcp6       0      0 :::22                   :::*                    LISTEN      869/sshd: /usr/sbin 
tcp6       0      0 ::1:44321               :::*                    LISTEN      1277/pmcd           
[root@ol95 installer]# 





 














2023年4月29日 星期六

Python Script for Append BanIP Groups form CSV file (FortiGate Firewall)

 Demo

[root@centos7 tmp]# cat test.py 

#!/usr/bin/python3

from netmiko import Netmiko

from csv import DictReader

import time

import os

import csv

os.chdir('/tmp')

csvfile = open('list.csv', 'r')

data = csv.DictReader(csvfile)



fw_01 ={'host':'192.168.100.254',

'username':'admin',

'password':'admin',

'device_type':'fortinet',

}


print(f"connecting to the device")

net_connect = Netmiko(**fw_01)

print("device is connected")


for i in data:

    #print(i['ip'])

    banip=(i['ip'])

    #time.sleep(2)

    print(banip)

    config = ['config firewall address',

         f'edit Ban-{(banip)}',

                 f'set associated-interface port2',

f'set subnet {banip} 255.255.255.255',

                 'next',

         'end'

    ]


    send_config =net_connect.send_config_set(config)

    print(send_config)

    config = ['config firewall addrgrp',

                 f'edit AutoBan',

                 f'append member Ban-{banip}',

                 'next',

                 'end'

    ]

    send_config =net_connect.send_config_set(config)

    print(send_config)


[root@centos7 tmp]# 



====================================



[root@centos7 tmp]# ./test.py

connecting to the device

device is connected

201.189.210.1

config firewall address

FortiGate-VM64 (address) # edit Ban-201.189.210.1

new entry 'Ban-201.189.210.1' added

FortiGate-VM64 (Ban-201.189.210.1) # set associated-interface port2

FortiGate-VM64 (Ban-201.189.210.1) # set subnet 201.189.210.1 255.255.255.255

FortiGate-VM64 (Ban-201.189.210.1) # next

FortiGate-VM64 (address) # end

FortiGate-VM64 # 

config firewall addrgrp

FortiGate-VM64 (addrgrp) # edit AutoBan

FortiGate-VM64 (AutoBan) # append member Ban-201.189.210.1

FortiGate-VM64 (AutoBan) # next

FortiGate-VM64 (addrgrp) # end

FortiGate-VM64 # 

[root@centos7 tmp]# cat list.csv 
ip
201.189.210.1
[root@centos7 tmp]# 



pip3 install netmiko==3.4.0
pip3 install cryptography==3.4.8

Reference

https://www.kareemccie.com/2021/12/python-script-for-creating-address_7.html

2018年7月19日 星期四

line webhook example


webhook.py

#!/bin/python3.6

from flask import Flask, request, abort

from linebot import (
    LineBotApi, WebhookHandler
)
from linebot.exceptions import (
    InvalidSignatureError
)
from linebot.models import (
    MessageEvent, TextMessage, TextSendMessage, ImageSendMessage
)

app = Flask(__name__)

# Channel Access Token
line_bot_api = LineBotApi('XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX=')
# Channel Secret
handler = WebhookHandler('XXXXXXXXXXXXXXXXXXXXX')

@app.route("/callback", methods=['POST'])
def callback():
    # get X-Line-Signature header value
    signature = request.headers['X-Line-Signature']

    # get request body as text
    body = request.get_data(as_text=True)
    app.logger.info("Request body: " +body)

    # handle webhook body
    try:
        handler.handle(body, signature)
    except InvalidSignatureError:
        abort(400)

    return 'OK'



@handler.add(MessageEvent, message=TextMessage)
def handle_message(event):
    message = TextSendMessage(text=event.message.text+" "+event.source.user_id+" ")
    print(message)
    #line_bot_api.reply_message(event.reply_token, message)

import os
if __name__ == "__main__":
    port = int(os.environ.get('PORT', 8888))
    app.run(host='0.0.0.0', port=port)

more example

https://github.com/line/line-bot-sdk-python

Install Python 3.6.X on CentOS 7


Install Python 3.6.X on CentOS 7

=======================================

yum -y install https://centos7.iuscommunity.org/ius-release.rpm
yum -y install python36
yum -y install python36u-devel
yum -y install python36u-libs
yum -y install python36u-pip

pip3.6  install --upgrade pip
pip3.6  install  line-bot-sdk
pip3.6  install  simplejson
pip3.6  install  responses
pip3.6  install  flask

pip3.6 install pyinstaller

=====================================

Python Flask Test

test.py

#!/bin/python3.6

from flask import Flask

app = Flask(__name__)

@app.route("/")
def index():
    return "Hello from FLASK"

if __name__ == "__main__":
    app.run(host='127.0.0.1')

======================================

Apache Proxy Setting

proxy.conf

<VirtualHost *:80>
    <Proxy *>
        Order deny,allow
          Allow from all
    </Proxy>
    ProxyPreserveHost On
    <Location "/test">
          ProxyPass "http:///127.0.0.1:5000"
          ProxyPassReverse "http://127.0.0.1:5000"
    </Location>
</VirtualHost>

===========================================

https://www.pyinstaller.org/

PyInstaller Quickstart
Install PyInstaller from PyPI:

pip install pyinstaller

Go to your program’s directory and run:

pyinstaller yourprogram.py


This will generate the bundle in a subdirectory called dist.

For a more detailed walkthrough, see the manual.