Главная


Showing posts with label english. Show all posts
Showing posts with label english. Show all posts

Sunday, 2 November 2025

JSON prompt as single workflow.

Hi all.

By the way, structured JSON prompts have another useful feature. Now we can put a whole series of actions(steps) into one prompt, making it like a single workflow.

For example, removing the background in one of my versions looks like this

1) Remove Background Ext:

{

  "Task": "Create a high-quality transparent image by removing the background from a source image.",

  "constraints": {

    "preserve_subject_details": true,

    "maintain_original_dimensions": true,

    "clean_edges": true

  },

  "steps": [

    {

      "step_id": 1,

      "name": "Generate High-Contrast Matte",

      "instructions": "Take the input image. Accurately segment the main subject(s) from the background. Replace the entire background with a solid, pure white color (hex #FFFFFF). The subject must be perfectly preserved with no alterations. The output image dimensions must be identical to the input image. Output this intermediate image as 'white_matte'."

    },

    {

      "step_id": 2,

      "name": "Create Transparency from Matte",

      "instructions": "Take the original input image and the 'white_matte' image from step 1. Use 'white_matte' as a pixel-perfect transparency mask for the original input image. Where 'white_matte' is pure white, the corresponding pixels of the original image must become fully transparent (alpha=0). Where 'white_matte' is not white, the original image pixels must be fully opaque (alpha=255). The anti-aliased (near-white) pixels along the subject's edge in 'white_matte' should be translated into corresponding levels of semi-transparency to ensure a smooth, clean edge. Output this as 'final_transparent_image'."

    }

  ],

  "Deliverables": {

    "transparent_png": "final_transparent_image"

  }

}

2) The same goes for creating a Loop Seamless Panorama:

{
  "Task": "Create a seamless horizontal panoramic loop from an image.",
  "constraints": {
    "no_distortion": true,
    "maintain_subject_integrity": true
  },
  "steps": [
    {
      "step_id": 1,
      "name": "Horizontal Expansion",
      "instructions": "Take the input image and expand it horizontally by approximately 2.5 times its original width. The generated content should naturally extend the background elements (like sky, landscape, etc.) without distorting the main subject. Output this as 'expanded_panorama'."
    },
    {
      "step_id": 2,
      "name": "Seamless Loop Adjustment",
      "instructions": "Take the 'expanded_panorama' image. Adjust the leftmost and rightmost sections of this image to ensure they seamlessly connect, creating a continuous horizontal loop without visible seams. Focus changes primarily on the edges to achieve the loop effect, preserving the central content as much as possible. Output this as 'final_seamless_loop'."
    }
  ],
  "Deliverables": {
    "final_seamless_loop_image": "final_seamless_loop"
  }
}

That's cool.

Monday, 27 October 2025

Structured JSON prompts in GenAI.

Hi all.

When working with GenAI, freeform text prompts are fine for casual use, but structured workflows require more discipline. Using JSON prompts allows you to define tasks clearly, enforce rules, and produce outputs that can feed directly into other models.

In this example, we generate a cozy winter cabin scene across three models: Gemini (image), Veo (video), and Suno (music).

1) Image Generation - Gemini

{ "task": "image_generation", "input": "Winter cabin in a snowy forest during blue hour, warm light
glowing from windows, soft snow falling",
"requirements": { "goal": "Create a detailed scene description suitable for video
and music generation", "rules": { "no_people_or_animals": true, "no_extra_locations": true }, "quality": { "description_detail": "high, vivid, and atmospheric", "mood": "peaceful, serene, cozy", "style": "concise and clear, visually evocative", "view_angle": "wide, showing the cabin and surrounding forest", "lighting": "soft blue hour with warm window glow" } }, "output_format": { "type": "text", "example": "A cozy wooden cabin sits quietly in a snowy forest. The soft
blue light of dusk reflects off the snow, and warm light glows from the windows.
Snowflakes gently fall, creating a peaceful and serene atmosphere. The scene is
viewed from a wide angle, showing both the cabin and the surrounding forest."
}, "notes": "This description will serve as the base for Veo video generation and
Suno music generation."
}

Tuesday, 30 September 2025

WMI Code Creator manuals

Hi all,

WMI Code Creator has an excellent manual covering four cases. I offer them to you below.

