2024年7月31日水曜日

RockyLinux9 インストール後の各種設定 2024/07/31

https://korodes.com/rockyl9-1_02/参照


1.SELinuxの無効化

まず、SELinuxを無効化します。SELnuxはLinuxの監査やセキュリティを向上させる機能ですが、有効になっているとサービスの動作や、設定内容にかなりの制限が出てきます。そのため、基本的には無効にする場合が多いのが実情です。

SELinuxの動作モード

Enforcing : SELinux機能は有効でアクセス制御も有効

Permissive : SElinuxはwarningを出すが、アクセス制限は行われません

disabled : SElinux機能・アクセス制御ともに無効


①現在のSELinuxの状態


# getenforce

Enforcing

②[permissive]モードへの切り替え


# setenforce 0

# getenforce

Permissive

③[enforcing]モードへの切り替え


# setenforce 1

# getenforce

Enforcing

④SELinux を完全に無効化する場合は、以下のようにカーネルコマンドラインに selinux=0 を追加して再起動が必要です。


# grubby --update-kernel ALL --args selinux=0

# reboot

※ SELinux 有効に戻す場合は以下 (変更後は再起動)


# grubby --update-kernel ALL --remove-args selinux

# rebbot


2.システムの最新化

OSインストール直後にはできるだけ早期にパッケージのアップデートを行います。

しかし、dnf updateを行うと、カーネルアップデートも同時に行われます。

カーネルアップデートを行うと、システムの再起動やサービスの停止が必要だったり、最悪カーネルパニックが発生して、システムが起動しない場合があります。カーネルを除外してアップデートする方が賢明です。

dnf -y updateの後ろに「--exclude=kernel*」を指定して実行することでカーネルをアップデート対象から除外することできます。


# dnf -y update --exclude=kernel*

3.セキュリティ対策のため停止するサービス

# systemctl stop atd.service

# systemctl disable atd.service

# systemctl stop kdump.service

# systemctl disable kdump.service

# systemctl stop lvm2-monitor.service

# systemctl disable lvm2-monitor.service

# systemctl stop mdmonitor.service

# systemctl disable mdmonitor.service

# systemctl stop smartd.service

# systemctl disable smartd.service

# systemctl stop dm-event.socket

# systemctl disable dm-event.socket



4.リポジトリーの追加

4.1 EPEL repository を追加

# dnf config-manager --set-enabled crb

# dnf -y install epel-release

# vi /etc/yum.repos.d/epel.repo

[epel]

name=Extra Packages for Enterprise Linux $releasever - $basearch

# It is much more secure to use the metalink, but if you wish to use a local mirror

# place its address here.

#baseurl=https://download.example/pub/epel/$releasever/Everything/$basearch/

metalink=https://mirrors.fedoraproject.org/metalink?repo=epel-$releasever&arch=$basearch&infra=$infra&content=$contentdir

enabled=1    ← リポジトリー有効(0 : リポジトリー無効)

priority=10 ← 優先度を1~99の範囲で指定

gpgcheck=1

countme=1

gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-$releasever

 

[epel-debuginfo]

name=Extra Packages for Enterprise Linux $releasever - $basearch - Debug

# It is much more secure to use the metalink, but if you wish to use a local mirror

4.2 Remi's RPM repository を追加

# dnf -y install https://rpms.remirepo.net/enterprise/remi-release-9.rpm

# dnf -y config-manager --set-enabled remi

# vi /etc/yum.repos.d/remi-safe.repo

# This repository is safe to use with RHEL/CentOS base repository

# it only provides additional packages for the PHP stack

# all dependencies are in base repository or in EPEL

 

[remi-safe]

name=Safe Remi's RPM repository for Enterprise Linux 9 - $basearch

#baseurl=http://rpms.remirepo.net/enterprise/9/safe/$basearch/

#mirrorlist=https://rpms.remirepo.net/enterprise/9/safe/$basearch/httpsmirror

mirrorlist=http://cdn.remirepo.net/enterprise/9/safe/$basearch/mirror

enabled=1      ← リポジトリー有効(0 : リポジトリー無効)

priority=10    ← 優先度を1~99の範囲で指定

gpgcheck=1

repo_gpgcheck=1

gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-remi.el9

 

[remi-safe-debuginfo]

name=Remi's RPM repository for Enterprise Linux 9 - $basearch - debuginfo

baseurl=http://rpms.remirepo.net/enterprise/9/debug-remi/$basearch/


5.ネットワークの設定(コマンドラインで設定)


#下記のパッケージをインストルする。Rocky Linuxには入ってない!! )

# dnf install NetworkManager-wifi


5.1 ネットワークデバイス名の確認

# nmcli dev s

ens33   ethernet  connected  ens33

