Archive for April, 2008

Функции перевода UNIX и Java даты в TDateTime

April 16th, 2008

Все как и указано в заголовке + функция вычисляющая разницу между указанной датой и системным временем (может пригодится при разработке IM-клиентов)

unit unit4;

interface

uses
Windows, SysUtils;

function DateTimeToUnix(ConvDate: TDateTime): Longint;
function UnixToDateTime(USec: Longint): TDateTime;
function JavaToDateTime(USec: int64): TDateTime;
function DateTimeToJava(ConvDate: TDateTime): int64;
function GetElapsedTime(last:int64):string;

implementation

const

// Sets UnixStartDate to TDateTime of 01/01/1970
UnixStartDate: TDateTime = 25569.0;

function DateTimeToUnix(ConvDate: TDateTime): Longint;
begin
//example: DateTimeToUnix(now);
Result := Round((ConvDate – UnixStartDate) * 86400);
end;

function UnixToDateTime(USec: Longint): TDateTime;
begin
//Example: UnixToDateTime(1003187418);
Result := (Usec / 86400) + UnixStartDate;
end;

function DateTimeToJava(ConvDate: TDateTime): int64;
var
TimeZoneInformation: TTimeZoneInformation;
JavaUTC:int64;
begin
GetTimeZoneInformation(TimeZoneInformation);
JavaUTC:=((TimeZoneInformation.Bias+TimeZoneInformation.DaylightBias)*60*1000);
Result := Round(((ConvDate – UnixStartDate) * 86400*1000) + JavaUTC);
end;

function JavaToDateTime(USec: int64): TDateTime;
var
TimeZoneInformation: TTimeZoneInformation;
begin
GetTimeZoneInformation(TimeZoneInformation);
Usec:=Usec-((TimeZoneInformation.Bias+TimeZoneInformation.DaylightBias)*60*1000);
Result := (Usec / (86400*1000)) + UnixStartDate;
end;

function GetElapsedTime(last:int64):string;
var
delta:int64;

SECOND:longint;
MINUTE:longint;
HOUR:longint;
DAY:longint;

begin
//initialization
SECOND := 1000;
MINUTE := 60 * SECOND;
HOUR := 60 * MINUTE;
DAY := 24 * HOUR;
//

delta:=DateTimeToJava(now)-last;
if delta < MINUTE then result:='Меньше минуты назад'
else if delta < HOUR then result:=IntToStr(delta div MINUTE)+' минут назад'
else if delta < DAY then result:=IntToStr(delta div HOUR)+' часов '+IntToStr((delta-(delta div HOUR)*HOUR) div MINUTE)+' минут назад'
else result:=IntToStr(delta div DAY)+’ дней ‘+IntToStr((delta-(delta div DAY)*DAY) div HOUR)+’ часов ‘+IntToStr((delta-((delta div HOUR)*HOUR)-((delta div DAY)*DAY) div HOUR) div MINUTE)+’ минут назад’;
end;

end.

CPAU

April 16th, 2008

Иногда в своей адмиминской работе мне приходилось сталкиваться с проблемой когда нужно дать возможность пользователю запустить программу с правами другого пользователя домена (например чтобы запускать НЕсетевую конфигурацию Консультант+ ). Делается это при помощи старой, доброй RunAS.EXE. Но есть одна проблема, программа требует ввода пароля с клавы, то есть становится проблематично использовать её в каких либо скриптах, а без них пользователи совсем озвереют.

Хорошей заменой утилиты от Microsoft является программа CPAU, которую надо положить в system32 и можно использовать в скриптах, например таких:


cpau -u INSP\ozolin -p XXXXX -ex “\\Server3\ConsultantPlus\cons.exe” –lwop

Сохраняете эту строчку в bat-файл и копируете на рабочий стол пользователя, вот и все.

DNS server Setup using bind in Ubuntu