Browsing the Namespaces on the Local Computer

Each class in WMI is in a namespace, with each namespace holding similar classes.  For example, the root\CIMV2 namespace contains classes that hold information about the Windows platform and your computer components. Each WMI class can have properties, methods, and qualifiers. A qualifier is a modifier that contains information that describes a class, instance, property, method, or parameter. Qualifiers are defined by the Common Information Model (CIM), by the CIM Object Manager, and by developers who create new classes.

The following steps describe how to use the WMI Code Creator to browse the namespaces on a local computer:

1. Select a namespace.  Each namespace holds classes that expose different data. The most commonly used namespace is root\CIMV2.

2. Select a class from the namespace.  The class list is populated with all the classes from the selected namespace. If the selected class has a Description qualifier, then the value of that qualifier is displayed in the Class Description text box.

3. Click the List all the properties in the class button to populate the property list with all the properties from the selected class.  When you select a property in the property list, the property description is displayed. The property description comes from the value of the Description qualifier for the selected property.

4. Click the List all the methods in the class button to populate the method list with all the methods from the selected class. When you select a method in the method list, the method description is displayed.  The method description comes from the value of the Description qualifier for the selected method.

5. Click the List all the qualifiers for the class button to populate the qualifier list will all the qualifiers from the selected class.

Wednesday, 24 September 2025

About WMI Code Creator.

Hi all.

WMI Code Creator is a magic wand for system administrators. But what's interesting is that the name is 100% accurate. It's also true that half of system administrators have never heard of this wonderful tool, and the other half who have heard of it don't use it yet.

WMI Code Creator is a tiny (300KB) Microsoft tool available here. To demonstrate its features, the code snippet below is for querying a machine’s model and gives us enough info to start using the tool.

strComputer = "."

Set WshShell = WScript.CreateObject("WScript.Shell")

strQuery="SELECT * from Win32_ComputerSystem"

Set col=GetObject("WinMgmts://" & strComputer & "/root/cimv2").ExecQuery(strQuery)

For Each WMIProperty in col

PCModel = WMIProperty.Model

First, I need to select the CIMV2 namespace and then find the win32_computersystem class in the class drop-down box. Without reference to a huge book or the internet, you would struggle to discover the properties in the class without perhaps writing a script. Code creator makes this trivial, with the click of a single button which lists all properties. The model is just one property of many, as you can see in figure below:


Saturday, 2 August 2025

Hosting ComfyUI via WebSocket

Hi all.

Today, I will share with you a post by a guru Philipp Doll on using websocket with СomfyUI. I have previously experimented with the API  with ComfyUI.

I can't say how much this might be needed for the regular ComfyUI user, but it's cool that this option is there.

Let us proceed.

Motivation

This article focuses on leveraging ComfyUI beyond its basic workflow capabilities. You have created a fantastic Workflow and want to share it with the world or build an application around it. By hosting your projects and utilizing this WebSocket API concept, you can dynamically process user input to create an incredible style transfer or stunning photo effect.

Introduction

This post describes the basic structure of a WebSocket API that communicates with ComfyUI. Generating images through ComfyUI typically takes several seconds, and depending on the complexity of the workflow,

this time can increase. We utilize a WebSocket connection to track progress and allow us to give real-time feedback to the user. Using these endpoints without a WebSocket connection is possible, but this will cost you the benefits of real-time updates.

Code for a basic WebSocket API structure can be found here: Basic WebSocket API.


Utilized ComfyUI endpoints

ComfyUI already has predefined endpoints ComfyUI endpoints, which we can target. Furthermore, ComfyUI also offers a WebSocket interface. For the API described later in this blog post, we do not need to modify this file, as it already provides everything we need.

@routes.get('/ws')  ⇒ Returns the WebSocket object, sends status and executing messages

@routes.post("/prompt")  ⇒ Queues prompt to workflow, returns prompt_id or error

@routes.get("/history/{prompt_id}")  ⇒ Returns the queue or output for the given prompt_id

@routes.get("/view")  ⇒ Returns an Image given a filename, subfolder, and type ("input", "output", "temp")

@routes.post("/upload/image") ⇒ Uploads an image to ComfyUI, given image_data and type ("input", "output", "temp")


Sunday, 16 June 2024

Run Stable Diffusion on AWS.

