X Window Systemについての備忘禄

今回のゴール

VirtualBox上で起動しているCentOSGUIアプリケーションをゲストOSのWindowsに描画する。 ほとんどXWindowSystemについての備忘禄。

環境情報

ホストOS : Windows7
ゲストOS :CentOS7

X Window Systemとは

物凄い平たく言えば、他ホストで実行されるアプリケーションのウィンドウを 自ホスト上に表示させ、操作することができる仕組み。

クライアント・サーバモデルを採用しており、 使用者が直接操作する側がサーバ(X サーバ)、 リモートで動作する側がクライアント(X クライアント)となる。 今回の場合、ホストOS側がXサーバとなり、ゲストOS側がXクライアントとなる。

Windows用Xサーバ

代表的なWindows用のXサーバとしては「Xming」がある。 今回はこちらをホストOSにインストールする。

http://www.straightrunning.com/XmingNotes/

X11フォワーディング

今回はX11フォワーディングという機能を利用して、 Xクライアントの情報をXサーバであるXmingに転送することで Windows上にCentOS上のアプリケーションを表示することになる。。

X11 フォワーディングについては以下の記事が非常にわかりやすかった。 http://research.kek.jp/people/yashiro/RepN/KEKint00-01/ssh_p.html

Jenkinsバックアップ&リストア(Windows編)

今回のゴール

Windows環境で起動しているJenkinsのバックアップを定期的に作成する。
バックアップファイル別のWindows環境にリストアする。

環境情報

OS : Windows7
Jenkins :1.514

バックアップ方法

バックアップ用のプラグインthinBackupなど)を利用する方法もあるが、
バックアップ対象などをフレキシブルに変更できるようにするため
バッチファイルを作成する。
当該のバッチファイルをJENKINSよりスケジュール起動することで、
定期的にバックアップを取得する。

バックアップ対象

下記のファイルを除く%JENKINS_HOME%配下全て

  • ${JENKINS_HOME}/jobs/${JOB_NAME}/builds : ビルド履歴
  • ${JENKINS_HOME}/jobs/${JOB_NAME}/workspace : ワークスペース
  • ${JENKINS_HOME}/jobs/${JOB_NAME}/lastStable : 最終安定ビルド
  • ${JENKINS_HOME}/jobs/${JOB_NAME}/lastSuccessful : 最終成功ビルド
  • ${JENKINS_HOME}/jobs/${JOB_NAME}/nextBuildNumber : 次回ビルド番号

要はビルド履歴に関するデータとワークスペース以外

バッチファイル作成

jenkins_backup.bat

SET BKDATE=%date:~-10,4%%date:~-5,2%%date:~-2,2%