lo      loopback  unmanaged  --

ネットワークデバイス名は「ens33」と分かります


5.2 ホスト名の変更

試しにホスト名をLepardに変更します


# hostnamectl set-hostname Lepard

 

再度ログインする

[huong@Lepard:~]$


5.3 固定IPv4アドレス設定

5.1よりネットワークインターフェースの名称は「ens33」である

Rockylinux8.xではnetwork-scriptsにあったifcfg-xxxファイルを書き換えて変更できましたが、Rockylinux9.xではディレクトリーの中身は空でありこの方法は使えませんので、「nmcli」コマンドで変更します。

固定IPv4アドレスを「192.168.11.83」に変更します。

「nmcli」コマンドで変更


# 固定 IPv4 アドレス設定

# nmcli connection modify ens33 ipv4.addresses 192.168.11.83/24

 

# ゲートウェイ設定

# nmcli connection modify ens33 ipv4.gateway 192.168.11.1

 

# 参照する DNS 設定

# nmcli connection modify ens33 ipv4.dns 192.168.11.1

 

# DNS サーチベース 設定 (自身のドメイン名)

# nmcli connection modify ens33 ipv4.dns-search rocky.korodes.com

 

# IP アドレス固定割り当てに設定

# nmcli connection modify ens33 ipv4.method manual

 

# インターフェースを再起動して設定を反映

# nmcli connection down ens33; nmcli connection up ens33

Connection 'ens33' successfully deactivated (D-Bus active path: /org/freedesktop/NetworkManager/ActiveConnection/1)

Connection successfully activated (D-Bus active path: /org/freedesktop/NetworkManager/ActiveConnection/2)



6.ネットワークの設定(GUIで設定)

6.1 固定IPアドレス設定

OSインストール時にデフォルトの DHCP による IP アドレス取得の設定になっている場合は、必要に応じてネットワークの設定を変更し固定IPアドレスにします。今回はネットワークインターフェースの名称「ens33」である。固定IPv4アドレスを「192.168.11.83」に変更します

下記コマンドを実行します

# nmtui

<OK>をクリック


<Edit...>をクリック


下記項目に入力する


[Tab]キーで最下欄まで移動し、<OK>をクリック



6.2 ホスト名の変更

試しにホスト名をLepardに変更します

[NetworkManager TUI]の最初の画面に戻り[Set system hostname]を選択し、<OK>をクリック


[Hostname]に入力し、<OK>をクリック


7.Vimの設定

①Vimのインストール

# dnf -y install vim-enhanced

②Vimの適用と反映

# vi ~/.bashrc

# 最終行にエイリアス追記

alias vi='vim'

# source ~/.bashrc

③ユーザー固有環境として Vim の設定

# vi ~/.vimrc

" vim の独自拡張機能を使用 (vi との互換性無し)

set nocompatible

" 文字コードを指定

set encoding=utf-8

" ファイルエンコードを指定 (先頭から順に成功するまで読み込む)

set fileencodings=utf-8,iso-2022-jp,sjis,euc-jp

" 自動認識させる改行コードを指定

set fileformats=unix,dos

" バックアップを取得

set backup

" バックアップを取得するディレクトリを指定

set backupdir=~/backup

" 検索履歴を残す世代数

set history=50

" 検索時に大文字小文字を区別しない

set ignorecase

" 検索語に大文字を混ぜると検索時に大文字を区別する

set smartcase

" 検索語にマッチした単語をハイライト

set hlsearch

" インクリメンタルサーチを使用

set incsearch

" 行番号を表示

set number

" 改行 ( $ ) やタブ ( ^I ) を可視化

set list

" 括弧入力時に対応する括弧を強調

set showmatch

" ファイルの末尾に改行を入れない

set binary noeol

" 自動インデントを有効にする

set autoindent

" 構文ごとに色分け表示

syntax on

" syntax on の場合のコメント文の色を変更

highlight Comment ctermfg=LightCyan

" ウィンドウ幅で行を折り返す

set wrap



2024年7月26日金曜日

Rocky LinuxでのminiPC NucBox5(CPU-N100)のWiFi設定メモ 2024/07/26投稿

要点

・RockyLinux(最小構成)には「NetworkManager-wifi」がインストールされていない場合はインストールする。

・EthenetとWiFiはIPアドレスが別々なのでWiFiのIPアドレスで接続する。


RedHatDocumentationの「nmcli を使用した WiFi ネットワークへの接続」を参照

https://docs.redhat.com/ja/documentation/red_hat_enterprise_linux/9/html/configuring_and_managing_networking/proc_connecting-to-a-wifi-network-by-using-nmcli_assembly_managing-wifi-connections


#下記のパッケージをインストルする。( Rocky Linuxには入ってない!! )