Hi all.

This is retype post from  Andrew "How to run Stable Diffusion on AWS".

Running Stable Diffusion in the cloud (AWS) has many advantages. You rent the hardware on-demand and only pay for the time you use. You don’t need to worry about maintaining the hardware.

Author set up a personal cloud server to run AUTOMATIC1111, ComfyUI, and SD Forge for saving storage space, the three Stable Diffusion software share models.


When do you want to use the Cloud?

The benefits of using a personal cloud server to run Stable Diffusion are:

  • You don’t need to buy and maintain hardware. The cloud provider is responsible for the capital cost and maintenance.
  • You can easily rent a more powerful GPU if you need it.
  • You can access the machine anywhere, even when you are traveling.

Setting up a cloud server requires some technical expertise and can be time-consuming. You can use Google Colab notebooks as alternative method.


Cloud server setup

This article will guide you in setting up a Stable Diffusion cloud server for personal use. You will use Amazon Web Service (AWS) to set up the cloud system.

AWS is Amazon’s cloud computing service. You can rent computer resources such as CPU, GPU, RAM, storage, and public IP addresses on demand. You only pay for the hours you use.

We will use:

  • EC2: Compute instance to host the Stable Diffusion server. You can select the CPU, GPU, and RAM specs. The instance will have options to run A1111, ComfyUI, or SD Forge.
  • Elastic IP: Fix the IP address of the EC2 instance. Without it, the IP address will change everytime you stop and start the instance.
  • S3 bucket (optionally): For storing the AI models more economically.


Notes:

You should stop the instance after each session. Otherwise, it will keep charging at the rate of a running instance. The storage is persistent, meaning that all the files and settings stay the same between sessions. It is no different from your local PC. See the summary of commands at the end.

Personal prerequisite - to follow this tutorial you should have a basic knowledge of using Linux with a terminal.

PS: of course, you can choose a Amazon Machine Image as Windows11 and simply upload your portable builds of A1111, ComfyUI and SD Forge to running EC2 instance.)

Monday, 24 July 2023

Создаем голосовой помощник c GPT.

Всем привет.

Мы уже пробовали использовать OpenAI для ответов на вопросы и извлечения текста из речи с помощью Whisper. Что, если мы теперь объединим эти и другие компоненты для создания голосового помощника на основе ИИ?  Т.е. в отличие от предыдущего проекта будем ответы GPT не только читать, но и слушать.

Теперь наша цель – использовать базу знаний GPT, чтобы получить ответы на вопросы, которые мы можем задать. Создадим некое подобие голосового помощника Alexa. Но наш интеллектуальный голосовой помощник сможет ответить на более сложные вопросы и предоставить больше полезной информации.

Наш помощник будет работать по такому алгоритму:

