2012年12月26日 星期三

使用apt-get安裝軟體不顯示提示輸入欄位(unattended)

最近在安裝chef時總是需要輸入一些資料,例如管理者密碼、本機網址等等
這個提示用意很好,但是在做自動化安裝時我們常常需要的是不需人工介入
因此就這好意就變成了困擾
在網路上找了一堆作法,經過測試後只有以下的作法才有用
先設定環境變數
export DEBIAN_FRONTEND=noninteractive
接著使用以下的指令做安裝軟體(${pkg_name}請填上您的軟體名稱)
apt-get -y -q install ${pkg_name}

2012年12月20日 星期四

Ubuntu遠端桌面伺服器

我需要的是一個類似Windows Remote Desktop的遠端桌面軟體
意即是"開機後,不需使用者登入,遠端桌面伺服器即啟動,且遠端與本地端的畫面是一樣的"
以下是我設定的方式

安裝軟體
sudo apt-get -y install x11vnc

讓啟動X11vnc的指令開機時執行
編輯/etc/rc.local並加入以下的指令
x11vnc -auth /var/run/lightdm/root/:0 -display :0 -forever &
PS. 如果需設定桌面小大,可以再加上"-geometry 1024x768"的參數

接著使用vncviewer連到${your_server_ip}:0就可以了

好玩的是還可以再用Ubuntu內建的Desktop sharing做同步分享出去喔!

參考資料連結如下:
http://marcelozambranav.blogspot.com/2011/11/configure-x11vnc-in-ubuntu-1110-aka.html
http://ubuntuguide.org/wiki/Ubuntu_Oneiric_Remote_Access#Remote_Access

2012年12月18日 星期二

密碼強度檢查方式比較

在http://www.checkio.org/上參加了用python解題的遊戲
第一個題目就讓我很感興趣
題目是要寫一隻程式去檢查密碼的強度
條件一:字串長度大於10
條件二:必需包含數字
條件三:必需包含小寫字母
條件四:必需包含大寫字母
我的解法是method1,但看了其他人的解法後不知道效率如何
於是寫了下面的程式去比較
其他的方法是依別人的解法去稍做修改,儘量不修改到程式,以求測試正確
#!/usr/bin/env python

import re
import string
import timeit

data_list = ['A1213pokl', 'bAse730onE', 'asasasasasasasaas', 'QWERTYqwerty', '123456123456', 'QwErTy911poqqqq']

def method1():
    global data_list

    for str in data_list:
        if len(str) >= 10 and re.match('.*([0-9]){1,}.*', str) and re.match('.*([a-z]){1,}.*', str) and re.match('.*([A-Z]){1,}.*', str):
            pass
        else:
            pass

    return True

def method2():
    global data_list

    for str in data_list:
        if len(str) >= 10 and filter(lambda a:a.isupper(), str) and filter(lambda a:a.islower(), str) and filter(lambda a:a.isdigit(), str):
            pass
        else:
            pass

    return True

def method3():
    global data_list

    for str in data_list:
        digit = upper = lower = False

        if len(str) < 10:
           pass
        else:
            for s in str:
                if s in string.ascii_lowercase:
                   lower = True
                if s in string.ascii_uppercase:
                    upper = True
                if s in string.digits:
                    digit = True
            if lower and upper and digit:
                pass
            else:
                pass

    return True

def method4():
    global data_list

    expr = re.compile("^.*(?=.{10,})(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).*$")

    for str in data_list:
        bool(expr.findall(str))

    return True

def method5():
    global data_list

    for str in data_list:
        bool(re.match('((?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{10})', str))

    return True

def method6():
    global data_list

    expr = re.compile('((?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{10})')

    for str in data_list:
        bool(expr.match(str))

    return True

t = timeit.Timer(method1)
print "method1", t.timeit()

t = timeit.Timer(method2)
print "method2", t.timeit()