April 15th, 2008
DNS Stands for Domain Name Service.On the Internet, the Domain Name Service (DNS) stores and associates many types of information with domain names; most importantly, it translates domain names (computer hostnames) to IP addresses. It also lists mail exchange servers accepting e-mail for each domain. In providing a worldwide keyword-based redirection service, DNS is an essential component of contemporary Internet use.

Introduction

BIND (Berkeley Internet Name Domain) is an open reference implementation of the Domain Name System (DNS) protocol and provides a redistributable implementation of the major components of the Domain Name System.

a name server (named)

a resolver library

troubleshooting tools like nslookup and dig

The BIND DNS Server is used on the vast majority of name serving machines on the Internet, providing a robust and stable architecture on top of which an organization’s naming architecture can be built. The resolver library included in the BIND distribution provides the standard APIs for translation between domain names and Internet addresses and is intended to be linked with applications requiring name service.

Firewall Config

Bind listens on port 53 UDP and TCP. TCP is normally only used during zone transfers so it would appear that you could filter it if you have no slaves. However If the response to a query is greater than 1024 bytes, the server sends a partial response, and client and server will try to redo the transaction with TCP.

Responses that big do not happen often, but they happen. And people do quite often block 53/tcp without their world coming to an end. But this is where one usually inserts the story about the Great DNS Meltdown when more root servers were added. This made queries for the root list greater than 1024 and the whole DNS system started to break down from people violating the DNS spec (RFC1035) and blocking TCP.

Differences in BIND8 and BIND9

Apart from being multi-threaded, and a complete code rewrite – which should provide better stability and security in the long term, there are other differences

If there is a syntax error in named.conf, BIND9 will log errors and not reload the named server. BIND8 will log errors and the daemon will die!

Extensive support of TSIGs (shared keys) for access control, for example, “update-policy” can be used for fine grained access control of dynamic updates.

The tool for starting/stopping/reloading etc., rndc is different from the v8 ndc – different communications, authentication and features.

Syntax in zone files is more rigorously checked (e.g. a TTL line must exist)

In named.conf

v8 options ‘check-names’ and ’statistics-interval’ are not yet implemented in V9.

the default for the option ‘auth-nxdomain’ is now ‘no’, if you don’t set this manually, BIND 9 logs a corresponding message on startup.

The root server list, often called named.root or root.hints in BIND8 is not necessary in BIND 9, as it is included within the server.

Installing Bind in Ubuntu

sudo apt-get install bind9 dnsutils

This will install all the required packages for bind9

Configuring Bind

If you install Bind from the source code, you will have to edit the file named.conf. However, Ubuntu provides you with a pre-configured Bind, so we will edit named.conf.local file

sudo vi /etc/bind/named.conf.local

This is where we will insert our zones.If you want to know what is zone in DNs check this

DNS zone is a portion of the global DNS namespace. This namespace is defined by RFC 1034, “Domain Names – Concepts and Facilities” and RFC 1035, “”Domain Names – Implementation and Specification”, and is laid out in a tree structure from right to left, such that divisions of the namespace are performed by prepending a series of characters followed by period (’.’), to the upper namespace

You need to add the following lines in named.conf.local file

# This is the zone definition. replace example.com with your domain name

zone “example.com” {
type master;
file “/etc/bind/zones/example.com.db”;
};

# This is the zone definition for reverse DNS. replace 0.168.192 with your network address in reverse notation – e.g my network address is 192.168.0

zone “0.168.192.in-addr.arpa” {
type master;
file “/etc/bind/zones/rev.0.168.192.in-addr.arpa”;
};

Now you need to edit the options file

sudo vi /etc/bind/named.conf.options

We need to modify the forwarder. This is the DNS server to which your own DNS will forward the requests he cannot process.

forwarders {
# Replace the address below with the address of your provider’s DNS server
123.123.123.123;
};

