2017年9月22日 星期五

Python Note



==========py to exe with sign==========
參考網址https://steward-fu.github.io/website/driver/wdm/self_sign.htm
或這個也寫得不錯http://mqjing.blogspot.tw/2009/03/plugin-activex-cab-signtool.html

signtool get from MS SDK or Visual C++ for Python (http://aka.ms/vcpython27)

First time
Makecert -r -pe -ss YourName YourName.cer
certmgr.exe -add YourName.cer -s -r localMachine root
After
signtool sign /s YourName YourApp.exe

==========bundle exe to py.exe==========
http://blog.csdn.net/Sagittarius_Warrior/article/details/73998548

currPath = sys.path[0]
os.system(currPath+"\\exe.exe") #exe.exe can not be found if without sys.path[0]
#or  add sys.path[0] to cwd path
os.path.join(os.getcwd(),sys.path[0])

C:\Python27\Scripts\pyinstaller --uac-admin ^
--uac-uiaccess ^
--win-private-assemblies ^
--clean ^
--key 1234512345 ^
-i Home.ico ^
--add-data=exe.exe;. ^
--add-data=signtool.exe;. ^
-F exe_Test.py

註: ^ 是換行的意思


====================
====================
====================
====================
======同時安裝python2 & 3==============
https://www.zhihu.com/question/21653286
py -2 v2.py
py -3 v3.py
py -2 -m pip install package
py -3 -m pip install package
header #! python2 or #! python3

==========Server & Client的部分==========
http://www.bogotobogo.com/python/python_network_programming_server_client_file_transfer.php

加一下自己寫的東西... https://github.com/kyc1109/devcon

# Compile .py to class ==========================================
#https://stackoverflow.com/questions/14205464/converting-jython-code-into-a-java-class
Test file: A31Mod.py, A31Mod$py.class
指令如下: #若直接用Jython編譯則產出class, 但是如果直接用Python編譯則產出pyc檔。
java -jar jython-standalone-2.7.0.jar #run Jython
>>> import compileall   # import for compile multi file。
#>>> compileall.compile_dir('directory/', force=True) #compile multi file
>>> import py_compile   # import for compile single file。
>>> py_compile.compile("A31Mod.py") #compile single file from A31Mod.py to A31Mod$py.class
>>> from A31Mod import A31Mod #import A31Mod$py.class
>>> a31 = A31Mod("TC_COM_1436") # use A31Mod()
>>> a31.LAN_PING()
ping www.compal.com #result
LAN check Pass #result


Python 中文教學
http://mirror.sars.tw/Python_tut_tw/tut.html

#How to overload __init__ method based on argument type?==========================================
#https://stackoverflow.com/questions/141545/how-to-overload-init-method-based-on-argument-type
class MyData: #Quick and dirty fix
    def __init__(string=None,list=None):
        if string is not None:
            #do stuff
        elif list is not None:
            #do other stuff
        else:
            #make data empty
#===import py part 1=======================================
#Complex.py
class Complex:
    def __init__(self, realpart, imagpart): #__init__ 就是class的方法,所以等於Complex()
        self.r = realpart
        self.i = imagpart     
#test.py
from Complex import Complex
x = Complex(3.0,-4.5)
print x.r, x.i

#===import py part 2=======================================
import os, subprocess, time
#變數和呼叫的方法要前面要加self.,所以會有一堆self.xxx。
class DevCompareMod:
    def __init__(self, original_file, unoriginal_file, log_file): #__init__ equal DevCompareMod()
        self.original_file = original_file #"original.txt"
        self.unoriginal_file = unoriginal_file #"unoriginal.txt"
        self.log_file = log_file #"log_DevCompare.txt"
    def wLog(self, txtLog):
        if not os.path.exists(self.log_file):
            wLog=open(self.log_file, "w")
            wLog.write(txtLog)
            wLog.close()     
        else:
            wLog=open(self.log_file, "a")
            wLog.write(txtLog)
            wLog.close()
    self.wLog(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())+"=======================================\n")
    self.wLog(strLost)

#使用方式
from DevCompareMod import DevCompareMod
DevCompareMod("original.txt","unoriginal.txt","log_DevCompare.txt")

#===import py part 3=======================================
#__init__ 和 __name__是可以一起用的
class DevCompareMod:
    def __init__(self): #__init__ equal DevCompareMod()

if __name__ == '__main__':
if len(sys.argv) < 2 or sys.argv[1].lower()=="/h" or sys.argv[1].lower()=="-h" or sys.argv[1].lower()=="/?" or sys.argv[1].lower()=="-?" : #len小於2也就是不帶參數啦
print "no/wrong argument."
else:
DevCompareMod()
# 參考網址 http://www.kaiching.org/2012/12/Python-Constructor.html




http://usyiyi.cn/documents/python_278/library/subprocess.html
簡中的翻譯版

建議優先使用 subprocess.call()或是subprocess.check_call()或是subprocess.check_output()(回傳值不為0則丟出例外),
如果不行的話,再用Popen 搭配communicate()
#Popen VS. check_output
#因為check_outputt因為已經內建stdout,所以如果有問題只會出現error code和error msg,但不會出現執行的內容。
try:
p = subprocess.check_output(["ls non_existent_file; exit 1"],shell=True, stderr=subprocess.STDOUT) #不允許stdout因為已經內建了
print p
except subprocess.CalledProcessError,e:
    print e.output
    輸出ls: cannot access 'non_existent_file': No such file or directory

q = subprocess.Popen(["ls","-a"],shell=True, stdout=PIPE, stderr=PIPE)
stdout, stderr = q.communicate() 
print stdout
輸出README.md
輸出Test_1.ipynb



https://docs.python.org/2/library/subprocess.html
#method2, output="dmesg | grep hda"
p1 = Popen(["dmesg"], stdout=PIPE)
p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
p1.stdout.close()  # Allow p1 to receive a SIGPIPE if p2 exits.
output = p2.communicate()[0]

http://www.powenko.com/wordpress/?p=8697
翻譯的有點怪,但還可以接受啦



https://stackoverflow.com/questions/4348524/subprocess-variables
https://blog.aweimeow.tw/2016/09/09/python-subprocess-%E5%90%84%E5%87%BD%E5%BC%8F%E7%9A%84%E4%BD%BF%E7%94%A8%E6%99%82%E6%A9%9F/

參考上述網頁,Popen裡面的指令與參數,用逗號","取代空格" "可以避免不必要的錯誤。
透過PIPE把結果回傳到stdout或是stderr。


def subxx(): 
    import sys, os, subprocess               # Import socket module
    from subprocess import Popen, PIPE
    try:
        output = subprocess.Popen(["ping","localhost"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)    #useing , not space in cmd
        stdout, stderr= output.communicate()
        print ("output: \n"+str(output))
        print ("stdout: \n"+stdout)
    except subprocess.CalledProcessError:
        print('Exception handled')

subxx()

====以下為輸出結果=============================================
output: 
<subprocess.Popen object at 0x8>
stdout: 

Ping localhost [127.0.0.1] (使用 32 位元組的資料): 
回覆自 127.0.0.1: 位元組=32 time<1ms TTL=128 
回覆自 127.0.0.1: 位元組=32 time<1ms TTL=128 
回覆自 127.0.0.1: 位元組=32 time<1ms TTL=128 
回覆自 127.0.0.1: 位元組=32 time<1ms TTL=128 

127.0.0.1 的 Ping 統計資料: 
封包: 已傳送 = 4,已收到 = 4, 已遺失 = 0 (0% 遺失), 
大約的來回時間 (毫秒): 
最小值 = 0ms,最大值 = 0ms,平均 = 0ms




















2017年9月15日 星期五

Java Screen Capture




    private static void screencapture() throws IOException, AWTException {
        //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        try{
            GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
            GraphicsDevice[] gs = ge.getScreenDevices();
            for (int j = 0; j < gs.length; j++) {   //get each monitor
                GraphicsDevice gd = gs[j];
                GraphicsConfiguration[] gc = gd.getConfigurations();          
                for (int i=0; i < gc.length; i++) {
                    Rectangle rec = gc[i].getBounds();  //get each screen resolution
                    BufferedImage image = new Robot().createScreenCapture(rec);
                 
                    String timeStamp = new SimpleDateFormat("MMdd_HHmm_ss").format(Calendar.getInstance().getTime());    //yyyyMMdd_HHmmss
                    ImageIO.write(image, "png", new File("Screen_"+j+"_"+ rec.width +"x"+rec.height +"_"+timeStamp +".png"));
                    System.out.println("Screen:"+j+"_"+ rec.width +"x"+rec.height +"_"+timeStamp +".png");
                    //Save file at %userprofile%\Documents\NetBeansProjects\JavaSikuli
                }  
            }
        } catch (AWTException ex) {
            Logger.getLogger(JavaSnapshot.class.getName()).log(Level.SEVERE, null, ex);          
        }
    }