t = timeit.Timer(method3)
print "method3", t.timeit()

t = timeit.Timer(method4)
print "method4", t.timeit()

t = timeit.Timer(method5)
print "method5", t.timeit()

t = timeit.Timer(method6)
print "method6", t.timeit()

測試出來的結果
method1 22.0549740791
method2 28.7450380325
method3 24.3238689899
method4 15.9753398895
method5 12.3819229603
method6 7.79946398735

所以看來使用正規表示式理論上是比較快的
但是前提是要看得懂
如果需要對大量的資料做正規表示式的比對
使用re.compile後的結果速度會快很多
但只有少數使用我想差距不大吧
但究竟是多少數,可能還要看正規表示式的內容跟數量才能做決定吧!

2012年11月21日 星期三

Prevent django form class cache data

import os
from django import forms

class FileSelector(forms.Form):
    file_list = forms.ChoiceField(label "Files")

    def __init__(self):
        self.fields['file_list'].choices = [(f, f) for f in os.listdir(".") if os.path.isfile(f)]

2012年10月26日 星期五

Force write temporary file to disk while uploading in django

vim setting.py
FILE_UPLOAD_MAX_MEMORY_SIZE=0
FILE_UPLOAD_TEMP_DIR=/tmp
FILE_UPLOAD_PERMISSIONS=0644
If you do not want to use memory for cache, just set the FILE_UPLOAD_MAX_MEMORY_SIZE to 0. And all file will be uploaded with a temporary file.

Disable file upload limitation in apache

vim /etc/httpd/conf/httpd.conf
LimitRequestBody 0

If you does not have this setting, it will set to 2G as default.

Create a usb key with grub multiboot from iso files

Create a bootable usb key:
Use fdisk to partition usb key and toggle bootable.
fdisk ${usb_key_device}
d => delete partition
n => create partition
a => toggle bootable flag
w => write change to device

Format file system to fat32
mkfs.vfat -F 32 -n ${usb_key_label} ${usb_key_device}

Mount usb key
mkdir -p ${abs_mount_point}
mount ${usb_key_device} ${abs_mount_point}

Install grub to usb key
grub-install --force --no-floppy --root-directory=${abs_mount_point} --boot-directory=${abs_mount_point} ${usb_key_device}

Edit grub configuration
vim ${abs_mount_point}/grub/grub.cfg
set default=0
set timeout=10

function mount_iso {
    loopback loop ${1}
}

menuentry "Tinycore ISO" {
    set src=/tinycore.iso
    mount_iso ${src}
    linux (loop)/boot/vmlinuz base superuser quiet waitusb=5
    initrd (loop)/boot/core.gz
}

menuentry "Ubuntu 12.04.1 i386" {
    set src=/ubuntu-12.04.1-dvd-i386.iso
    mount_iso ${src}
    linux (loop)/casper/vmlinuz boot=casper file=/cdrom/preseed/ubuntu.seed iso-scan/filename=${src} only-ubiquity quiet splash --
    initrd (loop)/casper/initrd.lz
}

menuentry "Ubuntu 12.04.1 amd64" {
    set src=/ubuntu-12.04.1-dvd-amd64.iso
    mount_iso ${src}
    linux (loop)/casper/vmlinuz boot=casper file=/cdrom/preseed/ubuntu.seed iso-scan/filename=${src} only-ubiquity quiet splash --
    initrd (loop)/casper/initrd.lz
}
menuentry "Ubuntu 12.10 Desktop i386" {
    set src=/ubuntu-12.10-desktop-i386.iso
    mount_iso ${src}
    linux (loop)/casper/vmlinuz boot=casper file=/cdrom/preseed/ubuntu.seed iso-scan/filename=${src} only-ubiquity quiet splash --
    initrd (loop)/casper/initrd.lz
}

