пятница, 22 января 2021 г.

incredible find :)
find all not executable files in directory and set executable attribute for any

find /data -type f -name *.exe ! -perm /o+x -exec chmod o+x {} +


+ is not same ;

среда, 13 января 2021 г.

 OMNITRACKER
Отбираем все объекты RFCs у которых было движение статуса из Acceptance в Evaluation и для них устанавливаем в поле AcceptanceDate последнюю дату этого движения.


Set objApp = CreateObject("OtAut.OtApplication")
Set ActiveSession = objApp.MakeSession("localhost",5085,"","")

Set objFolder = ActiveSession.RequestFolders("RFCs")
Set objQuery = objFolder.MakeQuery

Set objHistSearch = objFolder.MakeHistorySearch
objHistSearch.StartDate = DateSerial(1970, 1, 1)
objHistSearch.EndDate = Now
objHistSearch.Field = "State"
objHistSearch.Type = 1 ' otHistSearchModification
objHistSearch.Value1 = "Acceptance"
objHistSearch.Value2 = "Evaluation"


Set objColumn = objQuery.AddColumn("UID")
objColumn.Type = 2 ' otQColTypeUniqueId
objQuery.AddHistorySearch objHistSearch
objQuery.Recursive = True

Set objRS = objQuery.Execute

Set objTransQuery = objFolder.MakeQuery
Set objColumn = objTransQuery.AddColumn("Date")
objColumn.Type = 3 ' otQColTypeStateTransDate
objColumn.Field = "State"
objColumn.StartDateField = "CreationDate"
objColumn.EndDate = Now
objColumn.DefaultDate = Now
objColumn.LastStateTransition = True
objColumn.FromState = "Acceptance"
objColumn.ToState = "Evaluation"
objTransQuery.Recursive = True

For i = 0 To objRs.RowCount - 1
    Set objFilter = objFolder.MakeFilter
    objFilter.SpecialField("UNIQUE_ID") = objRs(i, 0)
    objTransQuery.Filter = objFilter
    Set objTransRS = objTransQuery.Execute
    If objTransRS.RowCount = 1 Then
    Set objRFC = ActiveSession.GetRequestByUniqueId(objRs(i, 0))
    objRFC.Fields("AcceptanceDate").TValue = objTransRS(0, 0)
    objRFC.SaveEx 1023 - 32
    EndIf
Next

четверг, 12 ноября 2020 г.

Connect to foreign exchange ps

$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://XXXXXXX
Import-PSSession $Session -DisableNameChecking

среда, 30 сентября 2020 г.

Rebuild Indexes. MS SQL

DECLARE @TableName VARCHAR(255)

DECLARE @sql NVARCHAR(500)

DECLARE @fillfactor INT

SET @fillfactor = 80

DECLARE TableCursor CURSOR FOR

SELECT OBJECT_SCHEMA_NAME([object_id])+'.'+name AS TableName

FROM sys.tables

OPEN TableCursor

FETCH NEXT FROM TableCursor INTO @TableName

WHILE @@FETCH_STATUS = 0

BEGIN

SET @sql = 'ALTER INDEX ALL ON ' + @TableName + ' REBUILD WITH (FILLFACTOR = ' + CONVERT(VARCHAR(3),@fillfactor) + ')'

EXEC (@sql)

FETCH NEXT FROM TableCursor INTO @TableName

END

CLOSE TableCursor

DEALLOCATE TableCursor

GO

четверг, 30 января 2020 г.

transmission-vise.py for Netgear ReadyNas 10400. run's by crontab every 2 hours
how it works:
stop torrent if ratio has been reached or seeders>MAXSEEDERS
start torrent if only my seeding

what's all this:
Netgear ReadyNas 10400 is slow,  but most importantly - hot and noisy at his place, but most of all - if seeding more torrents, it can't share plex because low cpu one core speed.

note:
crontab must run script w/o dots
do like this in /etc/crontab:
/2 *    * * *   root    /root/scripts/transmission-vice_py

#!/usr/bin/python
from os import popen
from sys import exit
import re
import logging

logging.basicConfig(filename='/root/scripts/transmission-vice.log', format='%(asctime)s - %(message)s', level=logging.INFO)

maxratio = 5
maxseeders = 3
unknowndata = 0
tarray = []
rawtorrents=popen('transmission-remote 8181 -l | egrep -v "ID|Sum"').read()

for torrent in rawtorrents.split("\n"):
    if len(torrent)==0:
        break
    spltorrent=torrent.split()
    torrentdict={'ID':spltorrent[0],'Done':spltorrent[1],'ETA':spltorrent[4],
                 'Ratio':spltorrent[7],'Status':spltorrent[8],'Name':' '.join(tuple(spltorrent)[9:])}
    torrentstats=popen('transmission-remote 8181 -t'+torrentdict['ID']+' -it').read()
    stat = re.findall(r"(\d+)\sseeders",torrentstats)
    if len(stat)>0:
        torrentdict['Seeders']=stat[0]
    else:
        torrentdict['Seeders']=unknowndata
    stat = re.findall(r"(\d+)\sleechers",torrentstats)
    if len(stat)>0:
        torrentdict['Leechers']=stat[0]
    else:
        torrentdict['Leechers']=unknowndata
    tarray.append(torrentdict)