2017年9月4日 星期一

Sikuli 筆記

VLC record desktop command:
vlc screen:// -I rc --screen-fps 30 :sout=#transcode{vcodec=h264}:std{access=file,dst=%homepath%/Desktop/output.mp4}
之後再打stop即可停止錄影。


1.
hover(Location(s.getBottomRight())) #終於找到了之一,S=screen, hover 可以改成click等動作
hover(Location(s.getTopLeft()).offset(100,100))    #終於找到了之二,hover offset on second monitor

#來源網址 http://www.lai18.com/content/7527573.html
#screen capture
screen = Screen()
sc = screen.capture()
shutil.move(sc.getFilename(), os.path.join(os.path.abspath('.'), "some-name.png"))

2.
跟find()有關的
Find() # FindFailed exceptions
exists() #no exceptions
Region.exists() #returns False
setFindFailedResponse(PROMPT) # PROMPT/RETRY/SKIP/ABORT/HANDLE when not found you will be prompted. 這個超好用的,在發現findfailed的時候會跳出提示,真貼心。


註:http://sikulix-2014.readthedocs.io/en/latest/region.html#exception-findfailed

3.
在Sikuli呼叫JAVA
看樣子,jar在Jython裡面被視為是一個資料夾,所以用法如方法三。

參考網站:
http://techblog.leosoto.com/jython-import-logic/
https://puremonkey2010.blogspot.tw/2014/01/jython-using-jython-to-call-java.html


下面的Jython.classJython.jar是我自己建立的測試檔案,不是官網上的Jython.jar喔!!!
#Method 1. Jython.class in *.sikuli_folder\Jython.class
import class
#Method 2. Jython.class in *.sikuli_folder\jython\Jython.class
import jython.Jython
#Method 3. Jython.jar in ..\*.sikuli_folder\sikulix\lib\Jython.jar
 import sys sys.path.append(getBundlePath()+"\\Jython.jar") #宣告jar檔案的位置 from jython import Jython #from package import class j = Jython("kyc1109","TPE") j.hello()