# dnf install NetworkManager-wifi


nmcli ユーティリティーを使用して、wifi ネットワークに接続できます。初めてネットワークに接続しようとすると、ユーティリティーは NetworkManager 接続プロファイルを自動的に作成します。ネットワークに静的 IP アドレスなどの追加設定が必要な場合は、プロファイルが自動的に作成された後にプロファイルを変更できます。


前提条件


ホストに wifi デバイスがインストールされている。

ハードウェアスイッチがある場合は、wifi デバイスが有効になっている。

手順


NetworkManager で wifi 無線が無効になっている場合は、この機能を有効にします。


# nmcli radio wifi on

オプション: 利用可能な wifi ネットワークを表示します。


# nmcli device wifi list

IN-USE  BSSID              SSID          MODE   CHAN  RATE        SIGNAL  BARS  SECURITY

        00:53:00:2F:3B:08  Office        Infra  44    270 Mbit/s  57      ▂▄▆_  WPA2 WPA3

        00:53:00:15:03:BF  --            Infra  1     130 Mbit/s  48      ▂▄__  WPA2 WPA3

サービスセット識別子 (SSID) 列には、ネットワークの名前が含まれています。列に -- が表示されている場合、このネットワークのアクセスポイントは SSID をブロードキャストしていません。


wifi ネットワークに接続します。

[ Office ]はSSID名

# nmcli device wifi connect Office --ask

Password: wifi-password

対話的に入力するのではなく、コマンドでパスワードを設定する場合は、コマンドで --ask の代わりに password wifi-password オプションを使用します。


# nmcli device wifi connect Office wifi-password

ネットワークが静的 IP アドレスを必要とする場合、NetworkManager はこの時点で接続のアクティブ化に失敗することに注意してください。後の手順で IP アドレスを設定できます。


ネットワークに静的 IP アドレスが必要な場合:


IPv4 アドレス設定を設定します。次に例を示します。


(IPv4アドレスを手動で設定)

[ wifi0 ]はnmtuiでWiFi名(WI-FI ooooo)をwifi0に変更しておくwlp1s0では接続できない

nmcli connection modify wifi0 ipv4.method manual ipv4.addresses 192.168.112.45/24
nmcli connection modify wifi0 ipv4.gateway 192.168.112.1
nmcli connection up wifi0


# nmcli connection modify Office ipv4.method manual ipv4.addresses 192.0.2.1/24 ipv4.gateway 192.0.2.254 ipv4.dns 192.0.2.200 ipv4.dns-search example.com


IPv6 アドレス設定を設定します。次に例を示します。

# nmcli connection modify Office ipv6.method manual ipv6.addresses 2001:db8:1::1/64 ipv6.gateway 2001:db8:1::fffe ipv6.dns 2001:db8:1::ffbb ipv6.dns-search example.com


接続を再度有効にします。

# nmcli connection up Office

検証


アクティブな接続を表示します。

# nmcli connection show --active

NAME    ID                                    TYPE  DEVICE

Office  2501eb7e-7b16-4dc6-97ef-7cc460139a58  wifi  wlp0s20f3

作成した wifi 接続が出力にリストされている場合、その接続はアクティブです。


EthenetとWiFiはIPアドレスが別々なのでWiFiのIPアドレスで接続する。

ホスト名または IP アドレスに ping を実行します。


# ping -c 3 example.com

2019年10月28日月曜日

[ Lazarus SQLite3 使用方法 ]

[ Lazarus SQLite3 使用方法 ]

①SQLite3.dllをダウンロードする。
 https://sqlite.org/download.html
 Windows用のプリコンパイル済みバイナリから
 SQLiteバージョン3.30.1用の64ビットDLL(x64)
 sqlite-dll-win64-x64-3300100.zip(ファイル名はバージョンで異なる)
 解凍後に「SQLite3.dll」をプロジェクトのフォルダに置くかLazarusの
 PATHの通ったフォルダに置く。

②TSQLiteConnectionコンポーネント
③TSQLTransactionコンポーネント
④TSQLQueryコンポーネント
をフォーム上にドラッグ&ドロップすると
uses節に必要なものが追加される。

⑤TSQLiteConnectionのプロパティの設定
 DataBaseName = (例:c:\LazarusProject\Sample\)
 […]をクリックしてdbファイルを選択する。

⑥TSQLTransactionのプロパティの設定
 Database = TSQLiteConnectionを選択

⑦TSQLQueryのプロパティの設定
 Database = TSQLiteConnectionを選択
 Transaction = TSQLTransactionを選択