menuentry "Ubuntu 12.10 Desktop amd64" {
    set src=/ubuntu-12.10-desktop-amd64.iso
    mount_iso ${src}
    linux (loop)/casper/vmlinuz boot=casper file=/cdrom/preseed/ubuntu.seed iso-scan/filename=${src} only-ubiquity quiet splash --
    initrd (loop)/casper/initrd.lz
}

menuentry "Ubuntu 12.10 Server i386" {
    set src=/ubuntu-12.10-server-i386.iso
    mount_iso ${src}
    linux (loop)/casper/vmlinuz boot=casper file=/cdrom/preseed/ubuntu.seed iso-scan/filename=${src} only-ubiquity quiet splash --
    initrd (loop)/casper/initrd.lz
}

menuentry "Ubuntu 12.10 Server amd64" {
    set src=/ubuntu-12.10-server-amd64.iso
    mount_iso ${src}
    linux (loop)/casper/vmlinuz boot=casper file=/cdrom/preseed/ubuntu.seed iso-scan/filename=${src} only-ubiquity quiet splash --
    initrd (loop)/casper/initrd.lz
}

SQLAlchemy disconnect from database immediately

from sqlalchemy import *

session = Session(bind = Engine("postgres://username:password@server:port/database"))
session.close()
session.bind.dispose()

Use dispose will disconnect from database immediately

2012年5月29日 星期二

Create a object from relation table by using SQLAlchemy

from sqlalchemy import *
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

## Create base class
Base = declarative_base()

## Create session class
Session = sessionmaker()

## Define User class
class User(Base):
    __tablename__ = "user"

    id = Column(Integer, Sequence('user_id_seq'), nullable = False, primary_key = True)
    username = Column(VARCHAR, nullable = False, primary_key = True)
    password = Column(VARCHAR, nullable = False)

    def __init__(self, username, password):
        self.username = username
        self.password = password

## Config connection engine
engine = create_engine("postgresql://username:password@server:port/database")

## Set user table use engine connection
User.metadata.bind = engine

## Create table, drop if exist
User.__table__.drop()
User.__table__.create()

## Create operate object and set connection
session = Session()
session.configure(bind = engine)

## Create user into database
session.add(User("kuntelin", "password"))
session.commit()

## Get users from database
print session.query(User).all()

2012年3月19日 星期一

Shell check if a variable is a number (Integer)

#!/bin/bash
if ! [[ "${variable}" =~ ^[0-9]+$ ]]
then
    echo "This variable is not a integer"
else
    echo "This variable is a integer"
fi
Reference: http://stackoverflow.com/questions/806906/how-do-i-test-if-a-variable-is-a-number-in-bash

Get installed rpm and format output

rpm -qa | uniq | sort | xargs rpm -q --qf "%{NAME},%{VERSION},%{RELEASE}\n" | uniq

2012年3月6日 星期二

Dnsmasq settings

domain=wiwynn.com

##Random IP
#dhcp-range=172.16.0.201,172.16.0.300

##Only static IP
dhcp-range=172.16.0.0,static

##Router
#dhcp-option=3,172.16.0.1
dhcp-option=option:router,172.16.0.1

##Name server
#dhcp-option=6,172.16.0.1
dhcp-option=option:dns-server,172.16.0.1

##NTP server
#dhcp-option=42,172.16.0.1
dhcp-option=option:ntp-server,172.16.0.1

dhcp-lease-max=1000
dhcp-authoritative

##Bootp
dhcp-boot=pxelinux.0,172.16.0.1

##Static IP and hostname to MAC address
dhcp-host=00:26:2d:09:5e:c6,172.16.0.101,juju1

##Forward domain archive.ubuntu.com query to 8.8.8.8
server=/archive.ubuntu.com/8.8.8.8

##Bind all host in main.wiwynn.com to 172.16.0.1
address=/main.wiwynn.com/172.16.0.1

Check option parameter:
sudo dnsmasq --help dhcp

2012年3月1日 星期四