------Jython.jar start----------------------------------------------
package jython; /** * * @author kyc1109 */ public class Jython { private String name; private String city; /** * @param name * @param city */ public Jython(String name, String city){ this.name = name; this.city = city; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public void hello() { System.out.println("Hi this is Java by hello()"); } public static void main(String[] args) { // TODO code application logic here System.out.println("Hi this is Java"); } }

------Jython.jar end----------------------------------------------

# for Multi-Monitor
for i in range(0,Screen.getNumberScreens()): #1 = Monitor2, 0 = Monitor 1 s= Screen(i) print i bounds=s.getBounds() print bounds hover(s) #move cursor to screen 1,2...



2017年3月14日 星期二

My Python note in Windows

My Python note in Windows

1. Python 已經內建pip,只需要update即可
C:\Python27\Scripts
python -m pip install -U pip

2. 透過pip安裝我常用的套件
pip install matplotlib BeautifulSoup selenium pandas requests bs4 jieba scikit-learn

3. 除了 scipy要另外單獨下載安裝
下載網址,注意他有for Python的版本喔!
http://www.lfd.uci.edu/~gohlke/pythonlibs/#scipy
pip install scipy-0.19.0-cp27-cp27m-win32.whl

另外,因為scipy是獨立安裝的關係吧,需要手動安裝numpy+MKL才行。
下載網址 http://www.lfd.uci.edu/~gohlke/pythonlibs/#numpy
pip install numpy‑1.11.3+mkl‑cp27‑cp27m‑win32.whl



以上筆記參考網址如下:
https://pip.pypa.io/en/latest/installing/#upgrading-pip
http://stackoverflow.com/questions/37267399/importerror-cannot-import-name-numpy-mkl

2016年10月26日 星期三

交通事故

今天2016/10/27早上約7:20~7:30。親眼目擊行經新北市汐止區吉林路口時,看到一位騎機車的婦人遭行經中興路的男子騎機車闖紅燈撞上。

不管事走路、騎車或開車,用路都要小心,阿彌陀佛。

2016年8月4日 星期四

Raspberry pi 網路資料筆記

raspberry + openCV 前置作業
http://yehnan.blogspot.tw/2015/12/raspberry-piraspbianopencv.html

直接安裝OpenCV的lib
sudo apt-get install libopencv-dev python-opencv

很棒的raspberry + openCV + camera 教學
https://www.raspberrypi.com.tw/tag/opencv/
https://www.slideshare.net/raspberrypi-tw/raspberry-pi-camera-python-opencv-day1
https://projects.raspberrypi.org/en/projects/getting-started-with-picamera

用Raspberry Pi學GPIO - 自己做遊戲機
http://www.slideshare.net/raspberrypi-tw/gpio-gameconsolestarterkit
PPT download
http://goo.gl/0nj2JB
sample code
http://goo.gl/BrPPP8

#開機就執行
#● 一次性的執行 , 可以放在 /etc/rc.local 裡
$ sudo nano /etc/rc.local
sudo python /home/pi/gpio-game-console/11_3-joystick_mapping_keyboard/joystick_mapping_keyboard.py &
#● 以服務的方式執行 , 需寫 systemd 設定檔
#新增 systemd 設定檔
$ sudo nano /lib/systemd/system/my_systemd.service
[Unit]
Description=Add a New Systemd
[Service]
ExecStart=/home/pi/my_systemd.sh
[Install]
WantedBy=multi-user.target
$ sudo systemctl daemon-reload
#● 有畫面的程式前景執行 , 用 LXDE 的 autostart
$ nano ~/.config/lxsession/LXDE-pi/autostart
@lxterminal -e /home/pi/gpio-game-console/11_3-joystick_mapping_keyboard/housenka.sh

#Q1 how to control PC

#http://blog.itist.tw/2016/03/clean-installation-and-setup-on-raspbian-jessie.html
#自動校時 (另一種方式就是用Server丟一個目前時間到Client,然後Clinet再照這個時間去設定)
sudo timedatectl set-ntp yes
sudo date 110121432016 #MMDDhhmmYYYY

# http://raspberrypihq.com/how-to-share-a-folder-with-a-windows-computer-from-a-raspberry-pi/
sudo apt-get -y update
sudo apt-get -y upgrade #更新的部分,不一定要進行如果你覺得你的系統穩定的話通常很多人是不會將系統進行更新免得產生額外問題,所以更新部分視情況決定就可以了。
sudo rpi-update
#xrdp port 3389
sudo apt-get install -y xrdp samba samba-common-bin
sudo shutdown now
sudo reboot
netstat -tlunp | grep mbd

sudo raspi-config
sudo chmod -R 777 Test

#---samba-------------------------------------------------------
sudo nano /etc/samba/smb.conf
    workgroup = WORKGROUP
    wins support = yes
    netbios=raspberryk
    dos charset = cp950
    display charset=utf8
    security=user
    passdb backend=tdbsam
    unix password sync  = yes
    passwd program      = /usr/bin/passwd %u
    pam password change = yes
    [pi]
        comment=Raspberry Pi
        path=/home/pi
        browseable=no
        writeable=Yes
        only guest=no
        create mask=0777
        directory mask=0777
        public=yes
    [PiShare]
        comment=Raspberry Pi Share
        path=/home/pi/share
        browseable=no
        writeable=Yes
        only guest=no
        create mask=0777
        directory mask=0777
        public=yes #public file or not

    [ICU]
        comment=Raspberry Pi ICU
        path=/home/pi/icu
        browseable=Yes
        writeable=Yes
        only guest=Yes
        create mask=0777
        directory mask=0777
        public=yes #public file or not

sudo smbpasswd -a pi #add user pi
sudo service samba restart
sudo /etc/init.d/samba restart
testparm  #查閱 smb.conf 的語法設定正確性


#---中文-------------------------------------------------------
# http://www.pcdiy.com.tw/detail/3773
#1.
sudo raspi-config
#Internationalisation Options -->Change Locale -->zh_TW.UTF-8
#2.
sudo apt-get install ttf-wqy-microhei ttf-wqy-zenhei xfonts-wqy
#3.
sudo apt-get install scim-chewing

#---OpenCV No need-------------------------------------------------------
# http://www.pyimagesearch.com/2016/04/18/install-guide-raspberry-pi-3-raspbian-jessie-opencv-3/
#We then need to install some developer tools, including CMake, which helps us configure the OpenCV build process:
sudo apt-get install build-essential cmake pkg-config
#Next, we need to install some image I/O packages that allow us to load various image file formats from disk. Examples of such file formats include JPEG, PNG, TIFF, etc.:
sudo apt-get install libjpeg-dev libtiff5-dev libjasper-dev libpng12-dev
#Just as we need image I/O packages, we also need video I/O packages. These libraries allow us to read various video file formats from disk as well as work directly with video streams:
sudo apt-get install libavcodec-dev libavformat-dev libswscale-dev libv4l-dev
sudo apt-get install libxvidcore-dev libx264-dev
#The OpenCV library comes with a sub-module named highgui  which is used to display images to our screen and build basic GUIs. In order to compile the highgui  module, we need to install the GTK development library:
sudo apt-get install libgtk2.0-dev
#Many operations inside of OpenCV (namely matrix operations) can be optimized further by installing a few extra dependencies:
sudo apt-get install libatlas-base-dev gfortran
#Lastly, let’s install both the Python 2.7 and Python 3 header files so we can compile OpenCV with Python bindings:
sudo apt-get install python2.7-dev python3-dev
#Now that we have our dependencies installed, let’s grab the 3.1.0  archive of OpenCV from the official OpenCV repository. (Note: As future versions of openCV are released, you can replace 3.1.0  with the latest version number):
cd ~
wget -O opencv.zip https://github.com/Itseez/opencv/archive/3.1.0.zip
unzip opencv.zip
#We’ll want the full install of OpenCV 3 (to have access to features such as SIFT and SURF, for instance), so we also need to grab the opencv_contrib repository as well:
wget -O opencv_contrib.zip https://github.com/Itseez/opencv_contrib/archive/3.1.0.zip
unzip opencv_contrib.zip
#Before we can start compiling OpenCV on our Raspberry Pi 3, we first need to install pip , a Python package manager:
wget https://bootstrap.pypa.io/get-pip.py
sudo python get-pip.py
#So, given that, what’s the point of using virtualenv  and virtualenvwrapper ?

#-----omnitty 批量管理多台linux介面-----------------------------------------------------
#require tool.
apt-get install libncurses5-dev
#http://omnitty.sourceforge.net/
# rote-0.2.8.tar.gz
./configure
make
make install
# omnitty-0.3.0.tar.gz
./configure
make
make install

#if error, try this.
#在/etc/ld.so.conf.d/下寫入一個omnitty.conf的檔案,內容寫入/usr/local/lib即可,之後重新執行/sbin/ldconfig
sudo echo /usr/local/lib > /etc/ld.so.conf.d/omnitty.conf
sudo ./sbin/ldconfig

#Added -lncurses and -ltinfo in Makefile of omnitty
#eg.
$(CC) $(CFLAGS)  -o omnitty $(objects) $(LDFLAGS) $(LIBS) -lncurses  -ltinfo




#-----Pi camera.py 這個似乎沒辦法透過Xming顯示(因為他是透過硬體?)-----------------------------------------------------
# https://www.raspberrypi.org/learning/getting-started-with-picamera/worksheet/
from picamera import PiCamera
from time import sleep
camera = PiCamera()
camera.rotation = 180
camera.start_preview()
sleep(10)
camera.stop_preview()

#-----Python camera.py 這個似乎可以透過Xming顯示 (因為他是透過軟體?) -----------------------------------------------------
不過很奇怪,有時候會無法開啟camera 會顯示 "error: (-215) size.width>0 && size.height>0 in function imshow"的錯誤訊息。
解決方法,重新載入驅動
sudo modprobe bcm2835-v4l2

其他指令如下
v4l2-ctl --list-devices
v4l2-ctl --list-formats
v4l2-ctl -L
#參考自 https://www.slideshare.net/raspberrypi-tw/raspberry-pi-camera-python-opencv-day1

import cv2, time
# reference https://gist.github.com/tedmiston/6060034
 cam = cv2.VideoCapture(0)#(0)
 cam.set(3,800) #reference https://stackoverflow.com/questions/11420748/setting-camera-parameters-in-opencv-python
 cam.set(4,600)
 while True:
  ret_val, img = cam.read()
  if mirror:
    img = cv2.flip(img, -1)
    img = cv2.flip(img, -1)
  cv2.imshow("webcam", img)
  if cv2.waitKey(1) == 27:
   break  # esc to quit
 cv2.destroyAllWindows()


#-----RPi-Cam-Web-Interface-----------------------------------------------------
#https://elinux.org/RPi-Cam-Web-Interface#Basic_Installation
    sudo apt-get update
    sudo apt-get dist-upgrade
    sudo rpi-update #Not recommand

    git clone https://github.com/silvanmelchior/RPi_Cam_Web_Interface.git
    cd RPi_Cam_Web_Interface
    ./install.sh

    sudo chmod 755 /etc/rc.local
    sudo reboot

    ./RPi_Cam_Web_Interface_Installer.sh

#-----模擬器-----------------------------------------------------
http://mstar.pixnet.net/blog/post/21804241-linux-%E4%B8%8B%E7%9A%84%E9%81%8A%E6%88%B2%E6%A9%9F%E6%A8%A1%E6%93%AC%E5%99%A8


#-----install utility-----------------------------------------------------
#rpm
sudo apt-get install alien
#7zip
sudo apt-get install p7zip
#unzip
7zr e file.zip
#player
sudo apt-get install smplayer
sudo apt-get install Rhythmbox


#Ubuntu : AVI, RMVB, MPEG, MP3 一次解決
#http://blog.xuite.net/chingwei/blog/27809648-%E3%80%90%E7%B3%BB%E7%B5%B1%E3%80%91Ubuntu+%3A+AVI,+RMVB,+MPEG,+MP3+%E4%B8%80%E6%AC%A1%E8%A7%A3%E6%B1%BA

sudo apt-get install gstreamer0.10-plugins-uglygstreamer0.10-plugins-bad gstreamer0.10-ffmpeg

#-----disable Pi camera LED-----------------------------------------------------
https://www.raspberrypi-spy.co.uk/2013/05/how-to-disable-the-red-led-on-the-pi-camera-module/
sudo nano /boot/config.txt
disable_camera_led=1

#-----install python module-----------------------------------------------------
pip3 install --upgrade pip
sudo pip3 install beautifulsoup4 html5lib pandas h5py keras numpy
pip install --upgrade tensorflow


#For pandas compile
sudo apt-get install gcc-arm-none-eabi

#-----install xming-----------------------------------------------------
sudo apt-get install -y lxde lightdm xinit

http://blog.jangmt.com/2009/11/xming.html
修改/etc/gdm/custom.conf,讓root可以使用
AllowRoot=true

#-----putty cmd-----------------------------------------------------
start putty -ssh yourIP  -X -l username -pw userpassword

The -X option turns on X11 forwarding in SSH, and -x turns it off. These options are only meaningful if you are using SSH.

#-----install tensorflow-----------------------------------------------------
pip install --upgrade tensorflow
or
#https://www.wandianshenme.com/play/howto-install-tensorflow-in-raspberry-pi-2/
wget https://github.com/samjabrahams/tensorflow-on-raspberry-pi/releases/download/v1.1.0/tensorflow-1.1.0-cp27-none-linux_armv7l.whl
sudo pip install tensorflow-1.1.0-cp27-none-linux_armv7l.whl

h
#-----proxy settings cmd-----------------------------------------------------
export http_proxy=http://ip:8080
export https_proxy=https://ip:8080

putty cmd: http://the.earth.li/~sgtatham/putty/0.53b/htmldoc/Chapter3.html#3.7.3

    cd /etc/apt/apt.conf.d
    sudo nano 10proxy
        Acquire::http::Proxy "http://ip:8080";
http://www.instructables.com/id/Adding-local-internet-proxy-settings-to-Raspberry-/
#-----Clean install all-----------------------------------------------------
sudo apt-get install -y alien p7zip xrdp samba samba-common-bin ttf-wqy-microhei ttf-wqy-zenhei xfonts-wqy scim-chewing lxde lightdm xinit python-opencv python-pip x11vnc

picamera doc
http://picamera.readthedocs.io/en/release-1.13/recipes1.html
#-----Clean script-----------------------------------------------------
sudo chmod +x /etc/rc.local #auto run

#-----auto run-----------------------------------------------------
/etc/rc.local # useless

#https://www.dexterindustries.com/howto/run-a-program-on-your-raspberry-pi-at-startup/

sudo nano /etc/init.d/myPiAutoRun.sh #OK

    #!/bin/bash
    ### BEGIN INIT INFO
    # Provides:          myPiAutoRun.sh
    # Required-Start:    $remote_fs $syslog
    # Required-Stop:     $remote_fs $syslog
    # Default-Start:     2 3 4 5
    # Default-Stop:      0 1 6
    # Short-Description: Start daemon at boot time
    # Description:       Enable service provided by daemon.
    ### END INIT INFO
    if [ -f "/home/pi/python/piCam/Pi_Camera_Photo_telegram.py"];then
        sudo /usr/bin/python3 /home/pi/python/piCam/Pi_Camera_Photo_telegram.py &
    fi
    exit 0
sudo chmod +x myPiAutoRun.sh
sudo update-rc.d myPiAutoRun.sh defaults

grep -rnw "/var/log/daemon.log" -e "myPiAutoRun" #check log

sudo nano /lib/systemd/system/myPiAutoRun.service #not yet
    [Unit]
    Description=myPiAutoRun
    After=multi-user.target
    Requires=network-online.target

    [Service]
    Type=idle
    ExecStart=/usr/bin/python3 /home/pi/python/piCam/Pi_Camera_Photo_telegram.py > /home/pi/python/piCam/Pi_Camera_Photo_telegram.log 2>&1
    #Restart=always

    [Install]
    WantedBy=multi-user.target

sudo chmod 644 /lib/systemd/system/myPiAutoRun.service
sudo systemctl enable myPiAutoRun.service
sudo systemctl start myPiAutoRun.service
sudo systemctl status myPiAutoRun
sudo systemctl daemon-reload

sudo reboot
systemctl status myPiAutoRun.service
journalctl -xn


#cmd

sudo reboot

#------localename-------------------------------
#https://github.com/spyder-ide/spyder/issues/4131

error message ValueError, 'unknown locale: %s' % localename

The problelm is solved. I installed the zh_TW.utf-8
with either "sudo locale-gen zh_TW.UTF-8" , or
"sudo dpkg-reconfigure locales" if the former does not work.

#---wlan cmd--------
sudo ifconfig wlan0 up
sudo iwlist wlan0 scan | grep ESSID
sudo iwconfig wlan0 essid ap_ssid key ap_key
sudo gedit /etc/wpa_supplicant/wpa_supplicant.conf
    network={
        ssid="AP_SSID"
        key_mgmt=WPA-PSK
        psk="AP_Key"
    }
sudo /etc/init.d/networking restart


sudo iw dev
sudo ip link set wlan0 up
sudo iw wlan0 scan
sudo wpa_passphrase blackMOREOps >> /etc/wpa_supplicant.conf
sudo wpa_supplicant -i wlan0 -c /etc/wpa_supplicant.conf
sudo iw wlan0 link
sudo dhclient wlan0
sudo ping 8.8.8.8

sudo iwconfig wlan0 txpower auto #change wlan0 power

#---ADSL pppoe cmd--------
sudo apt-get -y install pppoeconf

#---wlan auto connection--------
#https://weworkweplay.com/play/automatically-connect-a-raspberry-pi-to-a-wifi-network/
sudo nano /etc/network/interfaces
auto wlan0
auto eth0
sudo nano wpa-conf /etc/wpa_supplicant/wpa_supplicant.conf
iface default inet dhcp


2016年3月3日 星期四

Fedora 23 Note not finish yet !!!
# https://ask.fedoraproject.org/en/question/84212/grubx64efi-tftpboot-option-negotiation-failed-user-aborted-the-transmission/
# http://superuser.com/questions/1052455/grubx64-efi-tftpboot-option-negotiation-failed-user-aborted-the-transmission
# https://bugzilla.redhat.com/show_bug.cgi?id=1251600

#!/bin/bash

[Check list-status]
dhcp ipv4 ok
dhcp ipv6  Ping fail #https://www.ptt.cc/bbs/IPv6/M.1331661667.A.C61.html
tftp ok


CSM   IPv4  x86_x64 OK
uefi  IPv4  x86 NG
      IPv6  x64 NG

[Check list-Question]
how to configration dhcp.conf, pxe?

[Port]
tftp udp 68
dhcp udp 67
pxe udp 69

[command]
uname -r
netstat -nx
netstat -an |fgrep -w 67
chmod 675 folderName #r=4,w=2,x=1
chmod -R g=rw filename #[ugoa]=[rwx]
chgrp dhcpd
usermod -G groupName userName #join a user to group
useradd -G root admin #add a new user
http://linux.vbird.org/linux_basic/0210filepermission.php#chmod
cp -p -R
cat /proc/net/if_inet6
netstat -utlnp | grep named
/usr/sbin/dhcpd -6 -d -cf /etc/dhcp/dhcpd6.conf enp0s3

egrep "lease|hostname|hardware|\}" /var/lib/dhcpd/dhcpd.leases #dhcp list

chmod 675 -R /media/sf_ShareFolder
ln -s /media/sf_ShareFolder ./sf_ShareFolder
ln -s /etc/dhcp/dhcpd.conf ./dhcpd.conf
ln -s /etc/dhcp/dhcpd6.conf ./dhcpd6.conf
ln -s /var/lib/tftpboot ./tftpboot
ln -s /etc/radvd.conf .
ln -s /etc/dhcp6s.conf .
ln -s /etc/dhcp6c.conf .
ln -s /var/www/html ./html

dnf clean packages # remove cached packages

ausearch -m avc -ts recent
auditctl -w /etc/shadow -p w

Wireshark
ICMP, ICMPv6, DHCP, DHCPv6,TFTP
not nbns and not llmnr and not arp

[WLAN]
iwconfig
ifconfig wlp9s0 up

cat /var/log/messages #check system log

#!/bin/bash
#backup for fedora
tar -cizvf backup.tar.gz
#conf
/etc/radvd.conf
/etc/dhcp6s.conf
/etc/dhcp6c.conf
/etc/dhcp/dhcpd.conf
/etc/dhcp/dhcpd6.conf
/var/lib/tftpboot/
/etc/xinetd.d/tftp
/etc/mtftp
/etc/sysconfig/network
/etc/sysconfig/dhcpd
/etc/sysconfig/network
/etc/sysconfig/dhcpd

#file-cache
/var/cache/dnf
/etc/dnf
/var/lib/dnf
exit

#!/bin/bash
#restore
tar -xzvf backup.tar.gz -C /
exit

[vbox]
#no support vbox of kernel version
kernel-devel-4.4.2-301.fc23.x86_64

NIC1-bridge for PXE
  IPv4 192.168.1.1
  netmask 255.255.255.0
  gateway 192.168.1.1
  DNS 192.168.1.1
  Search Domain 192.168.1.1
  Routers Enable 只在使用這個連線的網路資源時,才使用此連線

  IPv6 3ffe:501:ffff:100::1
  前綴 64
  DNS ::1, fec0:0:0:fff::1, 3ffe:501:ffff:100::1
 
NIC2-NAT for WAN
  auto

#network-restart
/etc/init.d/network restart
/etc/selinux/config #Disable SELinux
# Server 2012
IP            2001:db8::1 / 64
Preferred DNS ::1
Alternate DNS fec0:0:0:fff::1
range6        2001:db8::


#get kernel version
uname -r
#裝完OS先裝這個 for vbox
dnf -y install gcc
dnf install kernel-devel-4.2.3-300.fc23.x86_64

[hostname]
hostnamectl set-hostname  --static "yourHostName"

[OS update]
http://www.tecmint.com/things-to-do-after-fedora-23-installation/#
dnf update

[X-windows]
http://www.server-world.info/en/note?os=Fedora_22&p=desktop&f=3
dnf -y group install "MATE Desktop"
echo "exec /usr/bin/mate-session" >> ~/.xinitrc
startx

#設定開機啟動至 GUI 模式(runlevel 5)
systemctl set-default graphical.target

[PXE]
https://docs.fedoraproject.org/en-US/Fedora/23/html/Installation_Guide/pxe-dhcpd.html

[PXE-dhcp IPv4]
https://docs.fedoraproject.org/en-US/Fedora/23/html/Installation_Guide/pxe-dhcpd.html
dnf install dhcp
/etc/dhcp/dhcpd.conf
systemctl start dhcpd
systemctl enable dhcpd #auto run in boot.
journalctl  --unit dhcpd  --since  -2m  --follow
#debug command
journalctl -xe


#No need, just for reference
#http://www.linuxquestions.org/questions/linux-networking-3/dhcpd-no-free-leases-361548/
#To initial dhcpd.leases, del /var/lib/dhcpd/dhcpd.leases and then reboot that will auto create
#touch /var/lib/dhcpd/dhcpd.leases

----- pluma /etc/dhcp/dhcpd.conf start--------
allow booting;
allow bootp;
option space PXE;
option PXE.mtftp-ip    code 1 = ip-address;
option PXE.mtftp-cport code 2 = unsigned integer 16;
option PXE.mtftp-sport code 3 = unsigned integer 16;
option PXE.mtftp-tmout code 4 = unsigned integer 8;
option PXE.mtftp-delay code 5 = unsigned integer 8;
option arch code 93 = unsigned integer 16;

subnet 192.168.1.0 netmask 255.255.255.0 {
interface enp0s3; # define eth0 to dhcp
range 192.168.1.10 192.168.1.200;
range dynamic-bootp 192.168.1.201 192.168.1.250;
authoritative;
default-lease-time 86400;
max-lease-time 86400;
option time-offset -18000; #Eastern Standard Time
ddns-update-style none;
option domain-name-servers 192.168.1.1;
option domain-name "ipc.linux";
option routers 192.168.1.1;
option broadcast-address 192.168.1.255;
option routers 192.168.1.1,8.8.8.8;

# https://docs.fedoraproject.org/en-US/Fedora/23/html/Installation_Guide/pxe-bootloader.html
# http://logout.sh/computers/linux/netboot/
class "pxeclients" {
                  match if substring (option vendor-class-identifier, 0, 9) = "PXEClient";
                  next-server 192.168.1.1;        #指定tftp server的位址        
                  if option arch = 00:02 {
                          filename "ia64/elilo.efi";
                  } else if option arch = 00:06 {
                          filename "uefi/bootia32.efi";
                  } else if option arch = 00:07 {
                          filename "uefi/bootx64.efi";
                          #filename "uefi/shim.efi"; #for secure boot
                  } else { #/var/lib/tftpboot/
                          filename "pxelinux.0";
                  }
          }

}
#next-server 192.168.1.1

#http://www.syslinux.org/wiki/index.php?title=PXELINUX
# .0    PXE bootstrap program (NBP) [PXELINUX only]
# .bin  "CD boot sector" [ISOLINUX only]
# .bs   Boot sector [SYSLINUX only]
# .bss  Boot sector, DOS superblock will be patched in [SYSLINUX only]
# .c32  COM32 image (32-bit COMBOOT)
# .cbt  COMBOOT image (not runnable from DOS)
# .com  COMBOOT image (runnable from DOS)
# .img  Disk image [ISOLINUX only]

# https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/7/html/Networking_Guide/sec-dhcp-configuring-server.html#config-file
----- /etc/dhcp/dhcpd.conf end--------


[PXE-dhcp IPv6-radvd]

#https://fedoraproject.org/wiki/IPv6Guide
dnf install radvd # if no radvd the client can't ping to DHCP server
systemctl enable radvd.service
systemctl start radvd.service
------- pluma /etc/radvd.conf start ------------
interface enp0s3
{
  AdvSendAdvert on;
  MinRtrAdvInterval 30;
  MaxRtrAdvInterval 100;
    AdvHomeAgentFlag off; #http://www.lijyyh.com/2012/05/dhcpv6ip-ciscolinux-isc-dhcpwindows.html
    AdvManagedFlag on;
    AdvOtherConfigFlag on;
  prefix 3ffe:501:ffff:100::/64
  {
    AdvOnLink on;
    AdvAutonomous on;
    AdvRouterAddr off;
  };
};
------- pluma /etc/radvd.conf end ------------

------- pluma /etc/dhcp6s.conf start ------------
interface enp0s3 {
link AAA {
    allow unicast;
    send unicast;
    allow rapid-commit;
    send server-preference 5;
    renew-time 1000;
    rebind-time 2400;
    prefer-life-time 2000;
    valid-life-time 3000;
    range 3ffe:501:ffff:100::10 to 3ffe:501:ffff:100::100/64;
    prefix 3ffe:501:ffff:100::/64;
    pool {
      prefer-life-time 3600;
      valid-life-time 7200;
      range 3ffe:501:ffff:100::10 to 3ffe:501:ffff:100::100/64;
      prefix fec0:fffe::/48;
    }
  }
}
------- pluma /etc/dhcp6s.conf end ------------

------- pluma /etc/dhcp6c.conf start ------------
interface enp0s3 {
  send rapid-commit;
  request prefix-delegation;
  request domain-name-servers;
  request temp-address;
  iaid 11111;
  address {
    3ffe:501:ffff:100::10/64;
    prefer-life-time 6000;
    valid-life-time 8000;
  };
  renew-time 11000;
  rebind-time 21000;
};
------- pluma /etc/dhcp6c.conf end ------------

[PXE-dhcp IPv6]

無狀態位址自動指派(Stateless Address Autoconfiguration, SLAAC)
無狀態DHCPv6(Stateless DHCPv6) 家用
全狀態DHCPv6(Stateful DHCPv6) 辦公室

DHCPv6(Stateless DHCPv6)

------- pluma /etc/sysconfig/network start -------
NETWORKING=yes
HOSTNAME=ipc.linux
# Enable IPv6 routing and stop accept_ra/autoconf.
NETWORING_IPV6=yes
IPV6FORWARDING=yes
------- pluma /etc/sysconfig/network end -------

#no needed
------- pluma /var/lib/tftpboot/uefi/grub.cfg start -------
set timeout=30
  menuentry 'RHEL' {
  linuxefi uefi/vmlinuz ip=dhcp #inst.repo=http://10.32.5.1/mnt/archive/RHEL-7/7.x/Server/x86_64/os/
  initrdefi uefi/initrd.img
}
------- /var/lib/tftpboot/uefi/grub.cfg end -------

# https://docs.fedoraproject.org/en-US/Fedora/22/html/Networking_Guide/sec-dhcp_for_ipv6_dhcpv6.html
pluma /etc/dhcp/dhcpd6.conf
/usr/sbin/dhcpd -6 -d -cf /etc/dhcp/dhcpd6.conf -user dhcpd -group dhcpd --no-pid enp0s3
systemctl --system daemon-reload
systemctl restart dhcpd.service
journalctl -xe

#need to modify the listen interface for dhcp and then reboot
echo "DHCPDARGS=\"enp0s3\";"  >> /etc/sysconfig/dhcpd # important

# /usr/share/doc/dhcp-server/dhcpd6.conf.example
-------pluma /etc/dhcp/dhcpd6.conf start -----------------------
allow booting;
allow bootp;
default-lease-time 2592000;
preferred-lifetime 604800;
max-lease-time 7200;
option dhcp-renewal-time 3600;
option dhcp-rebinding-time 7200;
option dhcp6.info-refresh-time 21600;
option dhcp6.name-servers 3ffe:501:ffff:100::1;
option dhcp6.domain-search "ipc.linux";
option dhcp6.bootfile-url code 59 = string;
# The subnet where the server is attached
#  (i.e., the server has an address in this subnet)
subnet6 3ffe:501:ffff:100::/64 {
  interface enp0s3; # define eth0 to dhcp
  # Two addresses available to clients
  # (the third client should get NoAddrsAvail)
  range6 3ffe:501:ffff:100::10 3ffe:501:ffff:100::100;
  # Use the whole /64 prefix for temporary addresses
  #  (i.e., direct application of RFC 4941)
  range6 3ffe:501:ffff:100:: temporary;
  # Some /64 prefixes available for Prefix Delegation (RFC 3633)
  prefix6 3ffe:501:ffff:100:: 3ffe:501:ffff:111:: /64;
  option dhcp6.name-servers 3ffe:501:ffff:100::1;
  option dhcp6.domain-search "ipc.linux";
  class "pxeclients" {
      match if substring (option vendor-class-identifier, 0, 9) = "PXEClient";    
      # using url via tftp only for IPv6          
      # http://www.ietf.org/assignments/dhcpv6-parameters/dhcpv6-parameters.txt
      if option dhcp6.client-arch-type = 00:06 { #efi x86
      option dhcp6.bootfile-url "tftp://[3ffe:501:ffff:100::1]/uefi/bootia32.efi";
      } else if option dhcp6.client-arch-type = 00:07 { #efi x64
      #option dhcp6.bootfile-url "tftp://[3ffe:501:ffff:100::1]/uefi/shim.efi"; # for secure boot
      option dhcp6.bootfile-url "tftp://[3ffe:501:ffff:100::1]/uefi/bootx64.efi";
      } else {
      option dhcp6.bootfile-url "tftp://[3ffe:501:ffff:100::1]/pxelinux.0";
      }
#https://docs.fedoraproject.org/en-US/Fedora/18/html/Installation_Guide/s1-netboot-pxe-config-efi.html                
  }

}
# IPv6 boot failed
# IPv4 error : couldn't send network packet
# IPv4 not authoritative for subnet


#https://docs.fedoraproject.org/en-US/Fedora/13/html/Deployment_Guide/s1-dhcp_for_ipv6_dhcpv6.html
-------/etc/dhcp/dhcpd6.conf end -----------------------


[PXE-tftp]
https://docs.fedoraproject.org/en-US/Fedora/23/html/Installation_Guide/pxe-dhcpd.html
dnf install tftp-server
systemctl start tftp.socket
systemctl enable tftp.socket

##tftp check
tftp localhost
tftp> get hello.txt

[Q&A]
PXE-E32: TFTP open timeout  --> 1. remove and then re-install again
                                2. disable and stop Firewall.service
                                3. hostname
#https://docs.oracle.com/cd/E19045-01/b200x.blade/817-5625-10/Linux_Troubleshooting.html
netstat -an | fgrep -w 67 # For DHCP
netstat -an | fgrep -w 69 # For tftp


# http://linux.vbird.org/linux_enterprise/0120installation.php#pxe_dhcp
-------pluma /etc/xinetd.d/tftp start -----------------------
service tftp
{
        Disable                = no
        socket_type            = dgram
        protocol               = udp
        wait                   = yes
        user                   = root
        server                 = /usr/sbin/in.tftpd
        server_args            = -u nobody -s /var/lib/tftpboot
        # -u 指定使用者, -s 指定要tdtp的目錄
        disable                = no
        per_source             = 11
        cps                    = 100 2
        flags                  = IPv4 IPv6
}
-------/etc/xinetd.d/tftp end -----------------------

#no needed
------- pluma /etc/mtftp start -----------------------
service mtftp
{
        socket_type            = dgram
        protocol               = udp
        wait                   = yes
        user                   = root
        server                 = /usr/sbin/in.mtftpd
        server_args            = /tftpboot
        disable                = no
        per_source             = 11
        cps                    = 100 2
        #flags                  = IPv4
}
-------/etc/xinetd.d/tftp end -----------------------



[PXE-clients]
https://docs.fedoraproject.org/en-US/Fedora/23/html/Installation_Guide/pxe-bootloader.html

dnf install syslinux

mkdir -p /var/lib/tftpboot/pxelinux.cfg
cp /usr/share/syslinux/{pxelinux.0,vesamenu.c32,ldlinux.c32,libcom32.c32,libutil.c32} /var/lib/tftpboot/
dnf install shim grub2-efi --installroot=/tmp/fedora --releasever 23

mkdir -p /var/lib/tftpboot/uefi
cp /tmp/fedora/boot/efi/EFI/fedora/{shim.efi,grubx64.efi} /var/lib/tftpboot/uefi/


#chmod 675 for tftpboot
#vmlinuz:就是安裝軟體的核心檔案 (kernel file);
#initrd.img:就是開機過程中所需要的核心模組參數;

# To be confirm ...如果是UEFI的SUT安裝,就得直接在/tftpboot/下建立一個efidefault的文字檔(因為目前CentOS 6.5直接放在pxelinux.cfg/下還是會有找不到檔案的問題)
----- pluma /var/lib/tftpboot/pxelinux.cfg/efidefault start------------------
# https://access.redhat.com/documentation/zh-TW/Red_Hat_Enterprise_Linux/6/html/Installation_Guide/s1-netboot-pxe-config-efi.html
default=0
timeout=60
splashimage=uefi/logo.xpm.gz
#hiddenmenu
title Fedora Installation
        root (nd)
        kernel f23/vmlinuz
        initrd f23/initrd.img
    #Fetching Netboot Image

    #initrd uefi/efiboot.img
    #error : couldn't send network packet

title UEFI boot
    root (nd)
    kernel grubx64.efi
    initrd uefi/efiboot.img


----- /var/lib/tftpboot/pxelinux.cfg/efidefault end--------------------------

----- pluma /var/lib/tftpboot/pxelinux.cfg/default start--------------------------
default vesamenu.c32
prompt 1
timeout 600
menu background logo.png
menu autoboot "Booting Default in #s"
menu title PXEboot menu

# install source
# https://access.redhat.com/documentation/zh-TW/Red_Hat_Enterprise_Linux/7/html/Installation_Guide/chap-anaconda-boot-options.html#sect-boot-options-installer

#item 1
label linux
menu label ^Install Fedora 23 64-bit
menu default
kernel f23/vmlinuz
append initrd=f23/initrd.img inst.stage2=http://download.fedoraproject.org/pub/fedora/linux/releases/23/Server/x86_64/os/ ip=dhcp
#item 2
label server
menu label ^Install Fedora 23 64-bit ( Minimal Image )
menu default
kernel f23/vmlinuz
append initrd=f23/initrd.img inst.stage2=http://download.fedoraproject.org/pub/fedora/linux/releases/23/Server/x86_64/os/ ip=dhcp ks=https://example.com/fedora/kickstarts/minimal.ks
#item 3
label rescue
menu label ^Rescue installed system 64-bit
kernel f23/vmlinuz
append initrd=f23initrd.img ip=dhcp root=live:http://download.fedoraproject.org/pub/fedora/linux/releases/23/Server/x86_64/os/LiveOS/squashfs.img rescue
#item 4
label local
menu label Boot from ^local drive
localboot 0xffff

# http://www.vercot.com/~serva/an/WindowsPXE1.html
# http://ftp.jaist.ac.jp/pub/Linux/Fedora/releases/23/Server/x86_64/os/isolinux/isolinux.cfg
# the main lable only has 5 items !?, using submenu for more items.

#item 5
# utilities submenu
menu begin ^Troubleshooting
menu title Troubleshooting

  label vesa
  menu indent count 5

  #item 5-1 (not yet)
  lable Win10
  menu label ^Install Windows 10 (not ready)
  com32 syslinux/linux.c32 /WinPE/wimboot/wimboot.x86_64
  append initrdfile=WinPE/bootmgr,WinPE/bcd,WinPE/boot.sdi,WinPE/pe_x64.wim

  #item 5-2
  label memtest
  menu label ^Run a memory test x86 (OK)
  kernel memtest

  #item 5-3
  label Floppy
  menu label ^Run a Floppy with Ram Disk x86 (OK)
  kernel syslinux/memdisk
  APPEND initrd=dos/fdboot.img floppy

  #item 5-4
  LABEL x86
  MENU LABEL 32Bit (x86)
  KERNEL syslinux/menu.c32
  APPEND pxelinux.cfg/x86.conf
 
  #item 5-5
  LABEL x64
    MENU LABEL 64Bit (x64)
    KERNEL syslinux/menu.c32
    APPEND pxelinux.cfg/x64.conf

  #item 5-6
  LABEL FreeDos
    MENU LABEL FreeDos x86 (not ready)
    COM32 syslinux/chain.c32
    KERNEL syslinux/menu.c32
    APPEND freedos="dos/kernel.sys"
#Initial menu has no LABEL entries.
# http://diddy.boot-land.net/pxe/files/imgs.htm

#item 5-6 (OK)
#http://www.howtogeek.com/162070/it-geek-how-to-network-boot-pxe-the-winpe-recovery-disk-with-pxelinux-v5-wimboot/
#https://technet.microsoft.com/en-us/library/cc753134(v=ws.10).aspx
  LABEL WinPE
    MENU LABEL WinPE (OK)
    #linux for WinPE boot utility
    com32 syslinux/linux.c32 /WinPE/wimboot/wimboot.x86_64
    #To load WinPE require files (bootmgr,bcd,boot.sdi and pe_x64.wim) in /var/lib/tftpboot/WinPE
    APPEND initrdfile=WinPE/bootmgr,WinPE/bcd,WinPE/boot.sdi,WinPE/pe_x64.wim

# cp -p /media/sf_ShareFolder/WinPE/* ./tftpboot/WinPE/
# chgrp root ./tftpboot/WinPE/*
# chmod 675 ./tftpboot/WinPE/*
# ls -l ./tftpboot/WinPE/

  label returntomain
  menu label Return to ^main menu
  menu exit
menu end
# add wimboot path, root is tftpboot folder
PATH WinPE/wimboot
-----/var/lib/tftpboot/pxelinux.cfg/default end--------------------------


# http://www.syslinux.org/wiki/index.php?title=PXELINUX
-----/var/lib/tftpboot/pxelinux.cfg/x86.conf start --------------------------
# Default boot option to use
  DEFAULT menu.c32
  # Prompt user for selection
  PROMPT 0
  # Menu Configuration
  MENU TITLE 32Bit (x86) OS Choice
  # Return to Main Menu
  LABEL MainMenu
    MENU DEFAULT
    MENU LABEL ^Main Menu
    KERNEL syslinux/menu.c32
  #
  # Blank boots
  #
  LABEL linux-43
    MENU LABEL ^Blank Boot 4.3
    KERNEL f23/vmlinuz
    APPEND initrd=f23/initrd.img
-----/var/lib/tftpboot/pxelinux.cfg/x86.conf end --------------------------


-----/var/lib/tftpboot/pxelinux.cfg/x64.conf start --------------------------
  # Default boot option to use
  DEFAULT menu.c32
  # Prompt user for selection
  PROMPT 0
  # Menu Configuration
  MENU TITLE 64Bit (x64) OS Choice
  # Return to Main Menu
  LABEL MainMenu
    MENU DEFAULT
    MENU LABEL ^Main Menu
    KERNEL syslinux/menu.c32
  #
  # Blank boots
  #
  LABEL linux-43
    MENU LABEL ^Blank Boot 4.3
    KERNEL f23/vmlinuz
    APPEND initrd=f23/initrd.img

-----/var/lib/tftpboot/pxelinux.cfg/x64.conf end --------------------------


--------(not used)---------- pluma /var/lib/tftpboot/pxelinux/uefi start --------------
function load_video {
insmod efi_gop
insmod efi_uga
insmod video_bochs
insmod video_cirrus
insmod all_video
}

load_video
set gfxpayload=keep
insmod gzio

menuentry 'Install Fedora 64-bit'  --class fedora --class gnu-linux --class gnu --class os {
linuxefi f23/vmlinuz ip=dhcp inst.repo=http://download.fedoraproject.org/pub/fedora/linux/releases/23/Server/x86_64/os/
initrdefi f23/initrd.img
}

menuentry 'Install Fedora 23 Server'  --class fedora --class gnu-linux --class gnu --class os {
kernel f23/vmlinuz
append initrd=f23/initrd.img inst.repo=http://download.fedoraproject.org/pub/fedora/linux/releases/23/Server/x86_64/os/ ip=dhcp ks=https://git.fedorahosted.org/cgit/spin-kickstarts.git/plain/fedora-install-server.ks?h=f21
}

menuentry 'Rescue installed system'  --class fedora --class gnu-linux --class gnu --class os {
kernel f23/vmlinuz
append f23/initrd=initrd.img root=live:http://download.fedoraproject.org/pub/fedora/linux/releases/23/Server/x86_64/os/LiveOS/squashfs.img rescue
}
--------(not used)----------/var/lib/tftpboot/pxelinux/uefi end----------------------

[ftp]
systemctl restart vsftpd
pluma /etc/vsftpd/vsftpd.conf

--------------- pluma /etc/xinetd.d/vsftpd start ---------------
service ftp
{
        socket_type             = stream
        wait                    = no
        user                    = anonymous #root
        server                  = /var/lib/tftpboot #/usr/sbin/vsftpd
        log_on_success          += DURATION USERID
        log_on_failure          += USERID
        nice                    = 10
        disable                 = no
}
--------------- pluma /etc/xinetd.d/vsftpd end ---------------

[PXE-kernel & initrd]
https://docs.fedoraproject.org/en-US/Fedora/23/html/Installation_Guide/pxe-kernel.html

 mkdir -p /var/lib/tftpboot/f23
 wget http://download.fedoraproject.org/pub/fedora/linux/releases/23/Server/x86_64/os/images/pxeboot/vmlinuz -O /var/lib/tftpboot/f23/vmlinuz
 wget http://download.fedoraproject.org/pub/fedora/linux/releases/23/Server/x86_64/os/images/pxeboot/initrd.img -O /var/lib/tftpboot/f23/initrd.img

[LDAP (no needed)]
#https://docs.fedoraproject.org/en-US/Fedora/23/html/System_Administrators_Guide/ch-Directory_Servers.html#s1-OpenLDAP
dnf install openldap-servers-2.4.40-14.fc23.x86_64
dnf install nss-pam-ldapd-0.8.14-5.fc23.x86_64
dnf install mod_ldap-2.4.18-1.fc23.x86_64

systemctl stop slapd.service
slappasswd
{SSHA}zq6z5sVg0xVrlmcBrAONySoXCFb2jfWb


---------- pluma /etc/openldap/ldap.conf start -----------
#http://blog.xuite.net/tolarku/blog/161523701-LDAP+%E5%AE%89%E8%A3%9D%E4%BB%8B%E7%B4%B9+-+CentOS+6.4+-+openldap
#
# See slapd.conf(5) for details on configuration options.
# This file should NOT be world readable.
#
include         /etc/openldap/schema/corba.schema
include         /etc/openldap/schema/core.schema
include         /etc/openldap/schema/cosine.schema
include         /etc/openldap/schema/duaconf.schema
include         /etc/openldap/schema/dyngroup.schema
include         /etc/openldap/schema/inetorgperson.schema
include         /etc/openldap/schema/java.schema
include         /etc/openldap/schema/misc.schema
include         /etc/openldap/schema/nis.schema
include         /etc/openldap/schema/openldap.schema
include         /etc/openldap/schema/ppolicy.schema
include         /etc/openldap/schema/collective.schema
# Allow LDAPv2 client connections.  This is NOT the default.
allow bind_v2
# Do not enable referrals until AFTER you have a working directory
# service AND an understanding of referrals.
#referral       ldap://root.openldap.org
pidfile         /var/run/openldap/slapd.pid
argsfile        /var/run/openldap/slapd.args
#在底下這行下指定 log 紀錄
loglevel        256
logfile        /var/log/slapd/ldap.log

# Load dynamic backend modules
# - modulepath is architecture dependent value (32/64-bit system)
# - back_sql.la overlay requires openldap-server-sql package
# - dyngroup.la and dynlist.la cannot be used at the same time
# modulepath /usr/lib/openldap
# modulepath /usr/lib64/openldap
# moduleload accesslog.la
# moduleload auditlog.la
# moduleload back_sql.la
# moduleload chain.la
# moduleload collect.la
# moduleload constraint.la
# moduleload dds.la
# moduleload deref.la
# moduleload dyngroup.la
# moduleload dynlist.la
# moduleload memberof.la
# moduleload pbind.la
# moduleload pcache.la
# moduleload ppolicy.la
# moduleload refint.la
# moduleload retcode.la
# moduleload rwm.la
# moduleload seqmod.la
# moduleload smbk5pwd.la
# moduleload sssvlv.la
# moduleload syncprov.la
# moduleload translucent.la
# moduleload unique.la
# moduleload valsort.la

# The next three lines allow use of TLS for encrypting connections using a
# dummy test certificate which you can generate by running
# /usr/libexec/openldap/generate-server-cert.sh. Your client software may balk
# at self-signed certificates, however.

#若有使用 SSL 憑證,則這個地方需修改
TLSCACertificatePath /etc/openldap/certs
TLSCertificateFile "\"OpenLDAP Server\""
TLSCertificateKeyFile /etc/openldap/certs/password

# Sample security restrictions
#       Require integrity protection (prevent hijacking)
#       Require 112-bit (3DES or better) encryption for updates
#       Require 63-bit encryption for simple bind
# security ssf=1 update_ssf=112 simple_bind=64

# Sample access control policy:
#       Root DSE: allow anyone to read it
#       Subschema (sub)entry DSE: allow anyone to read it
#       Other DSEs:
#               Allow self write access
#               Allow authenticated users read access
#               Allow anonymous users to authenticate
#       Directives needed to implement policy:
# access to dn.base="" by * read
# access to dn.base="cn=Subschema" by * read
# access to *
#       by self write
#       by users read
#       by anonymous auth
#
# if no access controls are present, the default policy
# allows anyone and everyone to read anything but restricts
# updates to rootdn.  (e.g., "access to * by * read")
#
# rootdn can always read and write EVERYTHING!

# enable on-the-fly configuration (cn=config)
database config
access to *
        by dn.exact="gidNumber=0+uidNumber=0,cn=peercred,cn=external,cn=auth" manage
        by * none
# enable server status monitoring (cn=monitor)
database monitor
access to *
        by dn.exact="gidNumber=0+uidNumber=0,cn=peercred,cn=external,cn=auth" read
        by dn.exact="cn=root,dc=ldap,dc=nthu,dc=org,dc=tw" read
        by * none
#增加底下這兩段
access to attrs=userPassword
       by self write
       #by anonymous auth
       by dn.base="cn=root,dc=ldap,dc=nthu,dc=org,dc=tw" write
       #by * none
#attrs=userPassword 限制 userPassword 只用於認證,只能用來做認證用,只有 user 自己才能修改密碼
#self write 允許使用者變更自己的密碼
#anonymous auth匿名用戶需要認證
#* none任何人都無法存取
access to *
       by self write
       by users read
       by dn.base="cn=root,dc=ldap,dc=nthu,dc=org,dc=tw" write
       #by * none

#######################################################################
# database definitions
#######################################################################
database        bdb
#suffix         "dc=my-domain,dc=com"
suffix          "dc=ipc,dc=linux,dc=com,dc=tw"
checkpoint      1024 15
#rootdn         "cn=Manager,dc=my-domain,dc=com"
rootdn          "cn=root,dc=ipc,dc=linux,dc=com,dc=tw"
# Cleartext passwords, especially for the rootdn, should
# be avoided.  See slappasswd(8) and slapd.conf(5) for details.
# Use of strong authentication encouraged.
# rootpw                secret
# rootpw                {crypt}ijFYNcSNctBYg
rootpw          {SSHA}zq6z5sVg0xVrlmcBrAONySoXCFb2jfWb
# The database directory MUST exist prior to running slapd AND
# should only be accessible by the slapd and slap tools.
# Mode 700 recommended.
directory       /var/lib/ldap
# Indices to maintain for this database
index objectClass                       eq,pres
index ou,cn,mail,surname,givenname      eq,pres,sub
index uidNumber,gidNumber,loginShell    eq,pres
index uid,memberUid                     eq,pres,sub
index nisMapName,nisMapEntry            eq,pres,sub
# Replicas of this database
#replogfile /var/lib/ldap/openldap-master-replog
#replica host=ldap-1.example.com:389 starttls=critical
#     bindmethod=sasl saslmech=GSSAPI
#     authcId=host/ldap-master.example.com@EXAMPLE.COM
---------- pluma /etc/openldap/ldap.conf end -----------

[Firewall]
# http://iori.tw/%E6%9E%B6%E8%A8%ADuefiipv6%E7%92%B0%E5%A2%83%E7%9A%84pxe-server-under-the-rhel-6-x/


pluma /etc/sysconfig/selinux -> Enabled after rebooting system
SELINUX=disabled



[dnsmasq No need, only for reference]
systemctl restart dnsmasq.service

------------- pluma /etc/dnsmasq.conf start --------------
interface=enp0s3
bind-interfaces
dhcp-range=192.168.1.10,192.168.1.200
dhcp-boot=grubnetx64.efi.signed
enable-tftp
tftp-root=/srv/tftp/
------------- /etc/dnsmasq.conf end --------------

[PXE-dns No need, only for reference]
/etc/resolv.conf
--------/etc/resolv.conf start ------------------
search 192.168.1.1 linux
domain ipc.linux
nameserver 192.168.0.1
nameserver 192.168.1.1
---------/etc/resolv.conf end-----------------

[DNS BIND]

---------- pluma /etc/named.conf start -------------
//
// named.conf
//
// Provided by Red Hat bind package to configure the ISC BIND named(8) DNS
// server as a caching only nameserver (as a localhost DNS resolver only).
//
// See /usr/share/doc/bind*/sample/ for example named configuration files.
//

options {
  listen-on port 53 { any; };
  listen-on-v6 port 53 { ::1; };
  directory   "/var/named";
  dump-file   "/var/named/data/cache_dump.db";
  statistics-file "/var/named/data/named_stats.txt";
  memstatistics-file "/var/named/data/named_mem_stats.txt";
  allow-query     { localhost; 192.168.1.1/24; };

  /*
   - If you are building an AUTHORITATIVE DNS server, do NOT enable recursion.
   - If you are building a RECURSIVE (caching) DNS server, you need to enable
     recursion.
   - If your recursive DNS server has a public IP address, you MUST enable access
     control to limit queries to your legitimate users. Failing to do so will
     cause your server to become part of large scale DNS amplification
     attacks. Implementing BCP38 within your network would greatly
     reduce such attack surface
  */
  recursion yes;

  dnssec-enable yes;
  dnssec-validation yes;

  /* Path to ISC DLV key */
  bindkeys-file "/etc/named.iscdlv.key";

  managed-keys-directory "/var/named/dynamic";

  pid-file "/run/named/named.pid";
  session-keyfile "/run/named/session.key";

    /* https://fedoraproject.org/wiki/Changes/CryptoPolicy */
    include "/etc/crypto-policies/back-ends/bind.config";
};

logging {
        channel default_debug {
                file "data/named.run";
                severity dynamic;
        };
};

zone "." IN {
  type hint;
  file "named.ca";
};

include "/etc/named.rfc1912.zones";
include "/etc/named.root.key";


---------- pluma /etc/named.conf end -------------


---------- pluma /etc/named.rfc1912.zones start -------------
// named.rfc1912.zones:
//
// Provided by Red Hat caching-nameserver package
//
// ISC BIND named zone configuration for zones recommended by
// RFC 1912 section 4.1 : localhost TLDs and address zones
// and http://www.ietf.org/internet-drafts/draft-ietf-dnsop-default-local-zones-02.txt
// (c)2007 R W Franks
//
// See /usr/share/doc/bind*/sample/ for example named configuration files.
//

zone "localhost.localdomain" IN {
  type master;
  file "named.localhost";
  allow-update { none; };
};

zone "localhost" IN {
  type master;
  file "named.localhost";
  allow-update { none; };
};

zone "1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.ip6.arpa" IN {
  type master;
  file "named.loopback";
  allow-update { none; };
};

zone "1.0.0.127.in-addr.arpa" IN {
  type master;
  file "named.loopback";
  allow-update { none; };
};

zone "0.in-addr.arpa" IN {
  type master;
  file "named.empty";
  allow-update { none; };
};

zone "ipc.linux" IN {
  type master;
  file "ipc.linux.zone";
  allow-update { none; };
};

---------- pluma /etc/named.rfc1912.zones end -------------