[ サンプルコード ]
procedure TForm1.SpeedButton1Click(Sender: TObject);
var
str, str2: string;
begin
  SQLiteConnection1.Close;
  SQLiteConnection1.Open;
  SQLTransaction1.active := true;
  SQLQuery1.SQL.Clear;
  SQLQuery1.SQL.Text := 'select * from sample.db;';
  SQLQuery1.Open;
  SQLTransaction1.Commit;
  str := Query.FieldByName('company').AsString;
  str2 := Query.FieldByName('address').AsString;

 ShowMessage(str + #13#10 + str2);

 SQLQuery1.Close;
end; 


procedure TForm1.OnDestroy;
begin
 SQLQuery1.Free;
 SQLTransaction1.Free;
 SQLiteConnection1.Close;
 SQLiteConnection1.Free;
end;



2016年5月14日土曜日

Fedora23 のデスクトップにアイコンを表示する方法

fedora 23 のデスクトップにアイコンを表示する方法

fedora23 はランチャーを表示してからアプリを選択しなければならないので不便です。
ファイルアプリケーションの「他の場所」で /usr/share/applications でアプリケーション一覧を表示させ、目的のアプリケーションを選択し「コピー」してデスクトップで「貼り付け」


fedora 23 アイコンのサイズ変更方法

fedora 23 のデフォルトのアイコンはデカイので
アイコンをマウス右ボタンをクリックし「アイコンのサイズ変更」を選択し、アイコンを直接ドラッグしてサイズを変更できます。


fedora 23 ターミナル等への貼り付け

インターネットブラウザで見つけた、設定コマンドをコピペで実行できます。

例えば下記様な長いコマンドを入力する場合に便利です。

# dnf install zlib-devel bzip2 bzip2-devel readline-devel sqlite sqlite-devel openssl-devel


shift + ctrl + v で貼り付け


- 2016/05/14 -

Fedora23 desktop & server 設定メモ


ferora23 desktop・server 設定メモ 

2016/05/16

※表示が戻れる
コマンド | less
例 semanege port -l | less

***** SELINUXを停める *********************************
setenforce 0

vi /etc/sysconfig/selinux
SELINUX=disabled


***** アップデーをする *******************************
dnf update


***** ユーザーにグループを追加する *******************
usermod -G postgres ooooo


***** ooo.cof をnarikyoフォルダにバックアップする ****

***** ホスト名を変更する *****************************
hostname server.gr.jp 一時的に更新
hostnamectl set-hostname server.gr.jp 恒久的に更新
hostnamectl 確認

**** Rubyをインストールする **************************
dnf install ruby


***** samba ユーザー&パスワード *********************
pdbedit -a user_name


***** 自動起動の設定 *********************************
ntsysv
    postgresql
    smb
    nma
    vsftp
    httpd


***** ファイヤーウォールの設定 ***********************
firewall-cmd --add-service=postgresql
firewall-cmd --permanent --add-service=postgresql

firewall-cmd --add-service=samba
firewall-cmd --permanent --add-service=samba

firewall-cmd --add-service=http
firewall-cmd --permanent --add-service=http

== https ssl ==
firewall-cmd --add-service=https
firewall-cmd --permanent --add-service=https

firewall-cmd --add-service=ftp
firewall-cmd --permanent --add-service=ftp


***** サーバー名の設定 ****************************
hostnamectl set-hostname name
vi /etc/hostname
 server

/etc/hosts は設定不要

***** sambaの設定 *********************************
コピーする
cp /etc/samba/smb.conf /etc/samba/smb.org

vi /etc/samba/smb.conf
 hosts allow = 127. 192.168.11. 最後のドットを忘れるな!!!!!
 workgroup = WORKGROUP

 netbios name = は不要
 wins support = は不要

systemctl restart smb
systemctl restart nmb


===== postgresql ================================
initdb
postgresql.conf
autovacuum = offにする

pg_hba.conf
systemctl restart postgresql


===== httpd (apache) ============================
コピーする
cp /etc/httpd/conf/httpd.conf /etc/httpd/conf/httpd.org

vi /etc/httpd/conf/httpd.conf
 <Directory "/var/www/cgi-bin">
  Options ExecCGI


 <IfModule mime_module>
  AddHandler cgi-script .cgi .rb .py #コメントアウトする

systemctl restart httpd


===== インターネット接続テスト =================
wget http://119.245.204.69/__CONNECT__


===== 検索 =====================================
find / -name syslog.conf

===== vsftp ====================================
コピーする
cp /etc/vsftpd/vsftpd.conf /etc/vsftpd/vsftpd.org

===== メモリ =====================================
free

===== HDD ======================================
df -h
fdisk -l

===== Postgresqlログ =============================
/var/log/pgsql/    場所
/var/lib/pgsql/data/pg_log/

パラメータ名            おすすめの値
log_destination            'stderr' または 'csv' (ver8.2~)
redirect_stderr (~ver8.2)
logging_collector (ver8.3~)    'on'
log_directory            'pg_log' or '/var/log/pgsql' など
log_filename            'postgresql-%Y-%m-%d_%H%M.log'など
log_line_prefix            '[%t][%p][%u][%d] 'など
log_rotation_age        '1d'または'1440' (1日単位で切り替え)
log_rotation_size        1ログファイルの許容サイズ(大きくても数百MB)
log_min_error_statement        error



===== HDD パーテッション =======================
LVM (Logical Volume Manager)論理ボリューム
/(root)        10GB
/boot        500MB
/boot/EFI    200MB
/home        10GB
swap        16GB    メモリ×2倍

===== journal ==================================
journaldが収集したログの確認方法

journalctl -b ブートログ

・すべてのログをlessにパイプして閲覧
# journalctl

・lessがいらないとき(-lをつけないと画面の右端でカットされる。)
# journalctl -l --no-pager

・特定サービスのログだけ見るとき
# journalctl -u hoge.service

・メタデータを含めて全部見たいとき
# journalctl -u hoge.service -o json-pretty

・tail -f コマンドっぽく、ログの新規出力を観察したいとき
# journalctl -f

====== Atom インストール ===============================
Atomのホームページからダウンロード
Dounload.rpm

dnf install lsb-core-noarch
rpm -ivh /ダウンロードフォルダ/atom.x86_64.rpm


===== chrombook ubuntu install =========================
①[esc]キーと[f3]に相当するキー[再読み込みキー]を押しながら電源を入れます。
②矢印キーで日本語表示に変更できます。

③この状態で[Ctrl] + [D]キーを押すとデベロッパーモードへの移行がはじまります。

④確認機能をオフにするにはEnterキーを押してください。
⑤ローカルデータは消去されます。」と表示されますので[Enter]キーを押します。
⑥Chromeブラウザを起動してアドレスバーに「https://goo.gl/fd3zc」を入力しEnterを押します

⑦次に[Ctrl] + [Alt] + [T] キーを押してターミナル画面を表示します。

⑧crosh > Shell
⑨chronos@localhost / $ sudo sh ~/Downloads/crouton -r trusty -t unity-desktop

tオプション

-t xfce (Xubuntu)
-t lxde (Lubuntu)

⑩chronos@localhost / $ sudo startunity
⑩chronos@localhost / $ sudo startxfce

===== ファイル操作 =================================
ファイル削除
rm -rf /home/oooo

===== 日本語 =======================================
echo $LANG
vi /etc/locale.conf
source /etc/locale.conf
dnf install ibus-mozc
reboot
vi /usr/share/ibus/component/mozc.xml

<layout>default</layout>
下記のように書き換える
<layout>jp</layout>
半角・全角で入力切り替え


===== wifi =========================================
dnf install NetworkManager-wifi

rebootする

dmesg | grep iwlwifi
nmcli device wifi connect marochan_net5 password ooooooooooo

lspci
nmcli device wifi list
nmcli general status
nmcli general logging
nmcli connection show
iwconfig
systemctl restart wpa_supplicant.service
ls /usr/lib/firmware/
nmcli radio wifi on
===== bash履歴 =====================================
vi ~/.bash_history

===== ターミナルでのコピペ =========================
Linux Gnome-terminal

Copy Ctrl + Insert
Paste Shift + Ctrl + v


===== python =======================================
.pyc作成
python -m compileall foo.py

===== pyenv =====
※開発環境インストール
# dnf groupinstall "Development Tools"
# dnf install zlib-devel bzip2 bzip2-devel readline-devel sqlite sqlite-devel openssl-devel

※pyenvインストール
$ git clone https://github.com/yyuu/pyenv.git ~/.pyenv

$ vi ~/.bash_profile

export PYENV_ROOT=$HOME/.pyenv
export PATH=$PYENV_ROOT/bin:$PATH
eval "$(pyenv init -)"

source ~/.bash_profile # すぐに認識させる。

$ pyenv install list

$ pyenv install 3.5.1
$ pyenv install 2.7.11

$ pyenv versions

== バージョン切り替え ==
python --version
Python 2.7.3

$ pyenv shell 2.7.9
$ python --version
Python 2.7.9

$ pyenv shell 3.5.0
$ python --version
Python 3.5.0

$ pyenv shell system
$ python --version
Python 2.7.3

== バージョンを戻す ==
$ pyenv shell system

2016年5月10日火曜日

Python ftps ダウンロードと圧縮と暗号化のメモ

python ftps ダウンロードと圧縮と暗号化のメモ

netからexampleを参考に書いてみました。

ftps TLS接続しダウンロード ー> zip -> 暗号化します。

復号化は最後のコードを参考に作成してみてください。


※エラー処理は適当なので付け加えてください。
##### source code ##########################################
# coding: utf-8

from ftplib import FTP_TLS
import os
import sys
import getpass  # パスワード入力用
import termios  # Yes or No 入力用
import tty      # Yes or No 入力用
import codecs   # エンコード用
import unicodedata
import zipfile
from hashlib import md5
from Crypto.Cipher import AES
from Crypto import Random

# ===== 暗号化 =====
def derive_key_and_iv(password, salt, key_length, iv_length):
    d = d_i = ''
    while len(d) < key_length + iv_length:
        d_i = md5(d_i + password + salt).digest()
        d += d_i
    return d[:key_length], d[key_length:key_length+iv_length]

def encrypt(in_file, out_file, password, key_length=32):
    bs = AES.block_size
    salt = Random.new().read(bs - len('Salted__'))
    key, iv = derive_key_and_iv(password, salt, key_length, bs)
    cipher = AES.new(key, AES.MODE_CBC, iv)
    out_file.write('Salted__' + salt)
    finished = False
    while not finished:
        chunk = in_file.read(1024 * bs)
        if len(chunk) == 0 or len(chunk) % bs != 0:
            padding_length = (bs - len(chunk) % bs) or bs
            chunk += padding_length * chr(padding_length)
            finished = True
        out_file.write(cipher.encrypt(chunk))


# ===== 復号化 =====
def decrypt(in_file, out_file, password, key_length=32):
    bs = AES.block_size
    salt = in_file.read(bs)[len('Salted__'):]
    key, iv = derive_key_and_iv(password, salt, key_length, bs)
    cipher = AES.new(key, AES.MODE_CBC, iv)
    next_chunk = ''
    finished = False
    while not finished:
        chunk, next_chunk = next_chunk, cipher.decrypt(in_file.read(1024 * bs))
        if len(next_chunk) == 0:
            padding_length = ord(chunk[-1])
            chunk = chunk[:-padding_length]
            finished = True
        out_file.write(chunk)


# ===== zip ======
def zip_write_dir(base_dir, src_dir, zip_name):
    """ディレクトリをzip圧縮する
        base_dir: src_dirが属するディレクトリを表す
        src_dir: 圧縮対象のディレクトリを表す
        zip_name: 出力先のzipファイルのフルパスを表す
    """
    zf = zipfile.ZipFile(zip_name, 'w', zipfile.ZIP_DEFLATED)

    current_dir = os.getcwd();
    os.chdir(base_dir)

    for root,dirs,files in os.walk(src_dir):
        for _file in files:
            filename = os.path.join(root,_file)
            arcname = filename
            zf.write(filename, arcname)

    zf.close()
    os.chdir(current_dir)

# ===== Yes or No =====
def yesno(message):
    result = ''
    sys.stdout.write(message)
    sys.stdout.flush()
    attribute = termios.tcgetattr(sys.stdin)
    tty.setcbreak(sys.stdin)
    try:
        while True:
            char = sys.stdin.read(1)
            if char == 'y' or char == 'Y':
                result = 'y'
                break
            elif char == 'n' or char == 'N':
                result = 'n'
                break
    except KeyboardInterrupt:
        result = '^C'
    termios.tcsetattr(sys.stdin, termios.TCSAFLUSH, attribute)
    print(result)
    return result


# ===== other input ==============================================
_usr = getpass.getpass('>>>>>  ユーザー名: ')
if _usr == '':
    sys.exit()

_pass = getpass.getpass('>>>>>  パスワード: ')
if _pass == '':
    sys.exit()

_makedir = raw_input('>>>>>  書き込むディレクトリ: ')
try:
    if _makedir != '' and not os.path.exists(_makedir):
        if _makedir.find('/') == -1:
            os.mkdir(_makedir)
            print('ディレクトリ ' + _makedir + ' を作成しました。')
        else:
            os.makedirs(_makedir)
            print('ディレクトリ ' + _makedir + ' を作成しました。')
except:
    print('>>>>>  Error mkdirに失敗しました。')
    sys.exit()

res = yesno('>>>>>  ' + _makedir + ' にダウンロードします。\n  ※ 処理を続行しますか? (Yes or No) ')
if res != 'y':
    print('>>>>>  ※ 処理をキャンセルしました。')
    sys.exit()

# ===== ftps connect ====================================================
try:
    try:
        ## 'なんとか.com'は書き換えてください。
        ftps = FTP_TLS('なんとか.com', timeout = 850)
        # login anonymously before securing control channel
        ftps.set_pasv(True) # パッシブモードON
        ftps.set_debuglevel(1) # ログ出力
        ftps.login(_usr, _pass)
        ftps.prot_p()                       # switch to secure data connection

        ## 'ssl/cgi-bin'は書き換えてください。
        ftps.cwd('ssl/cgi-bin')
    except Exception as e:
        print('>>>>>  Error ftp接続に失敗しました。')
        print('>>>>>  内容: ' + str(type(e)) + '\n' + str(e))

    # ===== download =====================================================
    filelist = ftps.nlst()
    print(str(filelist))
    ftps.set_debuglevel(0) # ログ出力
    _cnt = 0
    for _file in filelist:
        if _file != '.' and _file != '..':
            ftps.retrbinary('RETR ' + _file, open(_makedir + '/' + _file, 'wb').write)
            _cnt +=1
            print('>>>>>  ( ' + str(_cnt) + ' )  ' + _file + ' をダウンロードしました。')

    print('>>>>>  ' + str(_cnt) + ' download Complete!!')
except Exception as e:
    print('>>>>>  Error ' + _file + ' をダウンロードが出来ませんでした。')
    print('>>>>>  内容: ' + str(type(e)) + '\n' + str(e))
    ftps.close()
    sys.exit()
finally:
    ftps.close()

_zip_name = raw_input('>>>>>  圧縮ファイル名 (.zipなし): ')
if _zip_name == '':
    sys.exit()

zip_write_dir('.', _makedir, _zip_name + '.zip')

print('>>>>>  ' + _zip_name + '.zip' + ' 圧縮 Complete!!')

password = getpass.getpass('>>>>>  暗号化パスワード: ')
if _pass == '':
    sys.exit()

# ===== 暗号化 =====
with open(_zip_name + '.zip', 'rb') as in_file, open(_zip_name + '.panz', 'wb') as out_file:
    encrypt(in_file, out_file, password)

print('>>>>>  ' + _zip_name + '.panz' + ' 暗号化 Complete!!')

quit()


# ===== 復号化 =====
# with open(in_filename, 'rb') as in_file, open(out_filename, 'wb') as out_file:
#    decrypt(in_file, out_file, password)
# print('>>>>>  ' + _zip_name + '.panz' + ' 復号化 Complete!!')












# ===== 2016/05/10_1 ==========================================================

2016年5月9日月曜日

Python でファイルの暗号化メモ

python でファイルの暗号化メモ

色んなExampleから抜き出して作成してみました。

angoka.py 暗号化ファイル

cAngo.py 暗号化実装ファイル

実行方法

$ python angoka.py




以下ソースファイル

#===== BEGIN angoka.py =======================================================
# encoding: utf-8

#####  pythonのpathは必要ならば書き加えてください。  #####
#####  print文の print('ooo') カッコでエラーとなる場合は print 'ooo' に書き換えてください  #####

import os, sys        # 既存ターゲットファイル削除
import getpass        # パスワード入力用
import termios        # Yes or No 入力用
import tty            # Yes or No 入力用
import subprocess     # shell command用
from cAngo import *   # 暗号・復号化用 cAngo.py

               
#===== Yes or No =================================
def yesno(message):
    result = ''
    sys.stdout.write(message)
    sys.stdout.flush()
    attribute = termios.tcgetattr(sys.stdin)
    tty.setcbreak(sys.stdin)
    try:
        while True:
            char = sys.stdin.read(1)
            if char == 'y' or char == 'Y':
                result = 'y'
                break
            elif char == 'n' or char == 'N':
                result = 'n'
                break
    except KeyboardInterrupt:
        result = '^C'
    termios.tcsetattr(sys.stdin, termios.TCSAFLUSH, attribute)
    print(result)
    return result
   

#===== ファイル削除 =====================================================  
def delete_file(target):
    ret = os.path.exists(target)
    try:
        if ret:
            os.remove(target)
        return True
    except:
        print('  >>> ' + target + ' を削除出来ませんでした。')
        return False
       
       
       
_target_user = ''
_num = raw_input('暗号化 or 復号化を選択してください。\n  1: 暗号化\n  2: 復号化\n  ※番号を入力してください。: ')

if _num != '1' and _num != '2':
    print(' >>> キャンセルしました。')
    sys.exit()
   
   
_keycode = getpass.getpass('  >>> キーコードを入力して下さい。: ')
if _keycode == '':
    sys.exit()
     
 
_message = '暗号化'  
  
if _num == '2':
    _message = '復号化' 
   
           
_source_file = raw_input('  >>> ' + _message + ' するファイル名を入力して下さい。: ')
if _source_file == '':
    sys.exit()
   

ret = os.path.exists(_source_file)
if not ret:
    print(_source_file + ' は存在しません。')
    sys.exit()
   
   
   
_dest_file = raw_input('  >>> 出力するファイル名を入力して下さい。(未入力可): ')
if _dest_file == '':
    _dest_file = _source_file + '.enc'
   

# 既存ファイルの存在と上書きの確認   
ret = os.path.exists(_dest_file)
if ret:
    result = yesno(' >>> ' + _dest_file + ' はすでに存在します、上書きしますか? (Yes or No) ')
   
    if result != 'y':
        print(' >>> 中止しました。')
        sys.exit()
       
         
result = yesno(' >>> ' + _message + ' を実行しますか? (Yes or No) ')
if result != 'y':
    print('  >>> キャンセルしました。')
    sys.exit()
                       

# 既存ファイル削除
ret = delete_file(_dest_file)
if not ret:
    print(' >>> ' + _dest_file + ' を削除できませんでした。 中止します。')
    sys.exit()

try:
    if _num == '1':
        encrypt_file(_keycode, _source_file, _dest_file) # 暗号化
    else:
        decrypt_file(_keycode, _source_file, _dest_file) # 復号化       
except Exception as e:
    print('  >>> Error 中止しました。 (02)' + e.message)
    sys.exit()
      
      
ret = os.path.exists(_dest_file) # 暗号化・復号化ファイルが作成されたか確認
if not ret:
    print('  >>> Error 失敗しました。 (03)')
    sys.exit()

path = os.path.dirname(_dest_file) # ファイルのdirectory  
       
print(subprocess.check_output(['ls', '-l', path])) # 確認用 ls -l
         
print(' >>> ' + _message + ' Complete!! <<<')

# 2016/05/09_1
#===== END angoka.py =========================================================


※参考リンク

http://eli.thegreenplace.net/2010/06/25/aes-encryption-of-files-in-python-with-pycrypto
#===== BEGIN cAngo.py =========================================================
# encoding: utf-8
import os, random, struct
from Crypto.Cipher import AES


def encrypt_file(key, in_filename, out_filename=None, chunksize=64*1024):
    """ Encrypts a file using AES (CBC mode) with the
        given key.
   
        key:
            The encryption key - a string that must be
            either 16, 24 or 32 bytes long. Longer keys
            are more secure.
       
        in_filename:
            Name of the input file
       
        out_filename:
            If None, '<in_filename>.enc' will be used.
       
        chunksize:
            Sets the size of the chunk which the function
            uses to read and encrypt the file. Larger chunk
            sizes can be faster for some files and machines.
            chunksize must be divisible by 16.
    """
   
    if not out_filename:
        out_filename = in_filename + '.enc'
   
    if len(key) < 8:
        print('keyは8桁以上にして下さい。') # 安全のため8桁以上に
        return
       
  
    if len(key) % 16 != 0:
        key = key +  '=' * (16 - (len(key) % 16))
        #print(key)
                
    iv = ''.join(chr(random.randint(0, 0xFF)) for i in range(16))
    encryptor = AES.new(key, AES.MODE_CBC, iv)
    filesize = os.path.getsize(in_filename)

    with open(in_filename, 'rb') as infile:
        with open(out_filename, 'wb') as outfile:
            outfile.write(struct.pack('<Q', filesize))
            outfile.write(iv)
       
            while True:
                chunk = infile.read(chunksize)
                if len(chunk) == 0:
                    break
                elif len(chunk) % 16 != 0:
                    chunk += ' ' * (16 - len(chunk) % 16)
               
                outfile.write(encryptor.encrypt(chunk))
               
            
            
def decrypt_file(key, in_filename, out_filename=None, chunksize=24*1024):
    """ Decrypts a file using AES (CBC mode) with the
        given key. Parameters are similar to encrypt_file,
        with one difference: out_filename, if not supplied
        will be in_filename without its last extension
        (i.e. if in_filename is 'aaa.zip.enc' then
        out_filename will be 'aaa.zip')
    """
   
    if not out_filename:
        out_filename = os.path.splitext(in_filename)[0]
   
   
    if len(key) < 8:
        print('keyは8桁以上にして下さい。') # 安全のため8桁以上に
        return
       
       
    # キーコードの文字数は16の倍数にする必要があるので足らない分は'='を付け足す   
    if len(key) % 16 != 0:
        key = key +  '=' * (16 - (len(key) % 16))
        #print(key)
       
       
    with open(in_filename, 'rb') as infile:
        origsize = struct.unpack('<Q', infile.read(struct.calcsize('Q')))[0]
        iv = infile.read(16)
        decryptor = AES.new(key, AES.MODE_CBC, iv)
   
        with open(out_filename, 'wb') as outfile:
            while True:
                chunk = infile.read(chunksize)
                if len(chunk) == 0:
                    break
                outfile.write(decryptor.decrypt(chunk))
           
            outfile.truncate(origsize)
           
               
# 2016/05/09_1
#===== END cAngo.py =========================================================