REM バックアップファイル作成
%WORKSPACE%/7za920/7za.exe a -xr!*/jobs/*/workspace -xr!*/jobs/*/builds -xr!*/jobs/*/lastStable -xr!*/jobs/*/lastSuccessful -xr!*/jobs/*/nextBuildNumber "%WORKSPACE%/jenkins_%BKDATE%.zip" "%JENKINS_HOME%"

REM バックアップフォルダへコピー
copy "%WORKSPACE%\jenkins_%BKDATE%.zip" "%BACKUP_DIR%"

REM バックアップ世代管理
pushd "%BACKUP_DIR%"
for /f skip=%BACKUP_GEN% %%A in (`dir /a-d jenkins_????????.zip /b /o-d`) do (
    del /q %%A
)

1.JENKINSより渡される変数

  • JENKINS_HOME : JENKINSホームディレクトリの絶対パス
  • WORKSPACE : JENKINSワークスペース絶対パス
  • BACKUP_DIR : バックアップファイルの配置先
  • BACKUP_GEN : バックアップ世代数

 
2.ディレクトリ構成
%WORKSPACE%
 ├ 7za920
 │ ├ 7za.exe
 │ └ …
 └ jenkins_backup.bat …実行スクリプト
 
3.バックアップファイルにタイムスタンプを付与

SET BKDATE=%date:~-10,4%%date:~-5,2%%date:~-2,2%

 
4.バックアップファイルのZIP化

%WORKSPACE%/7za920/7za.exe a -xr!*/jobs/*/workspace -xr!*/jobs/*/builds -xr!*/jobs/*/lastStable -xr!*/jobs/*/lastSuccessful -xr!*/jobs/*/nextBuildNumber "%WORKSPACE%/jenkins_%BKDATE%.zip" "%JENKINS_HOME%"

WindowsコマンドラインではZIP化のコマンドが無いため、7-Zipコマンドライン版を使用する。
http://sevenzip.sourceforge.jp/howto/non-install-compress.html

各種コマンドは以下のとおり。

7-Zip (A) 9.20  Copyright (c) 1999-2010 Igor Pavlov  2010-11-18

Usage: 7za <command> [<switches>...] <archive_name> [<file_names>...]
       [<@listfiles...>]

<Commands>
  a: Add files to archive
  b: Benchmark
  d: Delete files from archive
  e: Extract files from archive (without using directory names)
  l: List contents of archive
  t: Test integrity of archive
  u: Update files to archive
  x: eXtract files with full paths
<Switches>
  -ai[r[-|0]]{@listfile|!wildcard}: Include archives
  -ax[r[-|0]]{@listfile|!wildcard}: eXclude archives
  -bd: Disable percentage indicator
  -i[r[-|0]]{@listfile|!wildcard}: Include filenames
  -m{Parameters}: set compression Method
  -o{Directory}: set Output directory
  -p{Password}: set Password
  -r[-|0]: Recurse subdirectories
  -scs{UTF-8 | WIN | DOS}: set charset for list files
  -sfx[{name}]: Create SFX archive
  -si[{name}]: read data from stdin
  -slt: show technical information for l (List) command
  -so: write data to stdout
  -ssc[-]: set sensitive case mode
  -ssw: compress shared files
  -t{Type}: Set type of archive
  -u[-][p#][q#][r#][x#][y#][z#][!newArchiveName]: Update options
  -v{Size}[b|k|m|g]: Create volumes
  -w[{path}]: assign Work directory. Empty path means a temporary directory
  -x[r[-|0]]]{@listfile|!wildcard}: eXclude filenames
  -y: assume Yes on all queries

 
5.世代管理
管理世代数を超えたファイルを削除する。

for /f "skip=%BACKUP_GEN%" %%A in ('dir /a-d jenkins_????????.zip /b /o-d') do (
    del /q %%A
)

JENKINSより起動

週1回の定期実行JOBを作成する。詳細は割愛。

リストア

1.JENKINS_HOME配下を削除(退避)
 
2.バックアップファイル(.zip)を解凍し、JENKINS_HOME配下に配置

※異なる環境にリストアする場合、Jenkinsの設定(Jenkins > Jenkinsの管理 > システムの設定)に留意する必要がある。

  • JDK/インストール済みのJDK …MAVEN_HOMEを適切に設定すること
  • Maven/インストール済みのMaven …JAVA_HOMEを適切に設定すること
  • Jenkinsの位置/Jenkins URL …Jenkins URLを適切に設定すること
  • Subversion/ワークスペースバージョン …バージョンを適切に設定すること
    などなど…

Raspberry PiにVPNサーバを構築する (1)インストール編

環境情報

PC : Raspberry Pi Model B
OS : Raspbian

VPNとは?

こちらのサイトを参考に
http://www.atmarkit.co.jp/fsecurity/special/22fivemin/fivemin00.html

インストールするVPNソフトウェア

SoftEther VPNhttps://ja.softether.org/

インストール手順

手順は公式マニュアルを参考に
https://ja.softether.org/4-docs/1-manual/7/7.3

1. パッケージのダウンロード
https://ja.softether.org/5-download

# wget http://jp.softether-download.com/files/softether/v4.06-9437-beta-2014.04.09-tree/Linux/SoftEther%20VPN%20Server/32bit%20-%20ARM%20EABI/softether-vpnserver-v4.06-9437-beta-2014.04.09-linux-arm_eabi-32bit.tar.gz

 
2. パッケージの解凍

# tar xzvf softether-vpnserver-v4.06-9437-beta-2014.04.09-linux-arm_eabi-32bit.tar.gz 

 
3. 実行可能ファイルの生成
vpnserverフォルダに移動し、makeコマンドを実行する

# cd vpnserver/
# make

 
4. VPNサーバの配置

vpnserver ディレクトリを、/usr/local ディレクトリに移動する

# mv vpnserver /usr/local

 
5. 権限の設定

# cd /usr/local/vpnserver
# chmod 600 *
# chmod 700 vpncmd vpnserver
# ll -tr
total 7500
-rw------- 1 root root   58227 Apr  9 10:22 ReadMeFirst_License.txt
-rw------- 1 root root   47041 Apr  9 10:22 ReadMeFirst_Important_Notices_ja.txt
-rw------- 1 root root   33209 Apr  9 10:22 ReadMeFirst_Important_Notices_en.txt
-rw------- 1 root root   28351 Apr  9 10:22 ReadMeFirst_Important_Notices_cn.txt
-rw------- 1 root root    2097 Apr  9 10:22 Makefile
-rw------- 1 root root 1009450 Apr  9 10:22 hamcore.se2
-rw------- 1 root root    1838 Apr  9 10:22 Authors.txt
drw------- 2 root root    4096 May  3 23:49 lib
-rwx------ 1 root root 3216345 May  3 23:50 vpnserver
drw------- 2 root root    4096 May  3 23:50 code
-rwx------ 1 root root 3216349 May  3 23:50 vpncmd
-rw------- 1 root root     867 May  3 23:50 lang.config
drw------- 2 root root    4096 May  3 23:50 chain_certs

 
6. check コマンドによる動作確認
下記のように全てのチェックに合格すればOK

# ./vpncmd
vpncmd command - SoftEther VPN Command Line Management Utility
SoftEther VPN Command Line Management Utility (vpncmd command)
Version 4.06 Build 9437   (English)
Compiled 2014/04/09 10:10:41 by yagi at pc25
Copyright (c) SoftEther VPN Project. All Rights Reserved.

By using vpncmd program, the following can be achieved. 

1. Management of VPN Server or VPN Bridge 
2. Management of VPN Client
3. Use of VPN Tools (certificate creation and Network Traffic Speed Test Tool)

Select 1, 2 or 3: 3

VPN Tools has been launched. By inputting HELP, you can view a list of the commands that can be used.

VPN Tools>check  
Check command - Check whether SoftEther VPN Operation is Possible
---------------------------------------------------
SoftEther VPN Operation Environment Check Tool

Copyright (c) SoftEther VPN Project.
All Rights Reserved.

If this operation environment check tool is run on a system and that system passes, it is most likely that SoftEther VPN software can operate on that system. This check may take a while. Please wait...

Checking 'Kernel System'... 
              Pass
Checking 'Memory Operation System'... 
              Pass
Checking 'ANSI / Unicode string processing system'... 
              Pass
Checking 'File system'... 
              Pass
Checking 'Thread processing system'... 
              Pass
Checking 'Network system'... 
              Pass

All checks passed. It is most likely that SoftEther VPN Server / Bridge can operate normally on this system.

The command completed successfully.

 
7. init.dスクリプトの作成

# vi /etc/init.d/vpnserver

以下の内容を記載する

#!/bin/sh
# chkconfig: 2345 99 01
# description: SoftEther VPN Server

DAEMON=/usr/local/vpnserver/vpnserver
LOCK=/var/lock/subsys/vpnserver

test -x $DAEMON || exit 0

case "$1" in
    start)
        $DAEMON start
        touch $LOCK
        ;;
    stop)
        $DAEMON stop
        rm $LOCK
        ;;
    restart)
        $DAEMON stop
        sleep 5
        $DAEMON start
        ;;
    *)
        echo "Usage: $0 {start|stop|restart}"
        exit 1
esac

exit 0

権限を付与する

# chmod 775 /etc/init.d/vpnserver

 
8. chkconfigによるサービスの自動起動設定

# chkconfig -add vpnserver
insserv: warning: script 'vpnserver' missing LSB tags and overrides
insserv: warning: script 'mathkernel' missing LSB tags and overrides
vpnserver                 0:off  1:off  2:on   3:on   4:on   5:on   6:off

 
9. 起動と停止

# service vpnserver start
SoftEther VPN Server Service Started.
# service vpnserver stop
Stopping SoftEther VPN Server Service...
SoftEther VPN Server Service Stopped.

Raspberry Pi デスクトップ画面の共有

今回やりたいこと

Raspberry piのデスクトップを無線LAN経由で別のPCで表示操作できるようにする。

環境情報
PC  :MacBook Pro
OS  :OS X 10.9.1

tightvncserverのインストール

raspberry piにVNCサーバをインストールする。

pi@raspberrypi ~ $ sudo apt-get install tightvncserver
Reading package lists... Done
Building dependency tree       
Reading state information... Done
The following extra packages will be installed:
  x11-xserver-utils xfonts-base
Suggested packages:
  tightvnc-java nickle cairo-5c xorg-docs-core
The following NEW packages will be installed:
  tightvncserver x11-xserver-utils xfonts-base
0 upgraded, 3 newly installed, 0 to remove and 0 not upgraded.
Need to get 7,148 kB of archives.
After this operation, 10.4 MB of additional disk space will be used.
Do you want to continue [Y/n]? Y
Get:1 http://mirrordirector.raspbian.org/raspbian/ wheezy/main tightvncserver armhf 1.3.9-6.4 [786 kB]
Get:2 http://mirrordirector.raspbian.org/raspbian/ wheezy/main x11-xserver-utils armhf 7.7~3 [181 kB]
Get:3 http://mirrordirector.raspbian.org/raspbian/ wheezy/main xfonts-base all 1:1.0.3 [6,181 kB]
Fetched 7,148 kB in 7s (999 kB/s)                                                                                                                              
Selecting previously unselected package tightvncserver.
(Reading database ... 68746 files and directories currently installed.)
Unpacking tightvncserver (from .../tightvncserver_1.3.9-6.4_armhf.deb) ...
Selecting previously unselected package x11-xserver-utils.
Unpacking x11-xserver-utils (from .../x11-xserver-utils_7.7~3_armhf.deb) ...
Selecting previously unselected package xfonts-base.
Unpacking xfonts-base (from .../xfonts-base_1%3a1.0.3_all.deb) ...
Processing triggers for man-db ...
Processing triggers for menu ...
Processing triggers for fontconfig ...
Setting up tightvncserver (1.3.9-6.4) ...
update-alternatives: using /usr/bin/tightvncserver to provide /usr/bin/vncserver (vncserver) in auto mode
update-alternatives: using /usr/bin/Xtightvnc to provide /usr/bin/Xvnc (Xvnc) in auto mode
update-alternatives: using /usr/bin/tightvncpasswd to provide /usr/bin/vncpasswd (vncpasswd) in auto mode
Setting up x11-xserver-utils (7.7~3) ...
Setting up xfonts-base (1:1.0.3) ...
Processing triggers for menu ...

起動してみる。
初回のみパスワードの設定を求められるみたい。

pi@raspberrypi ~ $ tightvncserver

You will require a password to access your desktops.

Password: 
Verify:   
Would you like to enter a view-only password (y/n)? y
Password: 
Verify:   

New 'X' desktop is raspberrypi:1

Creating default startup script /home/pi/.vnc/xstartup
Starting applications specified in /home/pi/.vnc/xstartup
Log file is /home/pi/.vnc/raspberrypi:1.log

ポートがLISTENか確認してみる。5901がちゃんと開いている。

pi@raspberrypi ~ $ netstat -lnt
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State      
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN     
tcp        0      0 127.0.0.1:6010          0.0.0.0:*               LISTEN     
tcp        0      0 0.0.0.0:5901            0.0.0.0:*               LISTEN     
tcp        0      0 0.0.0.0:6001            0.0.0.0:*               LISTEN 

Macから接続

Macは標準で VNC クライアントが用意されている。
Finder メニューバー > 移動 > サーバに接続 を選択して
プロトコル名(vnc)に Raspberry Pi のアドレスとポート番号 を加えて接続する。

f:id:takenyaan:20140216200603p:plain

サーバ側で設定したパスワードを入力すれば、
raspberry piのデスクトップ画面が表示される。

f:id:takenyaan:20140216200738p:plain

PythonでTwitter(1)準備編

今回やりたいこと

PythonからTwetterに接続し、ツイートさせてみたいと思う。

環境情報
PC  :MacBook Pro
OS  :OS X 10.9.1
Python:2.7.5

1. モジュールのインストール

twitterAPI用Pythonライブラリはtweepyとかpython-twitterとかいろいろあるみたい。 今回はなんとなくpython-twitterにしてみる。

まずはpython-twitterをインストールする。

$ sudo pip install python-twitter
Password:
Downloading/unpacking python-twitter
  Downloading python-twitter-1.1.tar.gz (91kB): 91kB downloaded
  Running setup.py (path:/private/tmp/pip_build_root/python-twitter/setup.py) egg_info for package python-twitter
    
    no previously-included directories found matching '.DS_Store'
Requirement already satisfied (use --upgrade to upgrade): setuptools in ./Extras/lib/python (from python-twitter)
Downloading/unpacking simplejson (from python-twitter)
  Downloading simplejson-3.3.2.tar.gz (67kB): 67kB downloaded
  Running setup.py (path:/private/tmp/pip_build_root/simplejson/setup.py) egg_info for package simplejson
    
Downloading/unpacking oauth2 (from python-twitter)
  Downloading oauth2-1.5.211.tar.gz
  Running setup.py (path:/private/tmp/pip_build_root/oauth2/setup.py) egg_info for package oauth2
    
Downloading/unpacking requests (from python-twitter)
  Downloading requests-2.2.1-py2.py3-none-any.whl (625kB): 625kB downloaded
Downloading/unpacking requests-oauthlib (from python-twitter)
  Downloading requests-oauthlib-0.4.0.tar.gz
  Running setup.py (path:/private/tmp/pip_build_root/requests-oauthlib/setup.py) egg_info for package requests-oauthlib
    
Downloading/unpacking httplib2 (from oauth2->python-twitter)
  Downloading httplib2-0.8.tar.gz (110kB): 110kB downloaded
  Running setup.py (path:/private/tmp/pip_build_root/httplib2/setup.py) egg_info for package httplib2
    
Downloading/unpacking oauthlib>=0.4.2 (from requests-oauthlib->python-twitter)
  Downloading oauthlib-0.6.1.tar.gz (96kB): 96kB downloaded
  Running setup.py (path:/private/tmp/pip_build_root/oauthlib/setup.py) egg_info for package oauthlib
    
Installing collected packages: python-twitter, simplejson, oauth2, requests, requests-oauthlib, httplib2, oauthlib
  Running setup.py install for python-twitter
    
    no previously-included directories found matching '.DS_Store'
  Running setup.py install for simplejson
    building 'simplejson._speedups' extension
    cc -fno-strict-aliasing -fno-common -dynamic -arch x86_64 -arch i386 -g -Os -pipe -fno-common -fno-strict-aliasing -fwrapv -mno-fused-madd -DENABLE_DTRACE -DMACOSX -DNDEBUG -Wall -Wstrict-prototypes -Wshorten-64-to-32 -DNDEBUG -g -fwrapv -Os -Wall -Wstrict-prototypes -DENABLE_DTRACE -arch x86_64 -arch i386 -pipe -I/System/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7 -c simplejson/_speedups.c -o build/temp.macosx-10.9-intel-2.7/simplejson/_speedups.o
    
    You have not agreed to the Xcode license agreements, please run 'xcodebuild -license' (for user-level acceptance) or 'sudo xcodebuild -license' (for system-wide acceptance) from within a Terminal window to review and agree to the Xcode license agreements.
    ***************************************************************************
    WARNING: The C extension could not be compiled, speedups are not enabled.
    Failure information, if any, is above.
    I'm retrying the build without the C extension now.
    ***************************************************************************
    
    ***************************************************************************
    WARNING: The C extension could not be compiled, speedups are not enabled.
    Plain-Python installation succeeded.
    ***************************************************************************
  Running setup.py install for oauth2
    
  Running setup.py install for requests-oauthlib
    
  Running setup.py install for httplib2
    
  Running setup.py install for oauthlib
    
Successfully installed python-twitter simplejson oauth2 requests requests-oauthlib httplib2 oauthlib
Cleaning up...

確認してみる。 確かにインストールされたみたいだ。

$ pip freeze | grep twitter
python-twitter==1.1

2. Application登録

twitterAPIを利用するためには、
Twitter Developers」にアプリケーションの登録をする必要がある。

以下のサイトにアクセスする。

Twitter Developers : https://dev.twitter.com/

右上の「Sign in」から、ログインページへ遷移し、
Twitterアカウントとパスワードを入力する。
(今回は開発用のアカウントを別途新規作成した。)

f:id:takenyaan:20140202015626p:plain

 
ログインが完了したら右上の「My applications」を選択する。

f:id:takenyaan:20140202020354p:plain

 
「Create a new application」からApplication登録ページへ遷移する。
必要な情報を入力したら「Create your Twitter application」をクリックする。

f:id:takenyaan:20140202020922p:plain

Name
アプリケーションの名前

Description
アプリケーションの説明

WebSite
アプリケーションを動作させるWEBサイトのURL
※今回は適当に入力する

Callback URL
認証などを行った時にtwitterから自分のアプリケーションに戻る時のURL
※今回は空白で問題なし
 
登録が完了したら「Setting」タブを選択し、
「Application Type」に「Read, Write and Access direct messages」を選択する。
「Read only」のままだと書き込み(=ツイート)ができないのだ。

f:id:takenyaan:20140202203945p:plain

 

変更後、「Update this Twitter application’s setting」ボタンをクリックする。
更新が終わったら、ページ左上、「Details 」を選択し元の画面へ戻る。

次にアクセストークンを作成する。
ページ下「Your access token」に「Create my access token」があるのでクリックする。

このアクセストークンは「Twitter Developers」にログインしたユーザの「鍵」のようなものであり、 この「鍵」を利用することでそのユーザにツイートさせることができるのである。
※「Twitter Developers」にログインしたユーザ以外のアクセストークンを取得したい場合は、
 別の方法が必要となる。

 
最後に登録した情報を確認する。

f:id:takenyaan:20140202210622p:plain

 

以下の情報が必要になるので、メモしておく。
・Consumer key
・Consumer secret
Access token
Access token secret

これで下準備は完了!!!
次はいよいよ、Pythonをかこう!!!(やっと・・・)