Linux: How to scan remote host for open ports ?

Linux : How to find a remote port is opened or not ?

Helllo Team,

If you are trying to findout whether a remote server port is opened or closed, then there are so many ways. Here In this article I am posting on same using telnet and nc commands.

Using telnet

Telnet usually holds prompt, so to avoid that, we are using echo in front of the command.

> $ echo | telnet xxxxxx 22
Trying xxxxxx...
Connected to xxxxx.
Escape character is '^]'.
Connection closed by foreign host.

Using nc

with nc command, its direct.

> $ nc -z -v -u xxxxx 22
Connection to xxxx port 22 [udp/ssh] succeeded!

# -z: Just perform scans without sending any data to the respective service running on the given port.
# -v : Verbose
# -u: UDP packets, without this it will be default tcp.

Hope it helps. Thanks

ServiceNow: How to read the content of a text file from an incident record attachment

How to read the content of a text file from an incident record attachment:

 GlideSysAttachment API is used to handle attachments.

With this API,

  • we can copy attachment from one record to another
  • read the content of a attached file as text, base64 or content stream
  • write the content
  • read all attachments of a record and also we can delete any of the attachment of a record

var attachment = new GlideSysAttachment();
var incidentSysID = '136e85931bc8fc1037fc4263cc4bcb46';
var agr = attachment.getAttachments('incident', incidentSysID);
gs.info(agr.getRowCount());
while (agr.next()) {
var attachmentContent = attachment.getContent(agr);
gs.info('Attachment content: ' + attachmentContent);



Output:
x_67546_crusher: Attachment content: Vamshi Vemula 
Staff software Engineer

 

OS Internals: Interprocess Communication ( IPC)

ipc

Interprocess Communication ( IPC )

  • Interprocess communication allows a process to communicate with another process.

  • Communications can be one of two types

    • Between related process ( parent and child )
    • Between unrelated processes ( one or more different processes)
  • IPC can use

    • Pipes
    • First In First Out ( FIFO) - Queue
    • Message Queues
    • Shared Memory
    • Semaphores
    • Signals

Pipes

  • Pipes are half-duplex, they can only read or write a process but only in one direction,

  •  

First In, First Out (Named Pipes)

  • FIFO are also called as named pipes, and are half duplex as pipes.

  • when you create a pipe, to identify it, execute ls -l command to the pipe, you can see if its a pipe or not

In the above output prw-r--r-- - p denotes that its a pipe.

Shared Memory

  • shared memory is full duplex, either process can read and/or write.
  • most efficient type of IPC, it does not require any kernel intervention once the shared memory has been allocated/deallocated.
  • Required a program
  • Any number of processes can read and write to the same shared memory segment.
  • You can query shared memory with the ipcs command
  • Processes must manage shared memory
  • Process must protect shared memory being wirtten or race conditions will occur( if two process are trying to access same data at same time)

Message Queues

  • created by syscall
  • managed by kernel
  • kernel will delete the message from queue once it is read
  • each read and write creates a syscall to the kernel
  • the message queue helps eliminate the occurrences of race conditions but comes at the expense of performance due to the syscall interrupt(trap)
  • data will remain in the queue until it is read and once read its gone.

 

Semaphores

  • Semaphores are used to protect critical/common regions of memory shared between multiple processes.

  • So other process cant use this shared memory till the process that owned the memory releases it.

  • Semaphores are the atomic structures of operating systems

  • Two Types of semaphores:

    • Binary: Only two states 0 and 1, locked/unlocked, or available, unavailable etc
    • Counting Semaphores : Allow arbitrary resource counters
  • When a process 'allocates' a semaphore, it blocks the other processes from access until the first process issues a 'release' indicating it has completed its operation.

  • The kernel then makes the semaphore available again for allocation.

Signals

  • A signal is a notification of an event occurrence.

  • A signal is also know as a trap, or software interrupt.

  • if you perform 'kill -l' you can see list of killl siganls implemented in your kernel

    • for example in a linux machine

     

    • And in Mac,
  • Signals can be generated by a user, process or kernel
  • if its a process, it is supposed to be written to handle them
  • Certain signals numeric 9-15 cannot be handled by the process they will immediately cause termination of the process and cannot be blocked, these are called 'process crash-outs' ExL CTRL+C, which cant be blocked by the process and terminates the process.

 

POSIX standards now govern the use and definition of IPC constructs and added support to modern features like threads etc.

 

Python Notes - Strings

Python Notes

String Methods

  • string.capitalize() 
  • Capitalized first letter of string.
  •  string.strip() 
  • Strips whitespaces both left and right side.
  •  string.lstrip() 
  • Strips whitespaces left side
  • string.rstrip() 
  • Strips whitespaces right side
  •  string.lower() 
  • turns string into lower case
  •  string.upper() 
  • turns string into upper case
  •  string.split() 
  • Split string into array

String Formatting


Formatting using %{s,i}

    	
          In [24]: import time

          In [25]: time.strftime("%H:%M:%S")
          Out[25]: '21:19:12'

          In [26]: # Method 1

          In [27]: print("Hello %s, current time is %s" % ("Raja", time.strftime("%H:%M:%S")))
          Hello Raja, current time is 21:20:22

          In [28]: # Method 2

          In [30]: print("Hello %(name)s, current time is %(time_now)s" % { "name" : "Raja", "time
              ...: _now" : time.strftime("%H:%M:%S") })
          Hello Raja, current time is 21:22:19

          In [31]:
		
	

Formatting Using .format()


      In [31]:  ## Using .format()

      In [32]: "Hello {} , current time {}".format("Raja", time.strftime("%H:%M:%S"))
      Out[32]: 'Hello Raja , current time 21:27:23'

      In [33]: "Hello {0} , current time {1}".format("Raja", time.strftime("%H:%M:%S"))
      Out[33]: 'Hello Raja , current time 21:27:38'


      In [36]: "Hello {u_name} , current time {time_now}".format(u_name = "Raja", time_now = t
          ...: ime.strftime("%H:%M:%S"))
      Out[36]: 'Hello Raja , current time 21:29:01'


      In [38]: "Hello {u_name} , current time {time_now}".format(**{"u_name" : "Raja", "time_n
          ...: ow" : time.strftime("%H:%M:%S")})
      Out[38]: 'Hello Raja , current time 21:31:32'

      In [39]: ## Alignment

      In [41]:
          ...: "{:>200}".format("Right arrow, right aligned, so 20 spaces, then aligned to rig
          ...: ht")
      Out[41]: '                                                                                                                                         Right arrow, right aligned, so 20 spaces, then aligned to right'

      In [42]:
          ...: "{:>200}".format("Right arrow, right aligned, so 200 spaces, then aligned to ri
          ...: ght")
      Out[42]: '                                                                                                                                        Right arrow, right aligned, so 200 spaces, then aligned to right'


      In [45]:
          ...: "{:^20}".format("aligned center")
      Out[45]: '   aligned center   '
      

Formatting Using F-Strings



        In [46]: ### F-Strings


        In [48]: def current_time() :
            ...:   return time.strftime("%H:%M:%S")
            ...:

        In [49]: current_time()
        Out[49]: '21:39:08'

        In [51]: name = "Raja"

        In [52]: f'Hello {name}, currne time is {current_time()}'
        Out[52]: 'Hello Raja, currne time is 21:40:03'

        In [53]: f' f-strings can do eval expressions as well {2+3}'
        Out[53]: ' f-strings can do eval expressions as well 5'

        In [54]: f'Hello {name.lower()}'
        Out[54]: 'Hello raja'

        In [55]: username = "Raja"

        In [56]: f'You {username=}'
        Out[56]: "You username='Raja'"

        In [57]:
	
    

String Slicing

  
  	In [61]: "this is a string"[5:10]
	Out[61]: 'is a '
  
  

String cancatenation

  
  In [62]: name = "Raja"

  In [63]: lname = "Genupula"

  In [64]: name + lname
  Out[64]: 'RajaGenupula'

  In [65]: name +" " + lname
  Out[65]: 'Raja Genupula'

  In [67]: " ".join([name, lname])
  Out[67]: 'Raja Genupula'

  In [68]: ", ".join([name, lname])
  Out[68]: 'Raja, Genupula'

  In [69]:
  
  
I hope by looking at the code and output, you can understand whats happening, if more explanation needed, please add in comments.
Thank you

JavaScript: Understanding Prototype and Class methods

So, in JavaScript, first of all, its an object oriented programming but without classes (till ES5), now with ES6 we have classes officially in JavaScript

But still the old behaviour of the language is forwarded with newer version

In Javascript creating an object is possible via its functions( new [Func]()), function is a first class (can be passed as an argument), function is a high order function(can be received as an argument), function it self acts a constructor( new func() )

take a look at below code

  
  function User(name, passwd) {
    this.name = name;
    this.passwd = passwd;
    this.methodname = "User"
  }

  u1 = new User("User1", "Password")
  u2 = new User("User2", "Password")

  console.log(u1)
  console.log(u2)

  User.prototype.method1 = function () {
    console.log("This is method1");
  }
  u1.method1()

  User.method2 = function() {
    console.log("this is method2");
  }
  User.method2()

  

explanation is as follows

  • We have defined a function called `User`
  • Created two objects from that function( Yes, in JS you can do that, function will now work a constrctor
  • Now if you look at console.log output u1 and u2 objects will contain the data, which are passed as argument to function
  • till now all good, then here comes interesting part, `prototype`, using prototype keyword, you are defining a new function called `method1`
  • this method1 function created after creating object u1, u2, but still because its a prototype method where JS will update its reference automatically to all existing objects, u1 and u2 objects can access that method
  • So, how's that happening ?, if you look u1 object structure, in console.log, you will a reference to User.prototype,so when ever a new method added to User.prototype, automatically its available for u1 object via path
  • But then we have defined a method called method2(), and this is defined at class level, so only the User function/constuctor can access that but not the objects like u1, u2
  • the reason isnt like its defined after you have created objects, the reason is its just not under the scope for objects, its under the scope of construtor only.
  • You can use this trick in Javascript, that if you have a method and you dont want that method to be available to your object, then create the method like method2

There is so much to say about prototype and class methods, but I believe this simple read might be helpful

Hope it helps

Thank you.

GoLang: How To work with JSON Data and Nested structs

GoLang: How To work with JSON Data and Nested structs

Hello Everyone,

I spent sometime today to craft this code, so this article slowly walk you through how to build a nested struct, how to load data into it, then converting it into JSON, writing to a file, reading from a file and append new data etc.

I was learning GoLang and found needed something like this. Hope it helps.

package main

import (
	"encoding/json"
	"fmt"
	"os"
)

type Schema struct {
	Users map[string]User
	Posts map[string]Post
}

type User struct {
	Username string `json:"username"`
	Email    string `json:"email"`
}
type Post struct {
	Heading     string `json:"post_heading"`
	Description string `json:"description"`
}

func main() {
	u1 := User{
		Username: "rajag",
		Email:    "rajag@example.com",
	}

	p1 := Post{
		Heading:     "Post 1 heading",
		Description: "Post 1 description",
	}

	fmt.Println(u1)
	fmt.Println(p1)

	schema := Schema{
		Users: make(map[string]User),
		Posts: make(map[string]Post),
	}

	schema.Users[u1.Username] = u1
	schema.Posts[p1.Heading] = p1

	fmt.Println(schema)

	// Now convert the data into JSON and print

	data, err := json.Marshal(schema)
	if err != nil {
		fmt.Println(err)
	}
	//fmt.Printf("%s", string(data))

	// Append data to exist JSON

	u2 := User{
		Username: "user2",
		Email:    "user2@example.com",
	}

	p2 := Post{
		Heading:     "Post 2 heading",
		Description: "Post 2 description",
	}

	schema.Users[u2.Username] = u2
	schema.Posts[p2.Heading] = p2

	data, err = json.Marshal(schema)
	if err != nil {
		fmt.Println(err)
	}
	fmt.Printf("%s\n", data)

	// Assume like you have to do unmarshal to append
	// create empty schema to store the data
	schema2 := Schema{
		Users: make(map[string]User),
		Posts: make(map[string]Post),
	}
	// then unmarshal by saying to store there, go principle share the memory
	err = json.Unmarshal(data, &schema2)
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println("Read from schema 2 >>>>>> ", schema2)

	u3 := User{
		Username: "user3",
		Email:    "user3@example.com",
	}

	p3 := Post{
		Heading:     "Post 3 heading",
		Description: "Post 3 description",
	}

	schema2.Users[u3.Username] = u3
	schema2.Posts[p3.Heading] = p3

	data, err = json.Marshal(schema2)
	if err != nil {
		fmt.Println(err)
	}
	fmt.Printf("data from schema 2 >>>>>>> %s\n ", data)

	// Write JSON to file
	fileName := "./my.json"

	err = os.WriteFile(fileName, data, 0755)
	if err != nil {
		fmt.Println(err)
	}

	//Read JSON from file
	schema3 := Schema{
		Users: make(map[string]User),
		Posts: make(map[string]Post),
	}

	dataFromFile, err := os.ReadFile(fileName)
	if err != nil {
		fmt.Println(err)
	}

	err = json.Unmarshal(dataFromFile, &schema3)
	if err != nil {
		fmt.Println(err)
	}

	fmt.Println("schema3 >>>>> ", schema3)

	// append data to structure
	u4 := User{
		Username: "user4",
		Email:    "user4@example.com",
	}

	p4 := Post{
		Heading:     "Post 4 heading",
		Description: "Post 4 description",
	}

	schema3.Users[u4.Username] = u4
	schema3.Posts[p4.Heading] = p4

	data, err = json.Marshal(schema3)
	if err != nil {
		fmt.Println(err)
	}

	// new data appended

	fmt.Printf("Schema4 >>>>> data %s\n", data)

	// now save changes to file
	os.WriteFile(fileName, data, 0755)
}