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.
Функции перевода UNIX и Java даты в TDateTime
CPAU
Иногда в своей адмиминской работе мне приходилось сталкиваться с проблемой когда нужно дать возможность пользователю запустить программу с правами другого пользователя домена (например чтобы запускать НЕсетевую конфигурацию Консультант+ ). Делается это при помощи старой, доброй 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
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
Вольный перевод статьи из 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 interface
auto lo
iface lo inet loopback
# This is a list of hotpluggable network interfaces.
# They will be activated automatically by the hotplug subsystem.
mapping hotplug
script grep
map eth0
# The primary network interface
auto eth0
iface eth0 inet static
address 192.168.0.100
netmask 255.255.255.0
network 192.168.0.0
broadcast 192.168.0.255
gateway 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.sh
echo '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/sda1
UUID=226d9304-88ca-44c0-a3e3-d1ad26cfc084 / ext3 defaults,errors=remount-ro,usrquota,grpquota 0 1
# /dev/sda5
UUID=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.groupКоманда quotacheck выведет ошибку:
chmod 600 /quota.*
mount -o remount /
quotacheck -avugm
quotaon -avug
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 = MYWORKGROUP
netbios name = SERVER1
server string = %h server (Samba, Ubuntu)
passdb backend = tdbsam
security = user
username map = /etc/samba/smbusers
name resolve order = wins bcast hosts
domain logons = yes
preferred master = yes
wins support = yes
# Set CUPS for printing
load printers = yes
printcap name = CUPS
printing = CUPS
# Default logon
logon drive = H:
logon script = scripts/logon.bat
logon path = \\server1\profile\%U
# Useradd scripts
# add user script = /usr/sbin/adduser --quiet --disabled-password --gecos "" %u
add user script = /usr/sbin/useradd -m '%u' -g users -G users
delete user script = /usr/sbin/userdel -r %u
add group script = /usr/sbin/groupadd %g
delete group script = /usr/sbin/groupdel %g
add user to group script = /usr/sbin/usernod -G %g %u
add machine script = /usr/sbin/useradd -s /bin/false/ -d /var/lib/nobody %u
idmap uid = 15000-20000
idmap gid = 15000-20000
template shell = /bin/bash
# sync smb passwords woth linux passwords
passwd program = /usr/bin/passwd %u
passwd chat = *Enter\snew\sUNIX\spassword:* %n\n *Retype\snew\sUNIX\spassword:* %n\n *password\supdated\ssuccessfully* .
passwd chat debug = yes
unix password sync = yes
# set the loglevel
log level = 3
[public]
browseable = yes
public = yes
[homes]
comment = Home
valid users = %S
read only = no
browsable = no
[printers]
comment = All Printers
path = /var/spool/samba
printable = yes
public = no
writable = no
create mode = 0700
[print$]
comment = Printer Drivers
path = /var/lib/samba/printers
browseable = yes
read only = yes
guest ok = no
write list = root, @smbadmin
[netlogon]
comment = Network Logon Service
path = /home/samba/netlogon
admin users = Administrator
valid users = %U
read only = no
guest ok = yes
writable = no
share modes = no
[profile]
comment = User profiles
path = /home/samba/profiles
valid users = %U
create mode = 0600
directory mode = 0700
writable = yes
browsable = no
guest ok = no
Создадим директории для domain logons и profiles:
mkdir /home/samba
mkdir /home/samba/netlogon
mkdir /home/samba/profiles
chmod 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.comТеперь добавим пользователя root (alias: Administrator), он будет domain-адиминистратором для добавления новых машин в Samba domain.
192.168.0.110 workstation1
192.168.0.111 workstation2
192.168.0.112 workstation3
192.168.0.113 workstation4
smbpasswd -a rootСоздадим файл /etc/samba/smbusers и добавим в него такую запись:
echo "root = Administrator" > /etc/samba/smbusersСоздадим дефолтные доменные группы для виндов:
net groupmap add ntgroup="Domain Admins" unixgroup="root" type=domain -U rootДля примера добавим в наш домен пользователя tom с паролем secret:
net groupmap add ntgroup="Domain Users" unixgroup="users" type=domain -U root
net groupmap add ntgroup="Domain Guests" unixgroup="nogroup" type=domain -U root
net rpc user add tom -U rootСоздадим общий для всех пользователей домена каталог:
net rpc user password tom "secret" -U root
smbpasswd -e tom
mkdir -p /home/shares/allusersДобавим его в конфигурационный файл Samba /etc/samba/smb.conf:
chown -R root:users /home/shares/allusers/
chmod -R ug+rwx,o+rx-w /home/shares/allusers/
[allusers]Перезапустим сервис Samba:
comment = All Users
path = /home/shares/allusers
valid users = @users
force group = users
create mask = 0660
directory mask = 0771
writable = yes
/etc/init.d/samba restart
(c) http://klek.blogspot.com/2007/12/samba-domain-controller-server-for.html
Резюме
Образование
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"
По не знаю какой уж там исторической традиции "честные"
(канонические, особенно коммерческие) системы Unix не имеют в
своем базовом комплекте ни одного нормального (еще раз
подчеркну это слово - НОРМАЛЬНОГО) текстового редактора.
Поэтому системный администратор должен уметь пользоваться
тем, что ему дают. А дают ему несравненный "Визуальный" экранный
редактор файлов - Редактор VI.
Редактор VI имеет три режима:
1. Командный - в этом режиме можно перемещаться по файлу и
выполнять редактирующие команды над текстом. Команды вызываются
ОБЫЧНЫМИ ЛАТИНСКИМИ БУКВАМИ.
2. Ввода текста - в этом режиме обычные латинские буквы будут
вставляться в текст.
3. Режим строчного редактора ED используется для управления
файлами (типа сохранить файл, зачитать файл и т.д.)
Прочитайте предыдущий абзац еще раз. Вы еще не испугались?
Хорошо. Поехали. Итак:
vi имя_файла
VI в КОМАНДНОМ РЕЖИМЕ.
ЧТОБЫ ВЫЙТИ ИЗ ФАЙЛА БЕЗ СОХРАНЕНИЯ, нажмите:
ESC : q ! Enter
чтобы выйти из файла, сохранив изменения, нажмите:
ESC : w ! Enter
ESC : 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
