вторник, 30 ноября 2021 г.
Последняя версия скрипта для бекапа 1С
# PowerShell.exe -ExecutionPolicy Bypass -File C:\!Scripts\1c_pg_backup.ps1
# powershell -windowstyle minimized -c "powershell -c C:\!Scripts\1c_pg_backup.ps1 -verbose >> C:\!Scripts\1c_pg_backup.log *>&1"
[CmdletBinding()]
param(
[String]$dbname="",
[String]$dumpdir= 'E:\\tmp\\backup',
[String]$PG_DIR='C:\Program Files\PostgreSQL 1C\12\',
[String]$PGDUMP="$PG_DIR\bin\pg_dump.exe",
[String]$PSQL="$PG_DIR\bin\psql.exe",
[String]$dbserver='localhost',
[String]$dbuser='postgres',
[String]$dbpassword='Passw0rD',
[String]$separateconfig=""
)
Write-Verbose -message dbname=$dbname
Write-Verbose -message dumpdir=$dumpdir
Write-Verbose -message PGDUMP=$PGDUMP
Write-Verbose -message PSQL=$PSQL
Write-Verbose -message dbserver=$dbserver
Write-Verbose -message dbuser=$dbuser
Write-Verbose -message dbpassword=$dbpassword
Write-Verbose -message datestamp=$datestamp
$excludedb="('template0','template1','postgres')"
# $excludedb="('template0','template1','postgres','atis-buh-new','atis-doc','mon-buh','mon-zup','ml-buh','ml-zup')"
$sql_listdb="select datname from pg_database where not datname in $excludedb order by datname;"
$env:PGPASSWORD = $dbpassword
$datestamp = Get-Date -UFormat "%Y%m%d-%H%M%S"
$alldbdir = "$dumpdir\\pgsql"
$IPCUser = "Administrator" # Authentication
$IPCPwd = "media!!2004" # for IPC$ share
$DstHost = "backupserver" # robocopy dest
$DstDir = "D$\1C\pgsql" # robocopy dest
$SrcDir = "E:\tmp\backup\pgsql" # robocopy source
$LogPath = "C:\!Scripts\1c_rbcp.log" # robocopy log
$Params = "/E" # Robocopy params
Write-Verbose -message "Проверяем указана ли база данных для копирования"
if ($dbname -eq "") {
Write-Verbose -message "Проверяем, существует ли папка $alldbdir"
if(!(Test-Path -Path $alldbdir )){
Write-Verbose -message "Cоздаём папку $dumpdir"
New-Item -ItemType directory -Path $alldbdir | Out-Null
} else {
Write-Verbose -message "Удаляем папку с дампами"
Remove-Item -path $alldbdir -Force -Recurse | Out-Null
New-Item -ItemType directory -Path $alldbdir | Out-Null
}
Write-Verbose -message "Делаем дамп каждой БД кроме $excludedb"
$dblist = &$PSQL -t -h $dbserver -U $dbuser -c $sql_listdb
foreach($db in $dblist) {
$db = $db.TrimStart()
if ($db -ne "") {
$dbname=$db
Write-Verbose -message "Делаем дамп БД $dbname"
# &$PGDUMP -h $dbserver -U $dbuser --dbname=$dbname --file=$alldbdir\$($dbname)__$datestamp.sql.gz --compress=1
&$PGDUMP -Fc -b -h $dbserver -U $dbuser --dbname=$dbname --file=$alldbdir\$($dbname)__$datestamp.backup
}
Write-Verbose -message "Создание дампов завершено"
Write-Verbose -message "Начинаем копирование дампов robocopy"
Write-Verbose -message "Авторизуемся на $DstHost"
NET USE \\$DstHost\ipc$ /U:"$IPCUser" $IPCPwd
Write-Verbose -message "Копируем $SrcDir на \\$DstHost\$DstDir"
robocopy.exe /NP $SrcDir \\$DstHost\$DstDir\ $Params /UNILOG:$LogPath
Write-Verbose -message "Отключаемся от $DstHost"
NET USE \\$DstHost\ipc$ /D
Write-Verbose -message "Выполнение завершено"
} else {
if(!(Test-Path -Path $dumpdir\$dbname )){
Write-Verbose -message "Cоздаём папку $dumpdir\$dbname"
New-Item -ItemType directory -Path $dumpdir\$dbname | Out-Null
} else {
Write-Verbose -message "Удаляем папку с дампами"
Remove-Item -path $dumpdir\$dbname -Force -Recurse | Out-Null
New-Item -ItemType directory -Path $dumpdir\$dbname | Out-Null
}
Write-Verbose -message "Добавляем разрешения для Network Service"
$acl = Get-Acl "$dumpdir\$dbname"
$ar = New-Object System.Security.AccessControl.FileSystemAccessRule("NT AUTHORITY\NETWORK SERVICE","FullControl","Allow")
$acl.SetAccessRule($ar)
$acl | Set-Acl "$dumpdir\$dbname"
if ($separateconfig -eq "" ) {
Write-Verbose -message "Делаем дамп указанной БД $dbname в $dumpdir\\$($dbname)__$datestamp.sql.gz"
#&$PGDUMP -h $dbserver -U $dbuser --dbname=$dbname --file=$dumpdir\\$($dbname)\\$($dbname)__$datestamp.sql.gz --compress=1
&$PGDUMP -Fc -b -h $dbserver -U $dbuser --dbname=$dbname --file=$dumpdir\\$($dbname)\\$($dbname)__$datestamp.backup
} else {
# Write-Verbose -message "$PGDUMP -h $dbserver -U $dbuser --dbname=$dbname --file=$dumpdir\$dbname\$dbname-config-scheme__$datestamp.sql -s -t config"
Write-Verbose -message "Делаем дамп схемы $dbname таблицы config scheme $dumpdir\$dbname\$dbname-config-scheme__$datestamp.sql"
&$PGDUMP -h $dbserver -U $dbuser --dbname=$dbname --file=$dumpdir\$dbname\$dbname-config-scheme__$datestamp.sql -s -t config
#Write-Verbose -message "$PSQL -h $dbserver -U $dbuser --dbname=$dbname -c ""COPY public.config TO '$dumpdir\\$dbname\\$dbname-config-datafile__$datestamp.bin' WITH BINARY;"""
Write-Verbose -message "Делаем бинарный дамп $dbname таблицы config binary $dumpdir\\$dbname\\$dbname-config-datafile__$datestamp.bin"
&$PSQL -h $dbserver -U $dbuser --dbname=$dbname -c "COPY public.config TO '$dumpdir\\$dbname\\$dbname-config-datafile__$datestamp.bin' WITH BINARY;"
# Write-Verbose -message "$dumpdir\$($dbname)__$datestamp.sql.gz -T config --compress=1"
Write-Verbose -message "Делаем частичный дамп $dbname без config $dumpdir\$dbname\$($dbname)__$datestamp.sql.gz"
&$PGDUMP -h $dbserver -U $dbuser --dbname=$dbname --file=$dumpdir\$dbname\$($dbname)__$datestamp.sql.gz -T config --compress=1
}
}
пятница, 26 ноября 2021 г.
IPSEC Mikrotik Strongswan
Strongswan:
config setup
charondebug="all"
uniqueids=yes
conn con1
# ike=blowfish-sha1-modp1024!
# esp=blowfish-sha1!
ike=aes256-sha256-modp2048!
esp=aes256-sha256!
aggressive=no
keyingtries=%forever
ikelifetime=28800s
lifetime=3600s
dpddelay=30s
dpdtimeout=120s
dpdaction=restart
keyexchange=ikev1
authby=secret
type=tunnel
leftid=%net_behind_mktk%
left=%net_behind_mktk%
leftsubnet=%net_behind_mktk%/32
rightid=%mktk_inet_ip%
right=%mktk_inet_ip%
# rightsubnet=%1_net_behind_mktk%,%2_net_behind_mktk%
conn con1-1
also=mlg1
rightsubnet=%1_net_behind_mktk%
auto=start
conn con1-2
also=mlg1
rightsubnet=%2_net_behind_mktk%
auto=start
charondebug="all"
uniqueids=yes
conn con1
# ike=blowfish-sha1-modp1024!
# esp=blowfish-sha1!
ike=aes256-sha256-modp2048!
esp=aes256-sha256!
aggressive=no
keyingtries=%forever
ikelifetime=28800s
lifetime=3600s
dpddelay=30s
dpdtimeout=120s
dpdaction=restart
keyexchange=ikev1
authby=secret
type=tunnel
leftid=%net_behind_mktk%
left=%net_behind_mktk%
leftsubnet=%net_behind_mktk%/32
rightid=%mktk_inet_ip%
right=%mktk_inet_ip%
# rightsubnet=%1_net_behind_mktk%,%2_net_behind_mktk%
conn con1-1
also=mlg1
rightsubnet=%1_net_behind_mktk%
auto=start
conn con1-2
also=mlg1
rightsubnet=%2_net_behind_mktk%
auto=start
Mikrotik:
/ip ipsec profile add \
enc-algorithm=aes-256 \
hash-algorithm=sha256 \
name=strongswan
/ip ipsec peer add \
/ip ipsec peer add \
address=%linux_inet_ip% \
local-address=%mktk_inet_ip% \
name=strongswan \
profile=strongswan \
send-initial-contact=no
/ip ipsec proposal add \
/ip ipsec proposal add \
auth-algorithms=sha256 \
enc-algorithms=aes-256-cbc \
lifetime=1h \
name=strongswan \
pfs-group=modp2048
/ip ipsec identity add \
/ip ipsec identity add \
notrack-chain=prerouting \
peer=strongswan \
secret=%PSK%
/ip ipsec policy add \
/ip ipsec policy add \
dst-address=%net_behind_linux% \
sa-dst-address=%linux_inet_ip% \
sa-src-address=%mktk_inet_ip% \
src-address=%1_net_behind_mktk% \
level=unique \
proposal=strongswan \
tunnel=yes
/ip ipsec policy add \
/ip ipsec policy add \
dst-address=%net_behind_linux% \
sa-dst-address=%linux_inet_ip% \
sa-src-address=%mktk_inet_ip% \
src-address=%2_net_behind_mktk% \
level=unique \
proposal=strongswan \
tunnel=yes
Ратнер Арсений, arsenyratner@gmail.com, 7 985 273 2090
четверг, 18 ноября 2021 г.
Инвентаризация подключенных информационных баз 1с на компьютерах в домене
Сначала получим список всех компьютеров
Get-ADComputer -Filter * -Properties * |
Select -Property Name,DNSHostName,Enabled,LastLogonDate,operatingSystem |
Export-CSV "C:\Users\Public\Documents\AllComputers.csv" -Delimiter ';' -Encoding UTF8 -NoTypeInformation
Select -Property Name,DNSHostName,Enabled,LastLogonDate,operatingSystem |
Export-CSV "C:\Users\Public\Documents\AllComputers.csv" -Delimiter ';' -Encoding UTF8 -NoTypeInformation
Проходим по списку компьютеров и копируем файлы AppData\Roaming\1C\1CEStart\ibases.v8i в одну папку. Можно скрипт добавить в планировщик, он будет собирать файлы по расписанию чтобы обработать компьютеры которые в данный момент были выключены.
$port=445
$timeout=100
$VerbosePreference = "Continue"
#$VerbosePreference = "SilentlyContinue"
$dst = 'C:\Users\Public\Documents\ibases'
$csv = 'C:\Users\Public\Documents\ibases.csv'
$timeout=100
$VerbosePreference = "Continue"
#$VerbosePreference = "SilentlyContinue"
$dst = 'C:\Users\Public\Documents\ibases'
$csv = 'C:\Users\Public\Documents\ibases.csv'
$compList = Get-Content "C:\Users\Public\Documents\computerlist.txt"
foreach ($comp in $compList) {
$requestCallback = $state = $null
$client = New-Object System.Net.Sockets.TcpClient
$beginConnect = $client.BeginConnect($comp,$port,$requestCallback,$state)
Start-Sleep -milli $timeOut
$src = "\\$comp\c$\users\"
if ($client.Connected) {
#write-verbose -Message "$comp connected"
$ibasespath = '\AppData\Roaming\1C\1CEStart\ibases.v8i'
$GC = Get-ChildItem $src
# where{$_.name -notcontains 'Public' -and $_.name -notcontains 'Default'}
ForEach ($user in $GC) {
$v8i = "$($src)$($user)$($ibases_path)"
if (Test-Path -Path "$v8i") {
write-verbose -Message "Copy $v8i to $dst\$($user)_$($comp)_ibases.txt"
Copy-Item -Path $v8i -Destination "$dst\$($user)_$($comp)_ibases.txt"
Parse-Config -ConfigFilePath $v8i
} else {
Write-Verbose -Message "Not found: $($src)$($user)$($ibases_path)"
}
}
} else {
Write-Verbose -Message "$comp - connection failed"
}
$client.Close()
}
foreach ($comp in $compList) {
$requestCallback = $state = $null
$client = New-Object System.Net.Sockets.TcpClient
$beginConnect = $client.BeginConnect($comp,$port,$requestCallback,$state)
Start-Sleep -milli $timeOut
$src = "\\$comp\c$\users\"
if ($client.Connected) {
#write-verbose -Message "$comp connected"
$ibasespath = '\AppData\Roaming\1C\1CEStart\ibases.v8i'
$GC = Get-ChildItem $src
# where{$_.name -notcontains 'Public' -and $_.name -notcontains 'Default'}
ForEach ($user in $GC) {
$v8i = "$($src)$($user)$($ibases_path)"
if (Test-Path -Path "$v8i") {
write-verbose -Message "Copy $v8i to $dst\$($user)_$($comp)_ibases.txt"
Copy-Item -Path $v8i -Destination "$dst\$($user)_$($comp)_ibases.txt"
Parse-Config -ConfigFilePath $v8i
} else {
Write-Verbose -Message "Not found: $($src)$($user)$($ibases_path)"
}
}
} else {
Write-Verbose -Message "$comp - connection failed"
}
$client.Close()
}
Соберём информацию из файлов в один csv
$VerbosePreference = "Continue"
$dst = 'C:\Users\Public\Documents\ibases\'
$csv = 'C:\Users\Public\Documents\ibases2.csv'
$comp = ''
Function parse-v8i {
param (
$v8iFilePath
)
$dbfn = ''
$srv = ''
$db = ''
$ConfigContent = Get-Content $v8iFilePath -Encoding UTF8
$IBases = $ConfigContent | ForEach-Object {
if ($_ -match '(?''dbfn''^\[.+\]$)'){
$dbfn = $Matches['dbfn']
}
if ($_ -match 'Connect=Srvr="(?''Srv''[^"]+)";Ref="(?''db''[^"]+)";'){
$srv = $Matches['srv']
$db = $Matches['DB']
}
if ($db -and $dbfn -and $srv){
$content=[pscustomobject]@{
DBFN = $dbfn
SRV = $srv
IB = $db
filename = $file
}
$dbfn = ''
$srv = ''
$db = ''
$content | Export-Csv -Path $csv -Delimiter ';' -Encoding UTF8 -NoTypeInformation -Append
}
}
}
$GC = Get-ChildItem $dst
ForEach ($file in $GC) {
$v8i = "$($dst)$($file)"
write-verbose -Message "Parse $v8i"
Parse-Config -v8iFilePath $v8i
}
$dst = 'C:\Users\Public\Documents\ibases\'
$csv = 'C:\Users\Public\Documents\ibases2.csv'
$comp = ''
Function parse-v8i {
param (
$v8iFilePath
)
$dbfn = ''
$srv = ''
$db = ''
$ConfigContent = Get-Content $v8iFilePath -Encoding UTF8
$IBases = $ConfigContent | ForEach-Object {
if ($_ -match '(?''dbfn''^\[.+\]$)'){
$dbfn = $Matches['dbfn']
}
if ($_ -match 'Connect=Srvr="(?''Srv''[^"]+)";Ref="(?''db''[^"]+)";'){
$srv = $Matches['srv']
$db = $Matches['DB']
}
if ($db -and $dbfn -and $srv){
$content=[pscustomobject]@{
DBFN = $dbfn
SRV = $srv
IB = $db
filename = $file
}
$dbfn = ''
$srv = ''
$db = ''
$content | Export-Csv -Path $csv -Delimiter ';' -Encoding UTF8 -NoTypeInformation -Append
}
}
}
$GC = Get-ChildItem $dst
ForEach ($file in $GC) {
$v8i = "$($dst)$($file)"
write-verbose -Message "Parse $v8i"
Parse-Config -v8iFilePath $v8i
}
Ратнер Арсений, arsenyratner@gmail.com, 7 985 273 2090
Генератор паролей apg или wapg для Windows
-n15 -EOI10l -a0 -m 10 -x 10 -MNCL -c cl_seed
Генерирует 15 произносимых паролей
Без неоднозначных символов O, I, 1, 0, l
Ратнер Арсений, arsenyratner@gmail.com, 7 985 273 2090
среда, 10 ноября 2021 г.
Не пускает доменных пользователей OL8 Centos 8
Не пускает доменных пользователей:
journalctl -f
pam_sss(sshd:auth): authentication success; logname= uid=0 euid=0 tty=ssh ruser= rhost=192.168.20.81 user=admin.appcpam_sss(sshd:account): Access denied for user admin.appc: 4 (System error)
Failed password for admin.appc from 192.168.20.81 port 52914 ssh2
fatal: Access denied for user admin.appc by PAM account configuration [preauth]
Решение:
Добавить в sssd.conf
[domain/.....]
ad_gpo_access_control = disabled
Ратнер Арсений, arsenyratner@gmail.com, 7 985 273 2090
среда, 3 ноября 2021 г.
Сброс пароля пользователя в 1С 8.3.17 ...
-- Переименовать таблицу v8users
EXEC sp_rename 'v8users', 'v8users_tmp'
GO
-- Переименовать users.usr в users.usr_tmp
UPDATE Params
SET FileName = 'users.usr_tmp'
WHERE FileName = 'users.usr'
GO
-- Создать пустую таблицу v8users
create table v8users(
ID binary(16) NOT NULL,
Name nvarchar(64) NOT NULL,
Descr nvarchar(128) NOT NULL,
OSName nvarchar(128) NULL,
Changed datetime2(0) NOT NULL,
RolesID numeric(10,0) NOT NULL,
Show binary(1) NOT NULL,
Data varbinary(max) NOT NULL,
EAuth binary(1) NULL,
AdmRole binary(1) NULL,
UsSprH numeric(10,0) NULL,
PRIMARY KEY (ID)
);
-- меняем пароль
-- удаляем таблицу
DROP TABLE v8users
GO
-- возвращаем копию таблицы
EXEC sp_rename 'v8users_old', 'v8users'
GO
UPDATE Params
SET FileName = 'users.usr'
WHERE FileName = 'users.usr_old'
GO
EXEC sp_rename 'v8users', 'v8users_tmp'
GO
-- Переименовать users.usr в users.usr_tmp
UPDATE Params
SET FileName = 'users.usr_tmp'
WHERE FileName = 'users.usr'
GO
-- Создать пустую таблицу v8users
create table v8users(
ID binary(16) NOT NULL,
Name nvarchar(64) NOT NULL,
Descr nvarchar(128) NOT NULL,
OSName nvarchar(128) NULL,
Changed datetime2(0) NOT NULL,
RolesID numeric(10,0) NOT NULL,
Show binary(1) NOT NULL,
Data varbinary(max) NOT NULL,
EAuth binary(1) NULL,
AdmRole binary(1) NULL,
UsSprH numeric(10,0) NULL,
PRIMARY KEY (ID)
);
-- меняем пароль
-- удаляем таблицу
DROP TABLE v8users
GO
-- возвращаем копию таблицы
EXEC sp_rename 'v8users_old', 'v8users'
GO
UPDATE Params
SET FileName = 'users.usr'
WHERE FileName = 'users.usr_old'
GO
Центос не обновляется
Надо было сделать:
unset LD_LIBRARY_PATH
[root@vm-ora7 yum.repos.d]# yum update
Plugin "refresh-packagekit" can't be imported
Loaded plugins: fastestmirror, priorities, security
Determining fastest mirrors
* base: centos.tt.co.kr
* updates: centos.tt.co.kr
base | 3.7 kB 00:00
Traceback (most recent call last):
File "/usr/bin/yum", line 29, in <module>
yummain.user_main(sys.argv[1:], exit_code=True)
File "/usr/share/yum-cli/yummain.py", line 276, in user_main
errcode = main(args)
File "/usr/share/yum-cli/yummain.py", line 129, in main
result, resultmsgs = base.doCommands()
File "/usr/share/yum-cli/cli.py", line 434, in doCommands
self._getTs(needTsRemove)
File "/usr/lib/python2.6/site-packages/yum/depsolve.py", line 99, in _getTs
self._getTsInfo(remove_only)
File "/usr/lib/python2.6/site-packages/yum/depsolve.py", line 110, in _getTsInfo
pkgSack = self.pkgSack
File "/usr/lib/python2.6/site-packages/yum/__init__.py", line 883, in <lambda>
pkgSack = property(fget=lambda self: self._getSacks(),
File "/usr/lib/python2.6/site-packages/yum/__init__.py", line 668, in _getSacks
self.repos.populateSack(which=repos)
File "/usr/lib/python2.6/site-packages/yum/repos.py", line 294, in populateSack
sack.populate(repo, mdtype, callback, cacheonly)
File "/usr/lib/python2.6/site-packages/yum/yumRepo.py", line 164, in populate
if self._check_db_version(repo, mydbtype):
File "/usr/lib/python2.6/site-packages/yum/yumRepo.py", line 222, in _check_db_version
return repo._check_db_version(mdtype)
File "/usr/lib/python2.6/site-packages/yum/yumRepo.py", line 1263, in _check_db_version
repoXML = self.repoXML
File "/usr/lib/python2.6/site-packages/yum/yumRepo.py", line 1462, in <lambda>
repoXML = property(fget=lambda self: self._getRepoXML(),
File "/usr/lib/python2.6/site-packages/yum/yumRepo.py", line 1454, in _getRepoXML
self._loadRepoXML(text=self)
File "/usr/lib/python2.6/site-packages/yum/yumRepo.py", line 1444, in _loadRepoXML
return self._groupLoadRepoXML(text, self._mdpolicy2mdtypes())
File "/usr/lib/python2.6/site-packages/yum/yumRepo.py", line 1419, in _groupLoadRepoXML
if self._commonLoadRepoXML(text):
File "/usr/lib/python2.6/site-packages/yum/yumRepo.py", line 1237, in _commonLoadRepoXML
result = self._getFileRepoXML(local, text)
File "/usr/lib/python2.6/site-packages/yum/yumRepo.py", line 1015, in _getFileRepoXML
size=102400) # setting max size as 100K
File "/usr/lib/python2.6/site-packages/yum/yumRepo.py", line 837, in _getFile
size=size
File "/usr/lib/python2.6/site-packages/urlgrabber/mirror.py", line 408, in urlgrab
return self._mirror_try(func, url, kw)
File "/usr/lib/python2.6/site-packages/urlgrabber/mirror.py", line 394, in _mirror_try
return func_ref( *(fullurl,), **kwargs )
File "/usr/lib/python2.6/site-packages/urlgrabber/grabber.py", line 985, in urlgrab
return self._retry(opts, retryfunc, url, filename)
File "/usr/lib/python2.6/site-packages/urlgrabber/grabber.py", line 886, in _retry
r = apply(func, (opts,) + args, {})
File "/usr/lib/python2.6/site-packages/urlgrabber/grabber.py", line 980, in retryfunc
apply(cb_func, (obj, )+cb_args, cb_kwargs)
File "/usr/lib/python2.6/site-packages/yum/yumRepo.py", line 1501, in _checkRepoXML
repoXML = repoMDObject.RepoMD(self.id, filepath)
File "/usr/lib/python2.6/site-packages/yum/repoMDObject.py", line 124, in __init__
self.parse(srcfile)
File "/usr/lib/python2.6/site-packages/yum/repoMDObject.py", line 140, in parse
parser = iterparse(infile)
File "/usr/lib/python2.6/site-packages/yum/misc.py", line 1169, in cElementTree_iterparse
_cElementTree_import()
File "/usr/lib/python2.6/site-packages/yum/misc.py", line 1164, in _cElementTree_import
import cElementTree
ImportError: No module named cElementTree
Подписаться на:
Сообщения (Atom)