PXEBoot config

Content of pxe config ( /var/lib/tftpboot/pxelinux.cfg/default )
DEFAULT menu
PROMPT 0
MENU TITLE Cobbler | http://fedorahosted.org/cobbler
TIMEOUT 50
TOTALTIMEOUT 6000
ONTIMEOUT local

##Boot into local hard disk
LABEL local
        MENU LABEL (local)
        MENU DEFAULT
        LOCALBOOT -1

##Boot into busybox, the busybox is copied from ubuntu install iso.
LABEL busybox
        MENU LABEL busybox
        kernel /sources/busybox/linux
        append initrd=/sources/busybox/initrd.gz

##Boot into ubuntu desktop amd64 live environment.
##Can't install ubuntu from this mode.
LABEL ubuntu-1110-desktop-amd64
        MENU LABEL Ubuntu 11.10 desktop amd64
        kernel /sources/ubuntu/1110/desktop/amd64/vmlinuz
        append initrd=/sources/ubuntu/1110/desktop/amd64/initrd.lz boot=casper root=/dev/nfs netboot=nfs nfsroot=192.168.116.1:/var/lib/tftpboot/sources/ubuntu/1110/desktop/amd64/nfs

##Boot into ubuntu desktop i386 live environment.
##Can't install ubuntu from this mode.
LABEL ubuntu-1110-desktop-i386
        MENU LABEL Ubuntu 11.10 desktop i386
        kernel /sources/ubuntu/1110/desktop/i386/vmlinuz
        append initrd=/sources/ubuntu/1110/desktop/i386/initrd.lz boot=casper root=/dev/nfs netboot=nfs nfsroot=192.168.116.1:/var/lib/tftpboot/sources/ubuntu/1110/desktop/i386/nfs
Mount ISO for provide NFS data
sudo mount -t auto -o loop ubuntu-1110-desktop-amd64.iso /var/lib/tftpboot/sources/ubuntu/1110/desktop/amd64/nfs
sudo mount -t auto -o loop ubuntu-1110-desktop-i386.iso /var/lib/tftpboot/sources/ubuntu/1110/desktop/i386/nfs

Content of nfs config( /etc/exports )
/var/lib/tftpboot/sources/ubuntu/1110/desktop/amd64/nfs 192.168.116.0/24(async,no_root_squash,no_subtree_check,ro)
/var/lib/tftpboot/sources/ubuntu/1110/desktop/i386/nfs 192.168.116.0/24(async,no_root_squash,no_subtree_check,ro)

2012年2月28日 星期二

Modify initrd.gz content

sudo gzip -d initrd.gz
sudo cpio -idm < initrd
...(Modify content)
sudo find . | cpio -o -H newc > initrd

2012年2月21日 星期二

avahi

Publish current information:
sudo avahi-publish -h ${host_name} -d ${domain_name} -s _${service_name}._tcp ${port_number} comment_1=${comment_1_context} comment_2="${comment_2_context_with_space}"

Collect information:
sudo avahi-browse -a -d ${domain_name} -r -p -t

2012年2月8日 星期三

Useful screen commands in byobu


CommandDescription

Ctrl + a, ?Show screen commands

Ctrl + a, |Split screen vertical

Ctrl + a, QShow current screen only

Ctrl + a, Ctrl + ISwitch focus screen

Ctrl + a, NumberSwitch to screen number X

Ctrl + a, CClean screen

Ctrl + a, x or Ctrl + xLock screen

Ctrl + a, k or KKill screen

2012年2月6日 星期一

Using lftp to mirror folder

Mirror CentOS repository from ftp.nchc.org.tw to local folder
sudo lftp -c mirror --continue --delete ftp://ftp.nchc.org.tw/pub/Linux/CentOS/ /mnt/mirror/CentOS/

2012年2月5日 星期日

Ubuntu wireless access point

Install hostaptd with command "sudo apt-get install -y hostapd"
Edit files as following.