• пользователь задает свой вопрос с помощью микрофона. Мы будем использовать Python SpeechRecognition (https://github.com/Uberi/speech_recognition);

• Whisper автоматически преобразует вопрос в текст;

• текст передается в конечные точки GPT;

• API OpenAI возвращает ответ;

• ответ сохраняется в файле mp3 и передается в Google Text to Speech (gTTS) для создания голосового ответа. Помощник проигрывает нам ответ в виде mp3.


Для голосового помощника на понадобяться три функции:

1. Запрос пользователя и запись его голоса - функция def record_audio для записи звука.

2. Расшифровка аудио з записью голоса пользователя - функция def transcribe_forever, которая использует OpenAI Whisper для расшифровки аудио.

3. Голосовой ответ на запрос пользователя - для ответа на запрос пользователя мы будем использовать функцию def reply дл ягенерации голосового ответа от GPT.

Saturday, 24 June 2023

Practice prompts with ChatGPT.

Hi all.

Knowing where to start with ChatGPT can be overwhelming, so we’ve made it easier for you! This post has prompts for all different types of English practice. Simply copy the prompt you want to use and paste it directly in ChatGPT. Of course you’re encouraged to use these prompts as inspiration, and change the prompt based on what you’re interested in and what you need to work on. 

You can select what you want to practice with ChatGPT:

  • Fluency 
  • Grammar 
  • Vocabulary 
  • Pronunciation 
  • TOEFL/IELTS 
  • Study Strategy
  • Conversation 
  • Monologues & Dialogues 
  • Writing.

Conversation

When you want to begin ChatGPT, give it instructions such as the following:

• Can you suggest topics for us to discuss?

• Let’s have a conversation about [topic].

• Let’s have a back-and-forth conversation about [topic].

• Let’s conduct a mock job interview where you will be asking my questions as if I were interviewing for a [position / job role]. Please provide feedback on my answers.

• Let’s have small talk together about [topic].

• Let’s have a conversation about [topic] and correct my mistakes. 

• Let’s have a conversation about [topic] and suggest different vocabulary / phrasal verbs I can use.


After the initial prompt, you can also ask for feedback or additional requests while having a conversation:

• Can you suggest words and expressions that I can use in this conversation?

• Can you suggest phrasal verbs that I can use in this conversation?

• Please correct my grammar mistakes in the text above.

• Please rewrite my answer and explain your changes. 

• Why did you make that suggestion?


You can also ask it to generate real-life conversations in specific situations:

• Write a conversation at a bank.

• Write a conversation at a bank about [scenario].

• Write a conversation between a customer support representative and a customer calling about a refund.

• Write a conversation between [person 1] and [person 2] about [subject]. For example: “between a bus driver and a passenger about not paying for a ticket.

• Write a conversation between three strangers about the [topic]. For example: finance, movies, sports, theatre, cars, etc.

• Write a conversation between two friends about [a specific topic]. 

• Can you rewrite this conversation and add a conflict? 

Thursday, 20 April 2023

Английский язык с ChatGPT.

Всем привет.

Пожалуй, новости о языковых моделях и их использовании уже немного надоели, но вчера я нашел у одного парня для себя полезное применение - изучать Английский, в том числе и разговорный. Что могут нам предложить в этом деле специалисты из OpenAI: например совместить работу ChatGPT, Whisper и Telegram.

Мотивация - нужно заговорить на английском не стесняясь, но так чтобы тебя понимали. Не секрет что уровень B1 у каждого второго преимущественно в чтении или письме. Разговорные уроки с учителем стоят довольно дорого, ходить в английские клубы не всегда удобно, да и вообще общаться с людьми оффлайн или онлайн на непонятные темы не хочется. Поэтому тот парень решил, что для начала будет легше заставить себя говорить на компьютер, например c ChatGPT. Где ChatGPT войдет в роль учителя-помощника и будет поправлять тебя каждый раз если ты ошибешся, также он будет готов тебя слушать 24/7 и поддерживать диалог на любую тематику. Почти идеально.

Про постановку задачи и проверку модели SAR вы можете прочитать у автора в посте. Репозиторий его кода расположен здесь.

Реализация - лично я не заморачивался арендой сервера. Я сделал форк его репозитория и пошел с ним на Gitpod, где и собрал нужный docker-контейнер. Разумеется перед сборкой надо прописать в коде значение openai.api_key  для GPT и TOKEN для Telegram. Уверен, что вы знаете где их искать.)


Далее запускаете контейнер "Run interactive" и разговариваете в своем Telegram. 


Все работает. Для задания роли учителя а не просто собеседника необходимо использовать ключ /teach.

Почти идеально ибо ваш учитель отвечает вам только письменно. Понимать на слух речь собеседника это уже другая задача. Кстати, преподаватели Английского уже малость волнуются за свое будущее, и я их понимаю: АІ-технологии могут им оставить только самых ленивых учеников, или самых болтливых.)

Удачи.


Tuesday, 7 March 2023

Copy/Paste feature between VMRC client and Virtual Machine.

Hi all.

I was amazing by discovering that feature  "Copy/Paste" between VMRC client and Windows/Linux Virtual Machine is not available. However to resolve such issue, you can first install or upgrade the VMware tools for the Windows/Linux virtual machine(VM) and perform next steps.. 

From the vCenter Server HTML5 Web Client.

1)Power off the VM.

2)Enable the Copy & Paste for the Windows/Linux virtual machine:

    a) Right-click the virtual machine and click Edit Settings.

    b) Click the VM Options tab, expand Advanced, and click Edit Configuration.



    c) Click on Add Configuration Params three times to give three rows 

    d) Fill in the Name and Value fields as mentioned below:

Name:                                 Value:

isolation.tools.copy.disable          FALSE

isolation.tools.paste.disable         FALSE

