четверг, 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)

среда, 31 октября 2018 г.

User account blocking for 100 days is not logged and mailbox not used for another actions (full access/forward mails)

#by me ;)

import-module activedirectory
Add-PSSnapin Microsoft.Exchange.Management.PowerShell.SnapIn;

$LOGFILE="c:\scripts\aduserblock1.log"
$SMTPSERVER = "mail.domain.local"

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


function SendEmaiToSD($msgstr){
Send-MailMessage -From powershell@domain.local -To sd@domain.local -Subject "Скрипт блокировки учетных записей в домене domain.loc вызвал ошибку выполнения." -Body $($msgstr) -SmtpServer $SMTPSERVER -Priority High -Encoding UTF8
}

function main{
$mdate = (Get-date).Add(-100d)
$oldusers = get-aduser -Filter {Enabled -eq $true -and msExchMailboxGuid -like "*"} -properties samaccountname, lastlogondate | where{$_.samaccountname -match "^\w{1,2}\.\w+$" -and $_.LastLogonDate -lt $mdate -and $_.LastLogonDate -ne $null} | sort-object lastlogondate | select samaccountname, lastlogondate

foreach($user in $oldusers){
$userIdentities = @()
$usermailbox = get-mailbox -Identity $($user.samaccountname)
if($usermailbox.ForwardingAddress -ne $null){
#write-host detected Forward for $user.samaccountname
continue
}
foreach($userSecurityIdentifier in ($usermailbox | get-mailboxpermission | ?{$_.IsInherited -eq $false -and $_.user -notlike "*NT*AUTH*"}).User.SecurityIdentifier.Value){
if($userSecurityIdentifier -eq $null){
continue
}
$adobject = get-adobject -Filter 'objectSID -like $userSecurityIdentifier -and ObjectClass -eq "user"'
$userIdentities+=$adobject
}
if($userIdentities.Count -gt 0){
#write-host User  $user.samaccountname has another owners for mailbox lastlogondate=$user.lastlogondate
continue
}
log("User account "+$user.samaccountname+" Disabled")
Set-ADUser -Identity $user.samaccountname -Enabled $false
}
}

try{
main
}
catch
{
$ErrorMessage = $_.Exception.Message
SendEmaiToSD($ErrorMessage)
}

вторник, 11 сентября 2018 г.

Crypt. C#
Появилась задача сделать ActiveX компонент для encrypt/decrypt со статическими ключами/солью. Разбор полётов с примерами породил такой сырец:
(внимание гостям, это рабочий варинт. не прилизан, не урезан не обфусцирован, много копи-паст :))
Как есть. Вектор и соль менять.

using System;
using System.Runtime.InteropServices;
using System.IO;
using System.Text;
using System.Security.Cryptography;

namespace AlexCrypt
{
    [ComVisible(true)]
    [Guid("235D87E1-9BFA-47AB-9E97-CF1A2D342054")]
    public interface IAlexCrypt
    {
        string Encrypt(
            string cipherText,
            string passPhrase);
        string Decrypt(
            string cipherText,
            string passPhrase);
    }

    [Guid("162E64E6-99D6-47BB-B52E-1A4205EFF5AF")]
    [ClassInterface(ClassInterfaceType.None)]
    //[ProgId("AlexCrypt")]
    [ComVisible(true)]
    public class AlexCrypt : IAlexCrypt
    {
        public string Encrypt
        (
            string plainText,
            string passPhrase)
        {
            string saltValue = "*4b5FHMwa$h22=Wh";
            string hashAlgorithm = "SHA1";
            int passwordIterations = 2;
            string initVector = "sQY*K&TF8MMcR3=r";
            int keySize = 256;
            string cipherText = "";

            try
            {
                byte[] initVectorBytes = Encoding.ASCII.GetBytes(initVector);
                byte[] saltValueBytes = Encoding.ASCII.GetBytes(saltValue);
                byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);

                PasswordDeriveBytes password = new PasswordDeriveBytes
                (
                    passPhrase,
                    saltValueBytes,
                    hashAlgorithm,
                    passwordIterations
                );
                byte[] keyBytes = password.GetBytes(keySize / 8);
                RijndaelManaged symmetricKey = new RijndaelManaged();
                symmetricKey.Mode = CipherMode.CBC;
                ICryptoTransform encryptor = symmetricKey.CreateEncryptor
                (
                    keyBytes,
                    initVectorBytes
                );
                MemoryStream memoryStream = new MemoryStream();
                CryptoStream cryptoStream = new CryptoStream
                (
                    memoryStream,
                    encryptor,
                    CryptoStreamMode.Write
                );

                cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
                cryptoStream.FlushFinalBlock();
                byte[] cipherTextBytes = memoryStream.ToArray();
                memoryStream.Close();
                cryptoStream.Close();
                cipherText = Convert.ToBase64String(cipherTextBytes);
            }
            catch
            {
                cipherText = "Error";
            }
            return cipherText;
        }

        public string Decrypt
        (
            string cipherText,
            string passPhrase
        )
        {
            string saltValue = "*4b5FHMwa$h22=Wh";
            string hashAlgorithm = "SHA1";
            int passwordIterations = 2;
            string initVector = "sQY*K&TF8MMcR3=r";
            int keySize = 256;
            string plainText = "";
            try
            {
                byte[] initVectorBytes = Encoding.ASCII.GetBytes(initVector);
                byte[] saltValueBytes = Encoding.ASCII.GetBytes(saltValue);
                byte[] cipherTextBytes = Convert.FromBase64String(cipherText);
                PasswordDeriveBytes password = new PasswordDeriveBytes
                (
                    passPhrase,
                    saltValueBytes,
                    hashAlgorithm,
                    passwordIterations
                );
                byte[] keyBytes = password.GetBytes(keySize / 8);
                RijndaelManaged symmetricKey = new RijndaelManaged();
                symmetricKey.Mode = CipherMode.CBC;
                ICryptoTransform decryptor = symmetricKey.CreateDecryptor
                (
                    keyBytes,
                    initVectorBytes
                );
                MemoryStream memoryStream = new MemoryStream(cipherTextBytes);
                CryptoStream cryptoStream = new CryptoStream
                (
                    memoryStream,
                    decryptor,
                    CryptoStreamMode.Read
                );
                byte[] plainTextBytes = new byte[cipherTextBytes.Length];
                int decryptedByteCount = cryptoStream.Read
                (
                    plainTextBytes,
                    0,
                    plainTextBytes.Length
                );
                memoryStream.Close();
                cryptoStream.Close();
                plainText = Encoding.UTF8.GetString
                (
                    plainTextBytes,
                    0,
                    decryptedByteCount
                );
            }
            catch
            {   
                plainText = "Error";
            }
            return plainText;
        }
    }
}