File: /etc/default/hostapd
Content:
RUN_DAEMON="yes"
DAEMON_CONF="/etc/hostapd/hostapd.conf"
DAEMON_OPTS="-dd"

File: /etc/hostapd/hostapd.conf
Content:
interface=wlan0 # Please reference to your wireless device name.
driver=nl80211  # All support 802.11 spec. device can use the common driver.
hw_mode=g
channel=11
ssid=MySSID     # Please input SSID name that you would like to use.
wpa=1
wpa_key_mgmt=WPA-PSK
wpa_pairwise=TKIP CCMP
wpa_passphrase=MyPassword  # Please input your password for wireless access point.

Start service with one of the commands.
1. sudo service hostapd start
2. sudo hostapd -dd /etc/hostapd/hostapd.conf

2012年2月2日 星期四

Search linux command history by PageUp and PageDown

Edit /etc/inputrc and unmark lines as following.
”\e[5~”: history-search-backward
”\e[6~”: history-search-forward

2012年2月1日 星期三

Ubuntu Orchestra server config files

Global settings: /etc/cobbler/settings
Config path: /var/lib/cobbler/config
Template path: /etc/cobbler/*.template

2012年1月17日 星期二

Using iptables to create nat

Internet setting:
Interface: eth0
IP: 172.16.116.1
MASK: 255.255.0.0
GATEWAY: 172.16.1.254

Nat setting:
Interface: eth1
IP: 192.168.116.1
MASK: 255.255.255.0
GATEWAY: 192.168.116.1

Content of /etc/network/interface:
# The loopback network interface
auto lo
iface lo inet loopback

# The primary network interface
auto eth0
iface eth0 inet static
    address 172.16.116.1
    netmask 255.255.0.0
    gateway 172.16.1.254
    # Enable package forwarding
    up sudo sh -c 'echo "1" > /proc/sys/net/ipv4/ip_forward'
    up sudo iptables -t nat -A POSTROUTING -j MASQUERADE -o $IFACE
    # Disable package forwarding
    down sudo sh -c 'echo "0" > /proc/sys/net/ipv4/ip_forward'
    down sudo iptables -t nat -D POSTROUTING -j MASQUERADE -o $IFACE

auto eth1
iface eth1 inet static
    address 192.168.116.1
    netmask 255.255.255.0
    # Enable package forwarding
    up sudo sh -c 'echo "1" > /proc/sys/net/ipv4/ip_forward'
    #up sudo iptables -A POSTROUTING -s 192.168.116.0/24 -o eth0 -j SNAT --to 172.16.116.1
    # Disable package forwarding
    down sudo sh -c 'echo "0" > /proc/sys/net/ipv4/ip_forward'
    #down sudo iptables -D POSTROUTING -s 192.168.116.0/24 -o eth0 -j SNAT --to 172.16.116.1

2012年1月16日 星期一

Ubuntu preseed file by Dustin Kirkland

# Ubuntu Server Quick Install
# by Dustin Kirkland 
#  * Documentation: http://bit.ly/uquick-doc

d-i     debian-installer/locale string en_US.UTF-8
d-i     debian-installer/splash boolean false
d-i     console-setup/ask_detect        boolean false
d-i     console-setup/layoutcode        string us
d-i     console-setup/variantcode       string
d-i     netcfg/get_nameservers  string
d-i     netcfg/get_ipaddress    string
d-i     netcfg/get_netmask      string 255.255.255.0
d-i     netcfg/get_gateway      string
d-i     netcfg/confirm_static   boolean true
d-i     clock-setup/utc boolean true
d-i     partman-auto/method string regular
d-i     partman-lvm/device_remove_lvm boolean true
d-i     partman-lvm/confirm boolean true
d-i     partman/confirm_write_new_label boolean true
d-i     partman/choose_partition        select Finish partitioning and write changes to disk
d-i     partman/confirm boolean true
d-i     partman/confirm_nooverwrite boolean true
d-i     partman/default_filesystem string ext3
d-i     clock-setup/utc boolean true
d-i     clock-setup/ntp boolean true
d-i     clock-setup/ntp-server  string ntp.ubuntu.com
d-i     base-installer/kernel/image     string linux-server
d-i     passwd/root-login       boolean false
d-i     passwd/make-user        boolean true
d-i     passwd/user-fullname    string ubuntu
d-i     passwd/username string ubuntu
d-i     passwd/user-password-crypted    password $6$.1eHH0iY$ArGzKX2YeQ3G6U.mlOO3A.NaL22Ewgz8Fi4qqz.Ns7EMKjEJRIW2Pm/TikDptZpuu7I92frytmk5YeL.9fRY4.
d-i     passwd/user-uid string
d-i     user-setup/allow-password-weak  boolean false
d-i     user-setup/encrypt-home boolean false
d-i     passwd/user-default-groups      string adm cdrom dialout lpadmin plugdev sambashare
d-i     apt-setup/services-select       multiselect security
d-i     apt-setup/security_host string security.ubuntu.com
d-i     apt-setup/security_path string /ubuntu
d-i     debian-installer/allow_unauthenticated  string false
d-i     pkgsel/upgrade  select safe-upgrade
d-i     pkgsel/language-packs   multiselect
d-i     pkgsel/update-policy    select none
d-i     pkgsel/updatedb boolean true
d-i     grub-installer/skip     boolean false
d-i     lilo-installer/skip     boolean false
d-i     grub-installer/only_debian      boolean true
d-i     grub-installer/with_other_os    boolean true
d-i     finish-install/keep-consoles    boolean false
d-i     finish-install/reboot_in_progress       note
d-i     cdrom-detect/eject      boolean true
d-i     debian-installer/exit/halt      boolean false
d-i     debian-installer/exit/poweroff  boolean false
d-i     pkgsel/include string openssh-server
After PXEBoot installed, you can log in the server with user "ubuntu" and password "ubuntu"

2012年1月12日 星期四

Python write syslog with logging

Python program:
import logging
import logging.handlers

logger = logger.getLogger("NAME")

log_handler = logging.handlers.SysLogHandler(address = "/dev/log")
log_handler.setLevel(logging.DEBUG)
log_handler.setFormatter(logging.Formatter("%(name)s:%(process)d - %(levelname)s - %(pathname)s:%(lineno)d - %(message)s"))

logger.addHandler(log_handler)

logger.debug("This is debug message")
logger.info("This is info message")
logger.warn("This is warning message")
logger.error("This is error message")
logger.critical("This is critical message")

Python write syslog with syslog

Python program:
import syslog

syslog.open(logoption = syslog.LOG_PID)
syslog.syslog("Hello world!")

syslog-ng config

Common section:
@version: 3.2

options {
    long_hostnames(off);
    flush_lines(0);
    use_dns(no);
    use_fqdn(no);
    owner("root");
    group("adm");
    perm(0640);
    stats_freq(0);
    bad_hostname("^gconfd$");
};

Write system log and kernel message to file:
# Record syslog to file
source recorder {
    file("/proc/kmsg");
    unix-dgram("/dev/log");
}
destination recorder {
    file("/var/log/syslog"
        owner(syslog)
        group(adm)
        perm(0644)
        dir_perm(0755)
        create_dirs(yes));
}
log {
    source(recorder);
    destination(recorder);
};

Send local log to remote:
# Send local syslog
source sender {
    file("/var/log/syslog");
};
destination sender {
    tcp(log_1.server port(514));
    tcp(log_2.server port(514));
};
log {
    source(sender);
    destination(sender);
};

Receive log from remote:
# Receive remote syslog
source receiver {
    udp(ip(0.0.0.0) port(514));
    tcp(ip(0.0.0.0) port(514));
};
destination receiver {
    file("/var/log/remote/$YEAR.$MONTH.$DAY/all"
        owner(root)
        group(adm)
        perm(0644)
        dir_perm(0755)
        create_dirs(yes));
    file("/var/log/remote/$YEAR.$MONTH.$DAY/$HOST"
        owner(root)
        group(adm)
        perm(0644)
        dir_perm(0755)
        create_dirs(yes));
};
log {
    source(receiver);
    destination(receiver);
};

Be sure just use "/dev/log" at source section onece.

Reference: http://www.balabit.com/sites/default/files/documents/syslog-ng-ose-3.2-guides/syslog-ng-ose-v3.2-guide-admin-en.html/bk01-toc.html

Python write syslog from config file with logging

Config file:
[loggers]
keys=root,SYS

[logger_root]
level=NOTSET
handlers=screen

[logger_SYS]
handlers=local,remote
qualname=compiler.parser
propagate=1

# Ref: http://docs.python.org/library/logging.html#formatter-objects
[formatters]
keys=simple,complex

[formatter_simple]
format=%(name)s:%(process)d - %(levelname)s - %(message)s

[formatter_complex]
format=%(name)s:%(process)d - %(levelname)s - %(pathname)s:%(lineno)d - %(message)s

# Define handler setting
# Ref: http://docs.python.org/library/logging.handlers.html
[handlers]
keys=screen,local,remote

[handler_screen]
class=StreamHandler
formatter=complex
args=(sys.stdout,)

[handler_local]
class=handlers.SysLogHandler
formatter=complex
args=("/dev/log",)

[handler_remote]
class=handlers.SysLogHandler
formatter=complex
#args=((,),)
args=(("172.16.1.1", 514),)


Python program:
import logging
import logging.config

logging.config.fileConfig("/path/to/config")
logger = logging.getLogger("UI")
logger.debug("This is debug message")
logger.info("This is info message")
logger.warn("This is warning message")
logger.error("This is error message")
logger.critical("This is critical message")

Python generate file with Template by Jinja2

Required: Jinja
Template file: syslog-ng.conf.tpl
context:
@version: 3.2

options {
    long_hostnames(off);
    flush_lines(0);
    use_dns(no);
    use_fqdn(no);
    owner("root");
    group("adm");
    perm(0640);
    stats_freq(0);
    bad_hostname("^gconfd$");
};

# Record syslog to file
source recorder {
    file("/proc/kmsg");
    unix-dgram("/dev/log");
}
destination recorder {
    file("/var/log/syslog"
        owner(syslog)
        group(adm)
        perm(0644)
        dir_perm(0755)
        create_dirs(yes));
}
log {
    source(recorder);
    destination(recorder);
};

# Send local syslog
source sender {
    file("/var/log/syslog");
};
destination sender {
{% for log_server in log_servers %}    tcp({{ log_server }} port(514));
{% endfor %}
#    tcp(172.16.116.240 port(514));
};
log {
    source(sender);
    destination(sender);
};

# Receive remote syslog
source receiver {
    udp(ip(0.0.0.0) port(514));
    tcp(ip(0.0.0.0) port(514));
};
destination receiver {
    file("/var/log/wistor/$YEAR.$MONTH.$DAY/all"
        owner(root)
        group(adm)
        perm(0644)
        dir_perm(0755)
        create_dirs(yes));
    file("/var/log/wistor/$YEAR.$MONTH.$DAY/$HOST"
        owner(root)
        group(adm)
        perm(0644)
        dir_perm(0755)
        create_dirs(yes));
};
log {
    source(receiver);
    destination(receiver);
};


Python program:
from jinja2 import Template

print Template(file("syslog-ng.conf.tpl").read()).render(log_server = [ "172.16.116.%d" % ip for ip in range(1, 11) ])

Reference: http://jinja.pocoo.org/docs/