isolation.tools.setGUIOptions.enable  TRUE

    e) Click OK to save and exit out of the Configuration Parameters wizard. Note: These options override any settings made in the guest operating system’s VMware Tools control panel. 

    f) Click OK to save and exit out of the Edit Settings wizard.

 

3) Power on the VM

4) Then use Copy/Paste directly on Windows/Linux/any other platform. 

5) For paste operation's target platform is Linux, Older X applications do not use a clipboard. Instead, they let you paste the currently selected text (called the "primary selection") without copying it to a clipboard. Pressing the middle mouse button is usually the way to paste the primary selection.

Monday, 9 January 2023

MS HyperV and Oracle VirtualBox.


Hi all.

I know this problem is -  problem due to the fact of incompatibility between MS HyperV and Oracle VirtualBox on the one host. However, today I can propose for you 3 steps for resolving it with VirtualBox:

1) to get your VMs working, you will need to go into the VM settings, choose the System section, go into the Acceleration tab, and select "Hyper-V" as the Paravirtualization Interface. 

2) you may also have to disable the "Enable I/O APIC" checkbox on the Motherboard tab. 

3) if you found some guest OS crash with it checked, but if it works for you, then leave it as is. Then,  you need to add an obscure setting to the .vbox file associated with your VM image:

VBoxManage setextradata "<VM Name>" "VBoxInternal/NEM/UseRing0Runloop" 0

Good luck!

Wednesday, 24 August 2022

Output data by Poweshell Studio in runtime.

Hi all.

If you newbee coder in Poweshell Studio you need simple method for output debug information in runtime. So I can present some variants for you.


1. You can easy test your form by sending output to Out-String and then Write-Host. For

example, in your form you could end up with a line like this:

<code to get data> | Out-String | Write-Host


2. So the next it's very popular method for output data in WinForms. It's Out-GridView, I wrote about it super commandlet early:

$entries = Get-EventLog -Computer $ComputerName.Text -Log $EventLogName.SelectedItem

$entries | Out-GridView


3. If you don’t want to create additional forms, there are several controls you can use within the form itself to display your results. You can use a Label control for a simple one-line result. Just set the Text property:

$labelDeviceID.Text=$data.deviceID

$labelFreespace.Text=$data.FreeGB

$labelSize.Text=$data.SizeGB

$labelVolume.Text=$data.Volumename

Sure, don't forget to set property $label.Visible = False for finishing, or remove all debug's labels from your Form before Build.


4. You could use a RichTextBox control. This control has some interesting visual properties you can experiment with. If you use this control, set the font to a fixed-width font like Consolas, especially if you want to display PowerShell output. Both of these controls expect strings, so you might need to reformat any PowerShell output by piping it to Out-String:

#clear any existing text box values

$RichTextBoxResults.Clear()

$data=<my command>

$RichTextBoxResults.Text=$data | Out-String


5. And the last option, although the most complicated of the bunch, is a DataGridView control. This is like what you get when you pipe results to Out-Gridview, except the table is in your form. You put data in the control via its DataSource property, which is an array of binding values. Fortunately, PowerShell Studio has a helper function called Update-DataGridView that makes it easier to populate it. Here’s a code snippet of what that might look like:

#clear the grid before

$datagridview1.ClearSelection()

#get data

$data=Get-WmiObject Win32_LogicalDisk -Filter "drivetype=3" -ComputerName $Computername.Text | Select "DeviceID",@{Name="SizeGB";Expression={"{0:N2}" -f ($_.Size/

1GB)}}, @{Name="FreeGB";Expression={"{0:N2}" -f ($_.Freespace/1GB)}},"VolumeName"

#add the data to the control

Update-DataGridView -DataGridView $datagridview1 -Item $data


See you later.

Wednesday, 22 June 2022

Анализ сетевых пакетов c TCPDump.

Всем привет.

Сегодня у нас четвертая часть серии "Анализ сетевых пакетов", переходим к TCPDump. Инструмент Tcpdump представляет собой основное средство сетевого анализа, используемое специалистами в сфере информационной безопасности. 


Tcpdump captures packets of network traffic on a given network interface

It uses command line arguments for selecting specific destinations, sources, protocols, etc

It can also use filter files containing command line arguments. Filters are used to restrict analysis to packets of interest