for torrent in tarray:
    print("Name:"+torrent["Name"]+" Status:"+torrent["Status"]+" Ratio:"+str(torrent["Ratio"])+" Seeders:"+str(torrent["Seeders"])+" ETA:"+str(torrent["ETA"]))
    peers = popen('transmission-remote 8181 -t'+torrent["ID"]+' -ip' + ' | egrep -v "Address"')
    peerasseeder = False
    for peer in peers:
        if int(float(peer.split()[2])) == 100:
            peerasseeder = True
    if int(torrent["Seeders"])<maxseeders and int(torrent["Leechers"])!=0 and not peerasseeder and float(torrent["Ratio"])<maxratio:
        if torrent["Status"]=="Stopped":
            result=popen('transmission-remote 8181 -t'+torrent["ID"]+' -s').read()
            logging.info("start:"+torrent["Name"]+" Ratio:"+str(torrent["Ratio"])+" Seeders:"+str(torrent["Seeders"]))
    elif  (peerasseeder or int(torrent["Seeders"])>3) and torrent["ETA"]=="Done" and float(torrent["Ratio"])>maxratio:
        if torrent["Status"]=="Idle" or torrent["Status"]=="Seeding":
            result=popen('transmission-remote 8181 -t'+torrent["ID"]+' -S').read()
            logging.info("stop:"+torrent["Name"]+" Ratio:"+str(torrent["Ratio"])+" Seeders:"+str(torrent["Seeders"]))
exit(0)

среда, 31 июля 2019 г.

Скрипт для поиска однофамильцев в AD. powershell
Namesakes detecting in ActiveDirectory, powershell

#by me, 2019

import-module activedirectory

$SMTPSERVER = "exch.domain.local"

function main{
$users = (get-aduser -filter {enabled -eq $true -and EmailAddress -like "*@*"} -properties DisplayName).DisplayName
$doubleDisplayNames = $users | group | where{$_.count -gt 1}
if($doubleDisplayNames.count -gt 0) {
Send-MailMessage -From powershell@domain.local -To achernov@domain.local -Subject "Обнаружены полные однофамильцы в домене domain.local" -Body $($doubleDisplayNames.Name -join "`n") -SmtpServer $SMTPSERVER -Priority High -Encoding UTF8
}
}#end of main

try{
 main
}
catch
{
 $ErrorMessage = $_.Exception.Message
 Send-MailMessage -From powershell@domain.local -To admin@domain.local -Subject "Скрипт поиска однофамильцев в домене domain.loc вызвал ошибку выполнения." -Body $($ErrorMessage) -SmtpServer $SMTPSERVER -Priority High -Encoding UTF8
}

среда, 13 февраля 2019 г.

<#
Скрипт очистки рабочих каталогов 1С пользователей. Скрипт для Terminal Server.
Принцип работы:
Логофит всех пользователей у которых запущен клиент 1С.
Удаляет каталоги формы [guid] из массива, определенного в переменной $global:dirs
Лог работы скрипта в файле с именем из переменной $logfile
Для запуска скрипта файл "C:\Program Files\1cv8\nightrestart" должен существовать
#>

$logfile = "C:\scripts\1C-TS-restartAndRemoveUsersWorkDirs.log"
$path = "C:\Program Files\1cv8\nightrestart"
$test = $false
$global:dirs = ("C:\Users\*\AppData\Local\1C\1Cv82\*","C:\Users\*\AppData\Roaming\1C\1Cv82\*","C:\Users\*\AppData\Local\1C\1Cv8\*","C:\Users\*\AppData\Roaming\1C\1Cv8\*","C:\Users\*\AppData\Roaming\1C\Файлы\")

if (-not(Test-Path $path)) {
    log("Script execution temporarily suspended. File C:\Program Files\1cv8\nightrestart not found.")
    Exit
}

function log([string]$txt)
{ add-content $logfile "$(Get-date): $txt" }


function LogoffAll {
# логофим всех пользователей у которых запущен клиент 1C
log("Logoff for all...")
$currentid = (Get-Process -PID $pid).SessionID
$proceses1c = Get-Process | Where-Object{$_.Name -like "1cv8" -or $_.Name -like "1cv8c"}
$sessionids = $proceses1c | select sessionid | Group-Object sessionid | select name
foreach ($sessionid in $sessionids) {if ($sessionid.name -ne "0" -and $sessionid.name -ne $currentid.ToString()) {logoff $sessionid.name}}
}

function RemoveDirs {
    $removedfiles = 0
foreach ($dirname in $global:dirs){
foreach ($dirtoremove in Get-ChildItem $dirname | Where {$_.Name -as [guid]}) {
try {
Remove-Item $dirtoremove -Force -Recurse -cf:$false -ErrorAction Stop -WhatIf:$test
$removedfiles++
}
catch {
log("Error. Can not remove dir " + $dirtoremove)
}
}
}
    return $removedfiles
}

#main section
log("Start...")
LogoffAll
$removeddirs = RemoveDirs
log("Dirs deleted: " + $removeddirs)