• Home
  • PS
  • C#
  • Perl
  • MSSQL
  • MariaDB
  • Linux
  • Docker
  • MacOS
  • PG
  • Exchange Server
  • Windows
  • Other

Extract all DLLs from a Nuget package (nupkg) with Windows cmd batch file

Details
Written by: po3dno
Category: C#
Created: 13 November 2024
Hits: 196
@echo off
REM Extracts all .dll files from nugets in this folder or its subfolders and copies them to a subfolders
REM .
REM Note: Uses .NET 4.5 to unzip the nugets. If this fails, use 7zip or something similar. 
REM       See http://stackoverflow.com/questions/17546016/how-can-you-zip-or-unzip-from-the-command-prompt-using-only-windows-built-in-ca/26843122#26843122


echo Extracting all dlls from nugets to folder \extracted-dlls

REM %mypath% is where the batch file is located
set mypath=%~dp0

set temppath=%~dp0temp\
set dllpath=%~dp0extracted-dlls\

REM Delete old dlls
echo Deleting old files
rd /s /q %dllpath%"
mkdir %dllpath%

rem traverse all nupkg files
pushd %mypath%
	for /r %%a in (*.nupkg) do (
		
		echo \- Processing %%~nxa
		
		REM unzip nuget to %temppath% folder.
		powershell.exe -nologo -noprofile -command "& { Add-Type -A 'System.IO.Compression.FileSystem'; [IO.Compression.ZipFile]::ExtractToDirectory('%%a', '%temppath%'); }
		
		REM Copy all dlls 
		REM See: http://stackoverflow.com/questions/11720681/windows-batch-copy-files-from-subfolders-to-one-folder
		pushd %temppath%
			for /r %%b in (*.dll) do (
				echo     \- Found %%~nxb
				COPY "%%b" "%dllpath%%%~nxb"
			)
		popd
		
		REM Delete Temp folder
		rd /s /q %temppath%"
    )
popd

pause

RemoveLocalAdm_PC

Details
Written by: po3dno
Category: C#
Created: 20 October 2021
Hits: 995
using System;
using System.Management;
using System.Text.RegularExpressions;
using System.DirectoryServices;