Output from tcpdump is called  dump 


Example dump

Ran tcpdump on the machine xanadu.ieu.edu.tr. First few lines of the output:

01:46:28.808262 IP xanadu.ieu.edu.tr.ssh > adsl-69-228-230-7.dsl.pltn13.pacbell.net.2481: . 2513546054:2513547434(1380) ack 1268355216 win 12816

01:46:28.808271 IP xanadu.ieu.edu.tr.ssh > adsl-69-228-230-7.dsl.pltn13.pacbell.net.2481: P 1380:2128(748) ack 1 win 12816

01:46:28.808276 IP xanadu.ieu.edu.tr.ssh > adsl-69-228-230-7.dsl.pltn13.pacbell.net.2481: . 2128:3508(1380) ack 1 win 12816

01:46:28.890021 IP adsl-69-228-230-7.dsl.pltn13.pacbell.net.2481 > xanadu.ieu.edu.tr.ssh: P 1:49(48) ack 1380 win 16560

Monday, 13 June 2022

Nmap scanning and discovering.

Всем привет.

Сегодня у нас вторая часть из серии "Анализ сетевых пакетов" и сегодня оперируем Nmap.

Nmap (network mapper) is an open source tool for network traffic analysis and security auditing. 

It uses raw network packets to determine:

  • what hosts are available on networks,
  • what services (application name and versions),
  • what operating systems and OS versions they are running,
  • what type of packet filters/firewalls are in use,

 and many more...


Single Target Scanning:

## Scan a single ip address ###

nmap 192.168.1.1


## Scan a host name ###

nmap www.google.com


## Scan a host name with more info###

nmap –v myhost.ieu.edu.tr


Multiple Target Scanning:

nmap 192.168.1.1 192.168.1.2 192.168.1.3

nmap 192.168.1.1,2,3

Saturday, 21 May 2022

Полчаса после полуночи.

Всем привет.

Давайте еще раз про время по английски. Я подозревал что я где-то ошибаюсь, но где именно ..?)

Итак 00:30 АМ это как пол первого ночи, т.е. как "полчаса после полуночи".

Или днем можно сказать 00:30 PM как "пол первого дня", т.е. как "полчаса после полудня".

Но оказывается 12:30 PM это тоже пол первого дня, и 12:30 АМ тоже можно как "пол первого ночи". Сюрприз! Для вас нет? Ok, то когда же проходит тот самый меридиан по которому мы пишем Ante Meridiem и Post Merediem?

И вот буквально вчера вынул список из одного промышленного шедулера. Нравится вам такое?))

Удачи.





Sunday, 24 October 2021

PowerShell Security book #2.

Hi all.

Today I would like to present second part of my resume by e-book "PowerShell Security".

JEA.

I don't know if I need to describe JEA again. Ok, I will write about it very shortly today. So, by default, there are three Session Configurations on each Windows computer, namely: 

  • microsoft.powershell, 
  • microsoft.powershell.workflow,
  • microsoft.windows.server-managerworkflows.

1) Get-PSSessionConfiguration

Define "HelpDesk" configuration:

Register-PSSessionConfiguration -Name HelpDesk

This opens the dialog you already know from managing file permissions:

Register-PSSessionConfiguration -Name HelpDesk -ShowSecurityDescriptorUI

Defining RunsAs users:

Register-PSSessionConfiguration -Name HelpDesk -RunAsCredential forza.com\MikeLee

Set additional options via configuration file:

New-PSSessionConfigurationFile -Path .\MyConfig.pssc

The following are particularly useful to prevent users from potentially harmful actions:

-languageMode with the values FullLanguage, RestrictedLanguage, ConstrainedLanguage, NoLanguage: The latter allows only the exe-cution of cmdlets and functions, other language resources are not available. 

FullLanguage offers the full range of language capabilities, the other two lie between these two poles.

-VisibleAliases, VisibleCmdlets, VisibleFunctions, VisibleProviders: These allow you to specify which aliases, cmdlets, functions, and providers are available in the session. 

You can use wildcards and specify multiple values as array.

Example:

New-PSSessionConfigurationFile -Path .\MyConfig.pssc -VisibleCmdlets "Get*","Select*"

You adjust the Session Configuration based on this file:

Set-PSSessionConfiguration -Name HelpDesk -Path .\MyConfig.pssc

Enter-PSSession -ComputerName Remote-PC -ConfigurationName HelpDesk

-OR-

Invoke-Command -ComputerName Remote-PC -ConfigurationName Helpdesk {Get-ChildItem}

2) New-PSRoleCapabilityFile -Path MyRCF.psrc

-OR-

JEA Helper Tool create MyRCF.psrc

Once you have created the list of permitted cmdlets and parameters, you can add them to the .psrc file. You save this file in a directory called RoleCapabilities under

$env:ProgramFiles\WindowsPowerShell\Modules

The last step is to link the role capabilities to the desired session configu-ration. To do this, edit the configuration file with the extension .pssc and add the role functions there.

Since you create this file automatically at the beginning, this (commented out) section for RoleDefinitions should already be there:

RoleDefinitions = @{ 'CONTOSO\SqlAdmins' = ` @{ RoleCapabilities = 'SqlAdministration' }; 

'CONTOSO\SqlManaged' = @{ RoleCapabilityFiles = 'C:\RoleCapability\SqlManaged.psrc' }; 

'CONTOSO\ServerMonitors' = ` @{ VisibleCmdlets = 'Get-Process' } }

Wednesday, 20 October 2021

PowerShell Security book #1.

Hi all.

Today I would like to present for your eyes the best e-book of authors Michael Pietroforte and Wolfgang Sommergut "PowerShell Security".

These authors describe in details security features in Powershell:

  • Control execution of scripts using execution policy, code signing and constrained language mode
  • Secure PowerShell remoting with SSH und TLS
  • Delegate administrative tasks with JEA
  • Audit and analyze PowerShell activities, encrypt logs
  • Improve code quality following best practices.

PowerShell is a powerful tool for system administration and as such also a perfect means for hackers. Due to the tight integration into the system, attempts to simply block PowerShell provide a false impression of security. The best protection is provided by PowerShell's own mechanisms. PowerShell offers almost unlimited access to the resources of a Windows computer and also can automate numerous applications such as Exchange. Users aren't limited to the many modules and cmdlets, but can also integrate .NET classes, Windows APIs, and COM objects. These capabilities are particularly dangerous in the hands of attackers. Since many versions of With Windows Server, Microsoft avoids to activate any roles and features on a freshly installed machine in order to minimize the attack surface. On such a locked down system users must explicitly add all required services.



So, now I try to explain for you these features in practically. Let's go.

# Execution scripts.

We can define policies for execution Powershell scripts on the host by:

  • GPO
  • signing our script
  • set constrained language mode.

# Execution policy.

I prefer set RemoteSigned mode. It means that Scripts downloaded from the Internet must be signed by a trusted publisher.

How it set?

  • Set-ExecutionPolicy RemoteSigned
  • Set-ExecutionPolicy RemoteSigned -Scope CurrentUser
  • $env:PSExecutionPolicyPreference

How it check?

Get-ExecutionPolicy -List | ft -AutoSize

We can set Turn on Poweshell script execution by GPO.

How it set?

mmc: Policies => Administrative Templates => Windows Components => Windows PowerShell and is called Turn on Script Execution.

Result: powershell.exe -ExecutionPolicy "Unrestricted" doesn't work!

However you can bypass it as following:

a) If a user decides to circumvent this policy, he simply copies the contents of a script to the ISE and runs it there. 

b) RemoteSigned allows unsigned scripts downloaded from the Internet to be started if you unblock the file using Unblock-File.

c) Another bypass consists of encoding the script in Base64 and transferring it to PowerShell.exe via the EncodedCommand parameter. 

To limit possible damage caused by such activities, it is recommended to use the Constrained Language Mode.

Friday, 11 December 2020

Testing Ansible roles with Molecule.

Hi all.

Today we will speaking about how to automate your verifications of code using Python.

Story author - Jairo da Silva Junior.

Test techniques role in software development, and this is no different when we are talking about infrastructure as Code (iaC). Developers are always testing, and constant feedback is necessary to drive development. if it takes too long to get feedback on a change, your steps might be too large, making errors hard to spot. baby steps and fast feedback are the essence of tdd (test-driven development). but how do you apply this approach to the development of ad hoc playbooks or roles?

