顯示具有 Linux Related 標籤的文章。 顯示所有文章
顯示具有 Linux Related 標籤的文章。 顯示所有文章

2019年5月22日 星期三

[Linux Shell Script] A script for parsing file, writing logs, archiving logs and taking args

We need a shell script to execute HTTP request on demand. This script shall read/parse text file and write/archive logs.
  • 3 sub functions
    1. get_script_dir : Get current folder path of this script
    2. echos : Write message to STDOut and log file
    3. archive_logs : Archive old logs to .tar
#!/bin/bash

# Functions
get_script_dir () 
{
 SOURCE="${BASH_SOURCE[0]}"
# While $SOURCE is a symlink, resolve it
 while [ -h "$SOURCE" ]; do
  DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
  SOURCE="$( readlink "$SOURCE" )"
# If $SOURCE was a relative symlink (so no "/" as prefix, need to resolve it relative to the symlink base directory
  [[ $SOURCE != /* ]] && SOURCE="$DIR/$SOURCE"
 done
 DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
 echo "$DIR/"
}

# DateFormat in log file : "[YYYY/MM/DD H:M:S]"
logDate=`date "+%Y%m%d"`
logFolder="$(get_script_dir)Logs/"

if [ ! -d $logFolder ]; then
 mkdir $logFolder
fi
logFile="${logFolder}CGI_Controller_${logDate}.log"

# Append STD out to file additionaly
echos ()
{
 logTime=`date "+%H:%M:%S"`
 builtin echo "[$logTime] $@" | tee -a "$logFile"
}

archive_logs()
{
 currentDate=`date "+%Y%m%d"`
 array=( $( ls ${logFolder} ) )
# Explicitly report array content.
 let i=0
 while (( ${#array[@]} > i )); do
 # echos "${i} ${array[i++]}"
 if [[ ${array[i]} == CGI_Controller_$currentDate* ]] || [[ ${array[i]} == zips ]]; then
  echos "The log is in the Current month, skipped it!"
 else
# Get target year and month for sufix of archived file name
  targetDate=`cut -d"_" -f 3 <<< "${array[i]}"`;
  targetDate=`cut -d"." -f 1 <<< $targetDate`;
  targetMonth="${targetDate:0:6}";
  zipFolder="$(get_script_dir)Logs/zips/"
  archivedFile="${zipFolder}Archived_${targetMonth}.tar.gz"
  if [ ! -d $zipFolder ]; then
   mkdir $zipFolder
  fi
  if [ -f "$archivedFile" ];then
   tar -rf $archivedFile --directory="${logFolder}" "${array[i]}" 
  else
   tar -cf $archivedFile --directory="${logFolder}" "${array[i]}" 
  fi
  echos "Archive file ${array[i]} to ${archivedFile}";
  rm "${logFolder}${array[i]}"
 fi
 ((i++))
 done
}
  • Main function
    1. Check if necessary files exist
    2. Check if parameter is valid
    3. Load setting file into an array
    4. Parsing settings and assemble CGI link
    5. Check server IP is UP
    6. Execute commands
# Main
# Check parameter number
if [ $# -ne 0 ]; then
 cmdI=$1
else
 echos "Parameter not found";
 exit 3
fi
# CMD array for each NVR
declare -a cmdArray

# Check if setting file existed
file="$(get_script_dir)config.txt"
if [ -f "$file" ];then
 echos "$file found";
else
 echos "$file not found, please create one";
 exit 4
fi

# Load file into array.
let i=0
while IFS=$'\n' read -r line_data; do
 cmdArray[i]="${line_data}"
((++i))
done < $file

# Roll back to item number
((--i))

if [ $i -le 0 ];then
 echos "No settings found in $file, please add CGI settings in this file. ([IP],[Path for Open],[Path for Close])";
 exit 5
fi

# Explicitly report array content.
#let i=0
#while (( ${#cmdArray[@]} > i )); do
# printf "${i} ${cmdArray[i++]}\n"
#done

# Make sure command number is less than settings number
if [ $cmdI -lt $i ]; then
 ip="$(cut -d';' -f1 <<<"${cmdArray[cmdI]}")"
 openPath="$(cut -d';' -f2 <<<"${cmdArray[cmdI]}")"
 closePath="$(cut -d';' -f3 <<<"${cmdArray[cmdI]}")"

 printf "${cmdI} ${cmdArray[cmdI]}\n"

 # Ping IP before executing it
 ping -c 1 -W 1 ${ip} &> /dev/null && result=0 || result=1

 if [ "${result}" == 0 ]; then
  echos "Server ${ip} is UP.";
 else
  echos "Server ${ip} is DOWN.";
  exit 6
 fi

 res="${logFolder}res"
 echos "http://${ip}${openPath}";
 wget -O $res "http://${ip}${openPath}";
 echos `cat $res`;
 # Delay 1 sec and then execute 2nd CGI command
 sleep 1
 echos "http://${ip}${closePath}";
 wget -O $res "http://${ip}${closePath}";
 echos `cat $res`;
 rm $res;
else
 echos "Parameter value is bigger than settings";
 exit 7
fi
archive_logs

2015年7月8日 星期三

[Linux] Execute other cmd from cmd 'find'

將目錄下所有size=0之檔案,調整其權限為777 "rwxrwxrwx"

find . -type f -size 0k -exec chmod 777 {} ;

將目錄下所有權限非777 "rwxrwxrwx"之檔案都列出

find . -type f ! -perm 777;

2014年11月5日 星期三

2014年6月12日 星期四

[Synology] Crontab settings

於Synology DS211j 中增加例行工作

vi /etc/crontab

#minute hour    mday    month   wday    who     command
17      8       *       *       2,5     root    /usr/bin/php -n -d safe_mode_exec_dir='' /usr/syno/bin/autoupdate.php
14      5       *       *       2,5     root    /usr/syno/bin/synopkg chkupgradepkg
0       0       *       *       3       root    /var/packages/AntiVirus/target/bin/synoavscan --all
0       3       *       *       *       root    /usr/syno/bin/syno_poweroff_feasible_check

修改後,儲存離開,並執行下列指令

synoservice -restart crond

2014年6月10日 星期二

[Synology] PHP exec disable

於Synology裡,在PHP中使用exec時,碰到 exec()無法使用的情況,需依照下列步驟處理。

修改下列檔案
/usr/syno/etc/php.ini
/usr/syno/etc/php/user-setting.ini

將下面這行設定
safe_mode_exec_dir = /usr/syno/bin
修改為
safe_mode_exec_dir =  

Apache重啟
/usr/syno/etc/rc.d/S97apache-user.sh restart 


p.s. 我使用的是Synology DS211j 機器 - DSM 4.3的版本

2012年11月5日 星期一

Linux vi 存檔錯誤

File-encodings setting (notice the plural) does not include utf-8, so Vim does not try to save it with that encoding. It probably either tries to save it using plain old ASCII encoding or something like latin1, which does not include this char and therefore conversion fails. 
You should fix your 'fencs' setting to something like ucs-bom,utf-8,default,latin1 or you can force Vim to save it in utf-8 encoding, by issuing :w ++enc=utf8 filename. (It might be, that this needs the +multi_byte feature, which is only enabled, when compiling at least a big version of Vim). 

簡單的說就是檔案含有UTF-8的內容,vim存檔時沒有使用UTF-8的encoding存檔所產生的錯誤。

解決方法只需在存檔時加入一個option即可,如下:

:w ++enc=utf8 FileName

2012年9月12日 星期三

System Update Error "Failed to fetch http://..."

當在做系統update時,出現無法Fetch....的錯誤訊息時,可嘗試下列commands


First confirm that you are able to browse other websites. 
Then, Run this commands:  sudo mv /var/lib/apt/lists{,bakjune4};
sudo mv /var/cache/apt/archives/partial{,bakjune4};
sudo apt-get update;
sudo apt-get upgrade;  


Linux Terminal 快捷鍵

Paste copied Text : [Shift] + [Insert]
Stop : [Ctrl] + [C]
Paste High Lighted Text : [Middle button]
Create New Terminal Tab : [Ctrl] + [T]
Switch Terminal Tabs : [Alt] + [#(Number)]
Close Current Terminal Tab : [Ctrl] + [Shift] + [W]

待續...

2012年5月23日 星期三

Linux環境下 console模式下抓封包



我的使用方式,開兩個terminals,一個執行
$ tcpdump -i eth0 -w abc.cap

另一個執行
$ tcpdump -r abc.cap 

使用tcpdump指令3個會用到的options


Ex.抓封包存入abc.cap檔案
$ tcpdump -i eth0 -w abc.cap 

Ex. 抓封包,分割每個儲存的封包(size 1500bytes)
$ tcpdump -i eth0 -s 1500 -w a.cap 

Ex. 讀封包
$ tcpdump -r abc.cap 

p.s. 必須使用root權限

2012年3月15日 星期四

Linux ~/.vimrc 設定

原文網址

在 Terminal中輸入
gvim ~/.vimrc
可設定以下內容 (以下是我個人的設定)

syntax on                           " 語法上色顯示
set ai              "自動縮排
set tabstop=2        " 設定縮排寬度 = 2
set softtabstop=2    " tab 的字元數
set shiftwidth=2           
set ruler            " 顯示右下角設定值
set ic               " 設定搜尋忽略大小寫
set ru               " 第幾行第幾個字
set hlsearc          " 設定高亮度顯示搜尋結果
set incsearch        " 在關鍵字還沒完全輸入完畢前就顯示結果
set smartindent
set history=100      " 保留 100 個使用過的指令

set nocp



colorscheme torte 

2012年3月14日 星期三

Linux File Time (atime, ctime, mtime)

st_atime
           Time when file data was last accessed. Changed by  the
           following   functions:   creat(),   mknod(),   pipe(),
           utime(2), and read(2).

st_mtime
           Time when data was last modified. Changed by the  fol-
           lowing  functions:  creat(), mknod(), pipe(), utime(),
           and write(2).

st_ctime
           Time when file status was last changed. Changed by the
           following   functions:   chmod(),   chown(),  creat(),
           link(2),  mknod(),  pipe(),  unlink(2),  utime(),  and
           write().


指令可使用
stat -c %x filename
stat -c %y filename
stat -c %z filename
或者
ls -lu  filename
ls -l    filename
ls -lc  filename


-lu    show access time and sort by name
-l     show modified time and sort by name
-lc   show ctime and sort by name

%x   Time of last access
%y   Time of last modification
%z   Time of last change

2012年3月12日 星期一

簡易 Linux FTP upload shell

簡易的FTP 檔案上傳Shell script


於Terminal中,輸入
gvim ftpUpload.sh
並輸入下列內容於此檔案
#!/bin/bash
echo file(s) upload $*;
ftp -v -i -n FTP位址 << FTPIT
user 帳戶 密碼
bin
cd /切換至要放上傳檔案的目錄
mput $*
quit
FTPIT
exit 0
存檔離開,並改變此檔案的屬性
chmod 755 ftpUpload.sh
最後,執行
./ftpUpload.sh file1.txt file2.doc file3.mov

p.s. 後面帶的參數即為要傳送的檔案名,而$*則為儲存所有arg的變數(以空格區隔)

Gvim plugin安裝於Ubuntu



以下內容出自上面原文,我再加上修改後,可於Ubuntu上安裝成功

註解程式快捷鍵plugin

於Terminal中輸入下列指令
sudo apt-get install vim-addon-manager vim-scripts
vim-addons install enhanced-commentify
即可
於Gvim中,將游標移至想要註解的那一行後按下
\+x
若要往下一行繼續註解,則按下
\+c

2012年3月6日 星期二

Ubuntu Wifi Hotspot不斷連線 斷線

在Ubuntu 11.10的版本,建立Hotspot後會不停的斷線與連線問題,嘗試了很多解法後,下面方法可以workable !
原文連結--> Cannot make Wi-Fi hotspot

1. go to System settings > Network > Wireless > Use as hotspot > Configure (or 'Edit connections' under your connections > Edit the hotspot connection)
2. Switch to IPv6 Settings tab > Set Method to 'Ignore' and confirm/save
3. in terminal (Ctrl + Alt + T) run the following command to kill all dnsmasq processes: sudo killall dnsmasq
4. go to System settings > Network > Wireless > Use as hotspot

2012年3月2日 星期五

Install PHP5 on Ubuntu

在Ubuntu上安裝PHP5

sudo apt-get install apache2
sudo apt-get install php5
sudo apt-get install libapache2-mod-php5
sudo /etc/init.d/apache2 restart

網頁存放的目錄是
/var/www/

本機端瀏覽的方式很容易只要在瀏覽器網址輸入
http://localhost
即可

2012年3月1日 星期四

Ubuntu 使用Root 帳號權限

1. 打開terminal

2. sudo -i 登入root後 

3. passwd更改root密碼

4. 之後即可使用 su 切換root

Ubuntu 11.10 輸入法設定

1. 先
apt-get install gcin
2. 然後點擊左上角Dash Board主目錄
3. 在搜尋框輸入ibus
4. 下方會出現Keyboard Input Method


點擊進入即可設定

2011年5月16日 星期一

[轉貼]Emesene 2於Ubuntu上安裝方式

原文網址Install Emesene 2 (2.11.4) in Ubuntu

由於使用Ubuntu內建的Ubuntu軟體中心安裝的是舊版的Emesene,所以上網找了一下方法來安裝Emesene 2。

我使用的環境是Ubuntu 10.04 32-bit

方式簡略如下
(若已安裝舊版的Emesene,請先移除)
1. 打開terminal

2. 依序輸入下列指令
   sudo add-apt-repository ppa:webupd8team/unstable
   sudo apt-get update
   sudo apt-get install emesene
(若已是root權限,以上指令可不用加sudo)

3. 當提示詢問是否安裝時,請輸入Y即可

2011年2月12日 星期六

在Ubuntu上安裝Qt之基本lib pkg


在configure Qt之前最好先安裝以下pkg


sudo apt-get install libX11-dev libXext-dev libXtst-dev libxrender-dev

2011年1月20日 星期四

[轉貼] Ubuntu 安裝 黑屏問題


在HP TouchSmart tm2 機器上嘗試安裝Ubuntu,安裝過程中出現黑屏之解決方式 


黑屏情況
用CD開機(or USB)的時候,進入選單安裝時即黑屏 或 載入安裝資料後即黑屏

以下是我的情況(參照原文網址的解法)


ubuntu安裝
1.開機後,一出現畫面時按鍵盤任一鍵,使ubuntu的安裝選單畫面出來
2.選完語言後再用上下鍵移動光條選到安裝的選項, 然後按下F6鍵, 勾選nomodeset,再按esc跳出來.
3.這個時候螢幕下方會有一行"開機選項",後面跟著一串能編輯的文字, 請找到"quite splash --",
並在splash這個字之後空一格, 輸入xforcevesa
4.按enter繼續執行試用或安裝.



安裝完系統,重開機,進入選單時
按e編輯選單
一樣找到"quite splash " 在後面加上 nomodeset xforcevesa 
然後按ctrl+x開機


進入系統後
打開Terminal
輸入sudo su,切換到root權限
cd /boot/grub
cp grub.cfg grub.cfg.bk
vi grub.cfg.bk
使用vi搜尋 quiet splash
一樣在後面加入 nomodeset xforcevesa
存檔後離開vi
最後把剛剛編輯的grub.cfg.bk覆蓋掉系統的grub.cfg檔
cp grub.cfg.bk grub.cfg
reboot
即可!

搜尋此網誌