namespace RemoveLocalAdm_PC
{
    class Program
    {
        static void Main(string[] args)
        {
            string PC = System.Environment.MachineName;
            string groupName = "local_administrator_" + PC;
            string sid = "544";

            ManagementObjectSearcher searchGroup = new ManagementObjectSearcher(@"SELECT name FROM Win32_Group where LocalAccount = true and sid = 'S-1-5-32-544'");
            ManagementObjectCollection adminGroup = searchGroup.Get();
            string gr = null;

            /*
            foreach (ManagementObject group in adminGroup)
            {
                gr = group["Name"].ToString();
                //Console.WriteLine(group["Name"].ToString());
                continue;
            }
            */

            if (gr != null)
            {
                ManagementObjectSearcher search = new ManagementObjectSearcher("SELECT * FROM Win32_GroupUser where (groupcomponent='win32_group.name=\"" + gr + "\",domain=\"" + PC + "\"')");
                ManagementObjectCollection userList = search.Get();

                foreach (ManagementObject user in userList)
                {
                    string pattern = ".+cimv2:win32_(.+).Domain=\"(.+)\",Name=\"(.+)\"";
                    Regex rgx = new Regex(pattern, RegexOptions.IgnoreCase);

                    Match m = Regex.Match(user["PartComponent"].ToString(), pattern, RegexOptions.IgnoreCase);

                    /*
                    if (m.Success)
                    {
                        //Console.WriteLine(m.Groups[1].Value + ' ' + m.Groups[2].Value + ' ' + m.Groups[3].Value);
                    }
                    */

                    DirectoryEntry localGroup = new DirectoryEntry(String.Format("WinNT://{0}/{1},group", Environment.MachineName, gr));
                    DirectoryEntry removeobj = new DirectoryEntry(String.Format("WinNT://{0}/{1}", m.Groups[2].Value, m.Groups[3].Value));

                    Console.WriteLine(String.Format("WinNT://{0}/{1}", m.Groups[2].Value, m.Groups[3].Value));

                    if (m.Groups[2].Value == PC && (m.Groups[3].Value == "Администратор" || m.Groups[3].Value == "Administrator")) { continue; }
                    if (m.Groups[2].Value == "DOMAIN" && m.Groups[3].Value == "Workstation_admins") { continue; }
                    if (m.Groups[2].Value == "DOMAIN" && m.Groups[3].Value == groupName) { continue; }

                    try
                    {
                        localGroup.Invoke("Remove", new object[] { removeobj.Path });
                        localGroup.CommitChanges();
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("Try remove from group from: {0} group or user: {1}..." + Environment.NewLine + e.ToString(), gr, m.Groups[2].Value + @"\" + m.Groups[3].Value);
                    }

                }
            }


            //Console.ReadLine();
        }
    }
}

LocalGroup_AD

Details
Written by: po3dno
Category: C#
Created: 05 October 2021
Hits: 996
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.DirectoryServices;
using System.Management;
using System.Threading;

namespace LocalGroup_AD
{
    class Program
    {
        static void Main(string[] args)
        {
            string r = null;
            using (ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_OperatingSystem"))
            {
                ManagementObjectCollection information = searcher.Get();
                if (information != null)
                {
                    foreach (ManagementObject obj in information)
                    {
                        r = obj["ProductType"].ToString();
                    }
                }

                Console.WriteLine("ProductType: {0}", r);
            }

            string osType = null;
            switch (r)
            {
                case "1":  osType = "WKS"; break;
                case "3":  osType = "SRV"; break;
                default:
                    Console.WriteLine("No valid input for osType");
                    Environment.Exit(0);
                    break;
            }

            //Console.ReadKey();
            //Environment.Exit(0);

            if (args.Count() != 1)
            {
                Console.WriteLine("Usage: LocalGroup_AD.exe [adm|rdu]");
                Environment.Exit(0);
            }

            string PC = System.Environment.MachineName;
            string sid = null;

            string lGroup = null;
            string groupName = null;
            switch (args[0].ToLower())
            {
                case "adm": lGroup = "Administrators"; groupName = "local_administrator_" + PC; sid = "544";  break;
                case "rdu": lGroup = "RDU"; groupName = "local_rdu_" + PC; sid = "555";  break;
                default: 
                    Console.WriteLine("No valid input for groupName");  
                    Environment.Exit(0); 
                    break;
            }

            DirectoryEntry dom = new DirectoryEntry();

            string pathDN = "OU=" + lGroup + ",OU=" + osType + ",OU=LocalGroups,OU=Security Groups";

            Console.WriteLine(pathDN);
            DirectoryEntry ou = dom.Children.Find(pathDN);

            bool groupName_exist = false;
            try
            {
                DirectoryEntry childGroup = ou.Children.Find("CN=" + groupName);
                if (childGroup != null)
                    groupName_exist = true;
            }
            catch { }

            if (groupName_exist)
            {
                Console.WriteLine("Group {0} exist", groupName);
            }
            else
            {
                try
                {
                    DirectoryEntry group = ou.Children.Add("CN=" + groupName, "group");
                    group.Properties["samAccountName"].Value = groupName;


                    group.CommitChanges();
                }
                catch (Exception e)
                {
                    Console.WriteLine("Try add group to domain..." + Environment.NewLine + e.ToString());
                }
            }




            ManagementObjectSearcher searchGroup = new ManagementObjectSearcher(@"SELECT name FROM Win32_Group where LocalAccount = true and sid = 'S-1-5-32-"+ sid +"'");
            ManagementObjectCollection adminGroup = searchGroup.Get();
            string gr = null;

            foreach (ManagementObject group in adminGroup)
            {
                gr = group["Name"].ToString();
                Console.WriteLine(group["Name"].ToString());
                continue;
            }

            Thread.Sleep(10000);

            DirectoryEntry localGroup = new DirectoryEntry(String.Format("WinNT://{0}/{1},group", Environment.MachineName, gr));
            DirectoryEntry remoteGroup = new DirectoryEntry(String.Format("WinNT://{0}/{1}", Domain, groupName));
            try
            {
                localGroup.Invoke("Add", new object[] { remoteGroup.Path });
                localGroup.CommitChanges();
            }
            catch (Exception e)
            {
                Console.WriteLine("Try add group to local group..." + Environment.NewLine + e.ToString());
            }

        }
    }
}

чтение DNS лога

Details
Written by: po3dno
Category: C#
Created: 21 March 2019
Hits: 1101
using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Threading;
using System.Text.RegularExpressions;
using System.Collections.Concurrent;
 
 
namespace dns_log_parser
{
    class Program
    {
 
        static long offset = 0;
        //static FileStream file;
        static StreamReader reader;
 