When you’re developing an automation, a typical workflow would start with a new virtual machine. i will use Vagrant [1] to illustrate this idea, but you could use libvirt [2], docker [3], Virtualbox [4], or Vmware [5], an instance in a private or public cloud, or a virtual machine provisioned in your data center hypervisor (oVirt [6], Xen [7], or Vmware, for example).

When deciding which virtual machine to use, balance feedback speed and similarity with your real target environment.

The minimal start point with Vagrant would be:

vagrant init centos/7 # or any other box

Then add Ansible provisioning to your Vagrantfile:

config.vm.provision "ansible" do |ansible|   

  ansible.playbook = "playbook.yml" 

end

In the end, your workflow would be:

1. vagrant up 2. edit playbook. 

3. vagrant provision 

4. vagrant ssh to verify Vm state. 

5. repeat steps 2 to 4. 

Occasionally, the Vm should be destroyed and brought up again (vagrant destroy -f; vagrant up) to increase the reliability of your playbook (i.e., to test if your automation is working end-to-end). Although this is a good workflow, you’re still doing all the hard work of connecting to the Vm and verifying that everything is working as expected. When tests are not automated, you’ll face issues similar to those when you do not automate your infrastructure. Luckily, tools like testinfra [8] and Goss [9] can help automate these verifications.

Thursday, 22 October 2020

Zabbix performance tuning #1.

Hi everybody.

Today I would like to present some ideas about Zabbix performance tuning. The main feature of problem with Zabbix can too many processes by graphs:
- zabbix poller processes more than 75% busy
- zabbix unreachable poller processes more than 75% busy

1. The device that collects data through Zabbix agent is in the state of monitoring, but the machine crashes or other reasons cause the zabbix agent to die. The server cannot obtain data, and the unreachable poller will rise.

2. The device that collects data through Zabbix agent is in the monitoring state, but the server takes too long to obtain data from the agent, often exceeding the server or even the timeout time, at this time the unreachable poller will increase.

So, this article is recopied from the "Gong Xiaoyi" blog, please be sure to keep this source http://gongxiaoyi.blog.51cto.com/7325139/1825492

Saturday, 14 March 2020

Using Python for Network Forensics #1.

Hi all.

Today I would like to present for us excerpt from book "Mastering Python Forensics", Copyright © 2015 Packt Publishing, written by authors Dr. Michael Spreitzenbarth and Dr. Johann Uhrmann. It's concerning using Python for network forensics. You are welcome!

In this chapter, we will focus on the parts of the forensic investigation that are specific to the network layer. We will choose one of the most widely used Python packages for the purpose of manipulating and analyzing network trafic (Scapy) as well as a newly released open source framework by the U.S. Army Research Laboratory (Dshell). For both the toolkits, we have selected the examples of
interesting evidence. This chapter will teach you the following:
•  How to search for IOC in network traffic
•  How to extract files for further analysis
•  How to monitor accessed files through Server Message Block (SMB)
•  How to build your own port scanner

So, how we are using Dshell during an investigation.

Dshell is a Python-based network forensic analysis toolkit that is developed by the U.S. Army Research Laboratory and released as open source at the end of 2014. It can help in making the forensic investigations on the network layer a little easier. The toolkit comes with a large number of decoders that can be used out of the box and are very helpful. Some of these decoders are as follows:
•  dns: Extracts and summarizes DNS queries/responses
•  reservedips: Identifies the DNS resolutions that fall in the reserved IP space
•  large-flows: Displays the netflows that have at least transferred 1MB
•  rip-http: Extracts the files from the HTTP traffic
•  protocols: Identifies non-standard protocols
•  synrst: Detects failed attempts to connect (SYN followed by a RST/ACK).

Dshell can be installed in our lab environment by cloning the sources from GitHub at, https://github.com/USArmyResearchLab/Dshell and running install-ubuntu.py.
This script will automatically download the missing packages and build the executables that we will need afterwards. Dshell can be used against the pcap files that have been recorded during the incidents or as a result of an IDS alert. A packet capture (pcap) file is either created by libpcap (on Linux) or WinPcap (on Windows). In the following section, we will explain how an investigator can make use of Dshell by demonstrating the toolkit with real-world scenarios that are gathered from
http://malware-traffic-analysis.net.


Версия на печать

Популярное