add the zone definition files (replace example.com with your domain name

sudo mkdir /etc/bind/zones

sudo vi /etc/bind/zones/example.com.db

The zone definition file is where we will put all the addresses / machine names that our DNS server will know.Example zone file as follows

// replace example.com with your domain name. do not forget the . after the domain name!
// Also, replace ns1 with the name of your DNS server
example.com. IN SOA ns1.example.com. admin.example.com. (
// Do not modify the following lines!
2007031001
28800
3600
604800
38400
)

// Replace the following line as necessary:
// ns1 = DNS Server name
// mail = mail server name
// example.com = domain name
example.com. IN NS ns1.example.com.
example.com. IN MX 10 mail.example.com.

// Replace the IP address with the right IP addresses.
www IN A 192.168.0.2
mta IN A 192.168.0.3
ns1 IN A 192.168.0.1

Create Reverse DNS Zone file

A normal DNS query would be of the form ‘what is the IP of host=www in domain=mydomain.com’. There are times however when we want to be able to find out the name of the host whose IP address = x.x.x.x. Sometimes this is required for diagnostic purposes more frequently these days it is used for security purposes to trace a hacker or spammer, indeed many modern mailing systems use reverse mapping to provide simple authentication using dual look-up, IP to name and name to IP.

In order to perform Reverse Mapping and to support normal recursive and Iterative (non-recursive) queries the DNS designers defined a special (reserved) Domain Name called IN-ADDR.ARPA. This domain allows for all supported Internet IPv4 addresses (and now IPv6).

sudo vi /etc/bind/zones/rev.0.168.192.in-addr.arpa

copy and paste the following sample file

//replace example.com with yoour domain name, ns1 with your DNS server name.
// The number before IN PTR example.com is the machine address of the DNS server. in my case, it’s 1, as my IP address is 192.168.0.1.
@ IN SOA ns1.example.com. admin.example.com. (
2007031001;
28800;
604800;
604800;
86400
)

IN NS ns1.example.com.
1 IN PTR example.com

Restart Bind server using the following command

sudo /etc/init.d/bind9 restart

Testing Your DNS Server

Modify the file resolv.conf with the following settings

sudo vi /etc/resolv.conf

Enter the following details save and exit the file

// replace example.com with your domain name, and 192.168.0.1 with the address of your new DNS server.

search example.com
nameserver 192.168.0.1

Test your DNS Using the following command

dig example.com

SAMBA (Domain controller) Server For Small Workgroups With Ubuntu 7.10

April 15th, 2008

Вольный перевод статьи из HowtoForge.
Оригинал…

В статье описывается один из вариантов установки file- и print-сервера для малого и среднего предприятия до 250 пользователей. Для хранения паролей и информации об аккаунтах пользователей используется Samba с поддержкой tdb.

Что будем ставить:
1. Samba как доменконтроллер

Войдем в режим root командой:

sudo -s -H

Настройка сети.

(K)ubuntu 7.10 при установке настраивает сеть на использование DHCP, т.е присваивает компьютеру динамический адрес. Серверу нужно иметь постоянный (static) адрес, поэтому нам нужно исправить сетевые настройки. Допустим, что наш сервер будет иметь адрес 192.168.0.100. Редактируем файл /etc/network/interfaces

# This file describes the network interfaces available on your system# and how to activate them. For more information, see interfaces(5).

# The loopback network interfaceauto loiface lo inet loopback

# This is a list of hotpluggable network interfaces.# They will be activated automatically by the hotplug subsystem.mapping hotplugscript grepmap eth0

# The primary network interfaceauto eth0iface eth0 inet staticaddress 192.168.0.100netmask 255.255.255.0network 192.168.0.0broadcast 192.168.0.255gateway 192.168.0.1

Чтобы изменения вступили в силу необходимо перегрузить сетевую подсистему:

/etc/init.d/networking restart

Теперь нужно изменить /etc/hosts, чтобы имя сервера соответствовало реальному IP, т.е. добавляем строчку типа:

192.168.0.100    server1.example.com    server1

Настраиваем Hostname:

echo server1.example.com > /etc/hostname/etc/init.d/hostname.shecho '192.168.0.100 server1.example.com' >> /etc/hosts

Для ограничения дискового пространства пользователей установим пакет quota:

aptitude install quita

Добавим в /etc/fstab параметры usrquota и grpquota в описание нужного раздела, например:

# /etc/fstab: static file system information.##     
       
proc            /proc           proc    defaults        0       0# /dev/sda1UUID=226d9304-88ca-44c0-a3e3-d1ad26cfc084 /               ext3    defaults,errors=remount-ro,usrquota,grpquota 0       1# /dev/sda5UUID=d824ce36-04b8-4870-83f4-f1a5037c2de4 none            swap    sw              0       0/dev/hdc        /media/cdrom0   udf,iso9660 user,noauto     0       0/dev/           /media/floppy0  auto    rw,user,noauto  0       0

Теперь нужно создать файлы quota.user и quota.group

touch /quota.user /quota.groupchmod 600 /quota.*mount -o remount /quotacheck -avugmquotaon -avug

Команда quotacheck выведет ошибку:

quotacheck: WARNING - Quotafile //quota.user was probably truncated. Cannot save quota settings...quotacheck: WARNING - Quotafile //quota.group was probably truncated. Cannot save quota settings...

Это нормально для первого запуска, не обращайте внимания.

Установка Samba.

aptitude install libcupsys2 samba samba-common samba-doc smbclient winbind cupsys-common

Отредактируем файл /etc/samba/smb.conf. Должно получиться что-то вроде этого:

[global]workgroup = MYWORKGROUPnetbios name = SERVER1server string = %h server (Samba, Ubuntu)

passdb backend = tdbsamsecurity = userusername map = /etc/samba/smbusersname resolve order = wins bcast hostsdomain logons = yespreferred master = yeswins support = yes

# Set CUPS for printingload printers = yesprintcap name = CUPSprinting = CUPS

# Default logonlogon drive = H:logon script = scripts/logon.batlogon path = \\server1\profile\%U

# Useradd scripts# add user script = /usr/sbin/adduser --quiet --disabled-password --gecos "" %uadd user script = /usr/sbin/useradd -m '%u' -g users -G usersdelete user script = /usr/sbin/userdel -r %uadd group script = /usr/sbin/groupadd %gdelete group script = /usr/sbin/groupdel %gadd user to group script = /usr/sbin/usernod -G %g %uadd machine script = /usr/sbin/useradd -s /bin/false/ -d /var/lib/nobody %uidmap uid = 15000-20000idmap gid = 15000-20000template shell = /bin/bash

# sync smb passwords woth linux passwordspasswd program = /usr/bin/passwd %upasswd chat = *Enter\snew\sUNIX\spassword:* %n\n *Retype\snew\sUNIX\spassword:* %n\n *password\supdated\ssuccessfully* .passwd chat debug = yesunix password sync = yes

# set the loglevellog level = 3

[public]browseable = yespublic = yes

[homes]comment = Homevalid users = %Sread only = nobrowsable = no

[printers]comment = All Printerspath = /var/spool/sambaprintable = yespublic = nowritable = nocreate mode = 0700

[print$]comment = Printer Driverspath = /var/lib/samba/printersbrowseable = yesread only = yesguest ok = nowrite list = root, @smbadmin

[netlogon]comment = Network Logon Servicepath = /home/samba/netlogonadmin users = Administratorvalid users = %Uread only = noguest ok = yeswritable = noshare modes = no

[profile]comment = User profilespath = /home/samba/profilesvalid users = %Ucreate mode = 0600directory mode = 0700writable = yesbrowsable = noguest ok = no

Создадим директории для domain logons и profiles:

mkdir /home/sambamkdir /home/samba/netlogonmkdir /home/samba/profileschmod 777 /var/spool/samba/chown -R root:users /home/samba/chmod -R 771 /home/samba/

Перезапустим сервис Samba:

/etc/init.d/samba restart

В файле /etc/nsswitch.conf нужно изменить строку:

hosts: files dns

на

hosts: files wins dns

Добавить все компьютеры группы в /etc/hosts:

192.168.0.100 server1 server1.example.com192.168.0.110 workstation1192.168.0.111 workstation2192.168.0.112 workstation3192.168.0.113 workstation4

Теперь добавим пользователя root (alias: Administrator), он будет domain-адиминистратором для добавления новых машин в Samba domain.

smbpasswd -a root

Создадим файл /etc/samba/smbusers и добавим в него такую запись:

echo "root = Administrator" > /etc/samba/smbusers

Создадим дефолтные доменные группы для виндов:

net groupmap add ntgroup="Domain Admins" unixgroup="root" type=domain -U rootnet groupmap add ntgroup="Domain Users" unixgroup="users" type=domain -U rootnet groupmap add ntgroup="Domain Guests" unixgroup="nogroup" type=domain -U root

Для примера добавим в наш домен пользователя tom с паролем secret:

net rpc user add tom -U rootnet rpc user password tom "secret" -U rootsmbpasswd -e tom

Создадим общий для всех пользователей домена каталог:

mkdir -p /home/shares/alluserschown -R root:users /home/shares/allusers/chmod -R ug+rwx,o+rx-w /home/shares/allusers/

Добавим его в конфигурационный файл Samba /etc/samba/smb.conf:

[allusers]comment = All Userspath = /home/shares/allusersvalid users = @usersforce group = userscreate mask = 0660directory mask = 0771writable = yes

Перезапустим сервис Samba:

/etc/init.d/samba restart

(c) http://klek.blogspot.com/2007/12/samba-domain-controller-server-for.html

Резюме

April 15th, 2008
Снегирев Олег Александрович (23)


Образование
9/2001 – 6/2006 ФАИТ СамГТУ, кафедра «Вычислительная техника», специальность: инженер-системотехник


Дополнительное
образование
7/2000 прослушал курс по web-дизайну во время учебы в Самарском техническом лицее.
10/2003 – 6/2006 технический английский(получил квалификацию – переводчик в сфере профессиональной деятельности) кафедра иностранных языков СамГТУ.
12/2007 Прошел курсы Microsoft: 2279 – Planning, Implementing, and Maintaining a Microsoft Windows Server 2003 Active Directory Infrastructure и 2277 Implementing, Managing, and Maintaining a Microsoft Windows Server 2003 Network Infrastructure: Network Services. Имею статус ZCSE – Zyxel Certified Engineer.

Опыт работы
8/2002-11/2002 ООО «Благо» программист

Установка и обслуживание бухгалтерской программы «Инфобухгалтер», работа в качестве помощника системного администратора, ремонт и обслуживании ПК.

6/2004 – 6/2006 МРО ЦЕХБ «Преображение» Администратор сайта

Веб-дизайн, веб-программирование, создание интернет сайта и его обслуживание, раскрутка сайта

5/2006 – 8/2006 ООО «Радиант» тестировщик

Сборка и ремонт персональных компьютеров и серверов, установка программного обеспечения.

7/2006 – настоящее время Правительство Самарской области. Государственная жилищная инспекция Самарской области. Ведущий специалист. (Системный администратор, программист баз данных Oracle, программист Delphi, web-программист)

Развертывание и поддержка работы сети на базе Windows 2003 Server, AD, DNS, NAT, установка VPN каналов, установка ПО Oracle, развертывание БД Oracle. Разработка АИС для нужд предприятия с использованием Delphi и PL/SQL (в том числе корпоративный Jabber клиент со специфическими функциями для кадровой службы.), обслуживание сайта организации.

10/2007 – настоящее время Разработка сайтов на заказ для различных коммерческих структур (ООО «Инженер-Сервис», «ВолгаСтройРесурс» и т.д.)

Среды программирования

Программирую в Borland Delphi 5-7, Turbo Pascal, PHP, PL/SQL Developer, СУБД (My SQL, технология BDE, ADO, Oracle 10g), специализируюсь на web-программировании с использованием БД. Знаю HTML, CSS, JavaScript. Работа с CMS PHP-fusion и д.р. Java2 (в NetBeans) – изучаю.

Опыт разработки

Разработка АИС для нужд предприятия с использованием Delphi и PL/SQL для СУБД Oracle, Экономическое ПО – «Инфобухгалтер», Интернет проекты – PHP/JS/MySQL

Навыки

технический английский, разговорный английский разговорный французский – изучаю.

Личные качества

Уживчивый, исполнительный, ответственный, легко обучаемый

Интересы, хобби

Музыка, кино, чтение, прогулки, плавание, история.


Очень кратко о редакторе "VI"

April 14th, 2008
По  не  знаю  какой  уж  там  исторической  традиции  "честные"(канонические, особенно коммерческие) системы Unix не имеют всвоем базовом  комплекте ни   одного   нормального   (еще  разподчеркну  это  слово  - НОРМАЛЬНОГО)   текстового    редактора.Поэтому    системный администратор  должен  уметь  пользоватьсятем, что ему дают. А дают ему несравненный "Визуальный" экранныйредактор  файлов  - Редактор VI.

Редактор VI имеет три режима:

1.  Командный  -  в  этом  режиме можно перемещаться по файлу ивыполнять редактирующие команды над текстом. Команды вызываютсяОБЫЧНЫМИ ЛАТИНСКИМИ БУКВАМИ.

2. Ввода текста - в этом режиме обычные латинские  буквы  будутвставляться в текст.

3.  Режим  строчного  редактора  ED используется для управленияфайлами (типа сохранить файл, зачитать файл и т.д.)

Прочитайте предыдущий абзац еще раз. Вы еще  не  испугались?Хорошо. Поехали. Итак:

  vi имя_файла

VI в КОМАНДНОМ РЕЖИМЕ.

ЧТОБЫ ВЫЙТИ ИЗ ФАЙЛА БЕЗ СОХРАНЕНИЯ, нажмите:ESC  :  q  ! Enter

чтобы выйти из файла, сохранив изменения, нажмите:ESC  :  w ! EnterESC  :  q   Enterвыйти из файла с сохранением, одной командой:ESC  :  wq  Enter

для перехода В РЕЖИМ ВВОДА нужно нажать команды типа:"i"   вставлять здесь"A"   вставлять с конца строки"cw"  заменять текущее слово

ESC    для ВОЗВРАТА В КОМАНДНЫЙ РЕЖИМCTRL-[ для возврата в командный режим

для перехода В РЕЖИМ УПРАВЛЕНИЯ ФАЙЛАМИ нужно нажать":"  (перейти в режим редактора ED)

Двигаться по файлу можно командами:h,j,k,l    влево, вниз, вверх, вправоCtrl-F     На страницу внизCtrl-B     На страницу вверхА если вам очень повезет, то можно будет двигаться стрелочками.Чтобы перейти в режим везения, нужно описать  для  операционнойсистемы   ваш   терминал.   Этим  займемся  в  дальнейшем  (см."Описание терминалов, terminfo, termcap").

Подгоните курсор к нужному месту и нажмитеi          перевод в режим вводавводите требуемый текстESC        прекратить ввод, перейти в командный режим

Подгоните курсор к ненужному месту и нажмитеx          удалить символdd         удалить строчку

Еще парочка полезных команд:

o          вставлять с новой строки (под текущей строкой)a          в режим ввода ЗА курсором5yy        запомнить 5 строчекПодгоните курсор к нужному местуp          вставить запомненные строки под курсоромP          вставить запомненные строки НАД курсором

J          Склеить две строки/Шаблон поиска Enter       - поискn          Повторить поиск

На этом ознакомление с редактором VI можно считать законченным.Того, кто считает, что VI может предоставить больше  удобств  икоманд  по  редактированию,  я  отсылаю  к  прилагаемому  здесьсправочнику-памятке "наиболее употребительные команды VI",vibegin.txtну, и,  естественно (как всегда), к документации. Остальных яотсылаю к не менее удивительному в своем роде редактору EMACS,которым, не смотря на это, рекомендую пользоваться впредь.

(с) http://lib.ru/unixhelp/vi.txt