        static ConcurrentDictionary<(string, string), int> dnsstat = new ConcurrentDictionary<(string, string), int>();
        static void Main(string[] args)
        {
            if (args.Count() < 1) {
                Console.WriteLine("Usage: dns_log_parser.exe [path_to_log]");
                Environment.Exit(0);
            }
 
            string sourceFile = args[0];
 
            if (!File.Exists(sourceFile))
            {
                Console.WriteLine("{0} not exist", sourceFile);
                Environment.Exit(0);
            }
 
            offset = (new FileInfo(sourceFile)).Length;
 
            Timer t = new Timer(TimerCallback, null, 0, 2000);
 
            while (true)
            {
                FileStream file = new FileStream(sourceFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                var info = new FileInfo(sourceFile);
                if (info.Length < offset)
                    offset = 0;
                using (new StreamReader(file))
                {
                    file.Seek(offset, SeekOrigin.Begin);
                    reader = new StreamReader(file);
 
                    file.Seek(offset, SeekOrigin.Begin);
                    if (!reader.EndOfStream)
                    {
                        do
                        {
                            string line = reader.ReadLine();
                            // ^.+Rcv\s+([0-9\.]+)\s+([0-9A-Fa-f]+)\s+.+\[.+\]\s+(\w+)\s+\(\d\)(.+)\(0\)$
                            // https://answers.splunk.com/answers/132364/dns-debug-log-dns-log-format-review.html
                            Regex regex = new Regex(@"^.+Rcv\s+([0-9\.]+)\s+([0-9A-Fa-f]+)\s+.+\[.+\]\s+(\w+)\s+\(\d\)(.+)\(0\)$");
 
                            Match match = regex.Match(line);
                            if (match.Success)
                            {
                                string ip = match.Groups[1].Value;
                                //string dsthost = match.Groups[4].Value;
                                string dsthost = Regex.Replace(match.Groups[4].Value, @"\(\d+\)+", ".");
 
                                int curcount;
                                if (dnsstat.TryGetValue((ip, dsthost), out curcount))
                                {
                                    dnsstat[(ip, dsthost)] = curcount + 1;
                                    if (curcount % 10 == 0)
                                    {
                                        //Console.WriteLine("ip: {0} dns: {1} count: {2}", ip, dsthost, curcount);
                                    }
                                }
                                else
                                {
                                    dnsstat.TryAdd((ip, dsthost), 1);
                                }
 
                                //Console.WriteLine("{0} {1}", ip, dsthost);
                            }
                               
                        } while (!reader.EndOfStream);
 
                        offset = file.Position;
                        //Console.WriteLine("{0}", offset);
                    }
                    reader.Close();
                    Thread.Sleep(100);
                }
            }
        }
        private static void TimerCallback(Object o)
        {
            ConcurrentDictionary<(string, string), int> dnsstatviewtemp = dnsstat;
 
            var dnsstatview = dnsstatviewtemp.OrderByDescending(x => x.Value).Take(50);
 
            Console.Clear();
 
            foreach (KeyValuePair<(string, string), int> item in dnsstatview)
            {
                Console.WriteLine("Key: {0}, Value: {1}", item.Key, item.Value);
 
            }
 
        }
    }
}

Delete WSUS 'Drivers'

Details
Written by: po3dno
Category: C#
Created: 30 September 2016
Hits: 1036

[reflection.assembly]::LoadWithPartialName("Microsoft.UpdateServices.Administration")

$wsus = [Microsoft.UpdateServices.Administration.AdminProxy]::GetUpdateServer();

$wsus.GetUpdates() | Where {$_.UpdateClassificationTitle -eq 'Drivers'} | ForEach-Object {$wsus.DeleteUpdate($_.Id.UpdateId.ToString()); Write-Host $_.Title removed }

 

$computerscope = New-Object Microsoft.UpdateServices.Administration.ComputerTargetScope

$updatescope = New-Object Microsoft.UpdateServices.Administration.UpdateScope

 

$wsus.GetSummariesPerUpdate($updatescope,$computerscope) | ?{$_.InstalledCount -ne 0} |select -First 1 | %{$_ | ft *; $wsus.GetUpdate([guid]$_.updateid)}

$wsus.GetSummariesPerUpdate($updatescope,$computerscope) | ?{$_.InstalledCount -eq 0 -and $_.DownloadedCount -eq 0 -and $_.NotInstalledCount -eq 0}

$wsus.GetSummariesPerUpdate($updatescope,$computerscope) | ?{$_.InstalledCount -eq 0 -and $_.DownloadedCount -eq 0 -and $_.NotInstalledCount -eq 0} | select -First 1 | %{$wsus.GetUpdate([guid]$_.updateid)}

$wsus.GetSummariesPerUpdate($updatescope,$computerscope) | ?{$_.InstalledCount -eq 0 -and $_.DownloadedCount -eq 0 -and $_.NotInstalledCount -eq 0} | %{$u = $wsus.GetUpdate([guid]$_.updateid); $wsus.DeleteUpdate($u.Id.UpdateId.ToString()); Write-Host $u.Title removed}

 

  1. Собираем информацию через WMI в БД MSSQL
  2. Настройки в ini файле на C#W
  3. Открываем файл на C#
  4. Читаем XLSL на C#

Page 1 of 2

  • 1
  • 2

Login Form

  • Forgot your password?
  • Forgot your username?

Statistics

  • Users 2
  • Articles 164
  • Articles View Hits 148993