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 =========================================================


2016年5月8日日曜日

Fedora23 server で intel NUC wifi 設定メモ

fedora 23 server intel NUC wifi 設定

fedora23 server でwifiを設定する。

wifiのdriverはデフォルトでインストールしてある。

※NetworkManager-wifiのインストール

root権限で
$ su
password:ooooooooo


# dnf install NetworkManager-wifi

※接続する ネットワーク名(SSID)とパスワードは各自で書き換える事

# nmcli device wifi connect ネットワーク名(SSID) password パスワード

wifi deviceが認識されていなければrebootしてみる

確認
# ifconfig
又は
# iwconfig

注意:パスワードがbashの履歴に残るので
# vi ~/.bash_story
で削除する事