Monday, 14 December 2020

Python regex to match start and end of sentence

 


#Check if the string starts with "The" and ends with "chennai":

txt = "The rain in chennai"

x = re.search("^The.*chennai$", txt)

Saturday, 28 November 2020

Why do we need weekend ??

 

  1. To improve on yourself as a person rather than always improving your professional skills.
  2. To re-energize yourself, when you go back after weekend, you are more relaxed and productive. A couple of days are really required to forget the rudeness of your office colleagues and managers.
  3. To spend time with friends and family, and to plan a weekend trip in a nearby place. It is also important to keep strengthening the bonds with the others around you, and these days you will always remember even when you retire.
  4. To spend time alone and learn some new skills. You can meditate and learn about spirituality, or you can enhance your skills in something else, which can help you, if the current technology you are working in, goes outdated. You will come out to be a more confidant and secured person.

Monday, 26 October 2020

Hackathon flow

 


Flow 

Register -> Create Teams -> View Problems/Deadlines/Leaderboard -> Submit Solutions -> Results

Monday, 3 August 2020

Ansible tower / AWX notification Microsoft teams channel



It's not a http header, it's the payload, which you can't alter. 

A WebHook Notification template type won't work for Mattermost/MS Teams/RocketChat or any other Slack compatible communication platform.

Try selecting Mattermost as the notification type and point it to your Teams webhook url; This should do the trick.

Friday, 31 July 2020

Scrum Process (two weeks sprint)



Day 1 : Creation of building blocks.

Day 2:  Converting building blocks into userstories

Day 3: Sprint Planning ( Converting userstories into JIRA tasks)

Day 4 - Day 13: Sprint run (incase of 2 weeks sprint) (Daily stand ups)

Day 14: Sprint Retrospective 

Sunday, 19 July 2020

Configuring zerotier on ubuntu


root@instance-20200602-1459:/# sudo snap install zerotier-one
root@instance-20200602-1459:/# sudo snap connect zerotier-one:network-control
root@instance-20200602-1459:/# sudo zerotier-one.zerotier-cli info
200 info ******** 1.4.6 ONLINE
root@instance-20200602-1459:/# sudo zerotier-one.zerotier-cli join *******
200 join OK






Friday, 3 July 2020

how to check who changed root password ?



In the /var/log/auth.log there should be an entry like:

Mar 31 12:41:41 UBUNTU sudo: daniel : TTY=pts/1 ; PWD=/dev ; USER=root ; COMMAND=/usr/bin/passwd root
Mar 31 12:41:52 UBUNTU passwd[25160]: (pam_unix) password changed for root
Mar 31 12:41:52 UBUNTU passwd[25160]: (pam_unix) Password for root was changed

Sunday, 28 June 2020

ssh : Permission denied (publickey,gssapi-with-mic)




[root@ansible kube-cluster]# vi /etc/ssh/sshd_config


# To disable tunneled clear text passwords, change to no here!

PasswordAuthentication yes




[root@ansible kube-cluster]# service sshd restart

Saturday, 20 June 2020

Windows host through SSH bastion on Ansible



Pre requisite :

install the required Python packages pip install ansible pypsrp requests[socks]

command to route traffic 

ssh -o "ControlMaster=auto" -o "ControlPersist=no" -o "ControlPath=~/.ssh/cp/ssh-%r@%h:%p" -CfNq -D 127.0.0.1:2222 -p 2222 root@<bastion server IP>

[windowstarget]
<IP>
[windowstarget:vars]
ansible_user=<domain>\<username>
ansible_password=<password>
ansible_connection=psrp
ansible_psrp_protocol=http
ansible_psrp_proxy=socks5h://localhost:2222








REF#

Ansible inventory to connect juniper switch


[juniperswitch]
<IP>

[juniperswitch:vars]
ansible_connection=netconf
ansible_network_os=junos
ansible_user=<IP>
ansible_python_interpreter=/usr/bin/python2.7
ansible_password=<Password>

Ansible inventory to connect cisco router



[ciscorouter]
<IP>

[ciscorouter:vars]
ansible_connection=network_cli
ansible_become=yes
ansible_become_method=enable
ansible_network_os=ios
ansible_user=<username>
ansible_password=<password>
ansible_python_interpreter=/usr/bin/python2.7

Ansible inventory to connect vsphere firewall



ansible_user=<username>@vsphere.local
ansible_password=<password>
ansible_connection=winrm
ansible_port=5985
ansible_winrm_transport=ntlm
ansible_winrm_server_cert_validation=ignore
ansible_winrm_scheme=http

Ansible inventory to connect Paloalto firewall



ansible_user=<username>
ansible_password=<password>
ansible_network_os=eos
ansible_connection=network_cli
#ansible_httpapi_use_ssl=False
#ansible_httpapi_validate_certs=False

Ansible inventory to connect Windows host



[windows]
<IP>

[windows_2]

ansible_user=<domain\username>
ansible_password=<password>
ansible_port=<portno>
ansible_connection=winrm
ansible_winrm_server_cert_validation=ignore
#ansible_connection=winrm
#ansible_winrm_transport=kerberos
ansible_winrm_transport=ntlm

Ansible inventory to connect linux host



<IP> ansible_connection=ssh ansible_ssh_pass=<password> ansible_ssh_user=<username>

Configure QPID



Listener 

listener {
    host: 0.0.0.0
    port: 5001
    role: inter-router

Connector

Connector {
    host: public IP
    port: 5001
    role: inter-router

Regex pattern to convert puppet host file to ansible host



puppet cert list --all | egrep "^\+.*" | awk -F"\"" '{ print $2 }' > /etc/ansible/puppet_hosts

Sunday, 24 May 2020

To use Kerberos authentication you need these optional dependencies



# for Debian/Ubuntu/etc:
$ sudo apt-get install gcc python-dev libkrb5-dev
$ pip install pywinrm[kerberos]

# for RHEL/CentOS/etc:
$ sudo yum install gcc python-devel krb5-devel krb5-workstation python-devel
$ pip install pywinrm[kerberos]

Wednesday, 6 May 2020

ANSIBLE FACTS

get all facts from a node (ad hoc)
ansible -i hosts targetName -m setup -a "filter="facter_*"

use fact in a playbook
include fact as {{ ansible_factname }}

add fact to Hosts file
[group]
host1 admin_user=jane
host2 admin_user=jack
host3 

[group:vars]
admin_user=john

get default IPV4 address
ansible_default_ipv4.address

Local facts

place .fact file into /etc/ansible/facts.d on target node
vim /etc/ansible/facts.d/fruits.fact

[fruits]
sweet=banana, apple, grapes
bitter=grapefruit

get Local facts
ansible -i hosts mrx -m setup -a "filter=ansible_local"

ANSIBLE FILES & DIRS

delete all files and hidden files in a directory
vars:
  app_home: /var/opt/application

tasks:
  - name: clear home dir
  - shell: "ls -la {{ app_home }}/"
    register: files_to_delete
  - file: path="{{ app_home }}/{{ item }}" state=absent
    with_items: "{{ files_to_delete.stdout_lines }}"

get files from node
ansible node1 -s -m fetch -a "src=/etc/hosts dest=/tmp"

copy file to node
ansible node1 -m copy -a "src=/etc/hosts  dest=/tmp/hosts"

remove all files matching a wildcard
file: path={{ item }} state=absent
with_fileglob: /tmp/*.rpm

ANSIBLE USER AND GROUP MGMT

change user password for user Joe (user Fred running the cmd as sudo on the target box)

# 1 install passlib 
pip install passlib

#2 update the pw, using a hash
ansible targethost -s -m user -a "name=joe update_password=always password={{ 'MyNewPassword' | password_hash('sha512') }}" -u fred --ask-sudo-pass

copy public ssh key to remote authorized_keys file

- hosts: targetHost
  tasks:
      - name: update nessus SSH keys
        become_user: root
        become_method: sudo
        become: true
        authorized_key:
           user: nessus
           key: "{{ lookup('pipe','cat ../files/ssh_keys/nessus.pub') }}"
           state: present

ANSIBLE PLAYBOOKS

run playbook with sudo
ansible-playbook -v config-users.yaml --sudo --sudo-user=joe --ask-sudo-pass


use different Hosts file
ansible-playbook -v -i /path/to/hosts


run playbook but only a specific task (tag)
ansible-playbook playbooks/restore_bitbucket.yaml -i hosts --tags rsync 

or to skip: (--skip-tags tag1, tag2)

store output of a command as a variable
shell: cat /etc/network | grep eth0
register: address
debug: msg="address is {{ address.stdout }}"


configure multiple items with one task

- name: more complex items to add several users
  user:
    name: "{{ item.name }}"
    uid: "{{ item.uid }}"
    groups: "{{ item.groups }}"
    state: present
  with_items:
     - { name: testuser1, uid: 1002, groups: "wheel, staff" }
     - { name: testuser2, uid: 1003, groups: staff }

get path location of current Playbook (pwd)
{{ playbook_dir }}


Set playbook to be verbose by default
- hosts: blah
  strategy: debug
run playbook with verbose traceback
ansible-playbook -i hosts myPlaybook.yaml -vvv

run playbook on multiple Host groups
- hosts: "search_head, deployer"

Run playbook locally on host

hosts: 127.0.0.1
connection: local


Prompt for password during Playbook run

# Playbook to change user password

- name: pw change
  hosts: target
  become: true
  become_user: root
  vars_prompt:
    - name: username
      prompt: "enter username for which to change the pw"
    - name: password
      prompt: "enter new password"
      private: yes
  
  tasks:
    - name: change pw
      user: "name={{ username }} password={{ password }} update_password=always"
  


run playbook with "dry run" / NOOP / simulate
ansible-playbook foo.yml --check

Run task on different target,
- name: run something on some other server
  debug: msg="running stuff"
  delegate_to: someserver

Delegate task to a host group
- name: restart web servers
  service: name=memcached state=restarted
  delegate_to: "{{ item }}"
  with_items: "{{ groups['webservers'] }}"

Get IP or facter of a remote host
- name: get IP
  debug: msg="{{ hostvars['nycweb01']['ansible_default_ipv4']['address'] }}"

or

debug: msg="{{ hostvars[item]['ansible_ssh_host'] }}"
with_items: "{{ groups['webservers'] }}"

synchronize file (copy file from Ansible host to target)
  - synchronize: 
     src: "{{ playbook_dir }}/files/vscode.repo"
     dest: /etc/yum.repos.d/ 

synchronize from server A to server B with a wildcard
    - name: copy Splunk Apps
      synchronize:
        src: "/opt/splunk/etc/apps/{{ item }}" (server A)
        dest: "/opt/splunk/etc/shcluster/apps/"  (server B)
      with_items:
        - item1
        - item2
      delegate_to: server A

wget a file to a location
  - get_url:
      url: 'https://dl.google.com/go/go1.10.linux-amd64.tar.gz' 
      dest: '/tmp'
      force: no  # dont download if file already exists

untar tar.gz

Ansible Variables inside Inventory Hosts file

cat hosts
[web]
nycweb01.company.local

[web:vars]
role="super duper web server"

now get the "role" variable inside the playbook,
- hosts: web
  gather_facts: true
  tasks:
    - name: print Role var
      debug: msg={{ role }}

// super duper web server

ANSIBLE VARIABLES

include global variables for all Roles

sample playbook
splunk/
   setup_splunk_playbook.yaml
   roles/base
           /tasks/main.yaml
           /tasks/install.yaml
         search_head
           /tasks/configure.yaml
         indexer
           /tasks/configure.yaml
         some_other_role
           /tasks/some_task.yaml
   hosts
   config.yaml
Place your vars into config.yaml

cat splunk/config.yaml

--- 
# global Splunk variables
splunk_version: 7.0.0
in your playbook, include the Roles

cat setup_splunk_playbook.yaml

- hosts: "search_heads"  
  become_user: root
  become: true
  gather_facts: true

  roles:
    - base
    - search_head
in your Role, include the Global Vars inside a Task

cat roles/base/tasks/main.yaml

---
# install Splunk Base

- name: include vars
  include_vars: "{{ playbook_dir }}/config.yaml"

- include: install.yaml
vars are accessible in tasks now,

cat roles/base/tasks/install.yaml

- name: echo version
  debug: splunk version is {{ splunk_version }}

Loop through a Dict variable inside a playbook

cluster:
  members:
    splunk01: 10.123.1.0
    splunk02: 10.123.1.1
    splunk03: 10.123.1.2

in the playbook, 
- debug: msg="{{ cluster.members.values() | map('regex_replace', '(.*)', 'https://\\1:8089') | join(',') }}"

>> https://10.123,1.0:8089, https://10.123.1.1:8089, etc etc


Use Inventory file variables inside a playbook

cat hosts
[apache]
nycweb01

playbook
debug: msg="IP: {{ hostvars[groups['apache'][0]]['ansible_default_ipv4']['address'] }}"
debug: msg="Hostname: {{ hostvars[groups['apache'][0]]['inventory_hostname'] }}"


register a List/Array to be used for later,
- name: parse all hostnames in group WebServer  and get their IPs, place them in a list
  command: echo {{ hostvars[item]['ansible_ssh_host'] }}"
  with_items: "{{ groups['webserver'] }}"
  register: ip_list

- name: show the IPs
  debug: msg={{ ip_list.results | map(attribute='item') | list }}"


export an Environment variable
- name: yum install
  yum: name=somepkg state=present
  environment: 
    SOME_VAR: abc

Ansible JOBS AND PROCESS CONTROL


run Ansible ad hoc with 10 parallel forks
ansible -i hosts testnode1 -a "uname -a" -f 10

show human readable output
add this line to ansible.cfg
stdout_callback=yaml

Ansible PACKAGES AND INSTALLATION

#install multiple packages
yum: name="{{ item }}" state=present
with_items:
  - http 
  - htop
  - myapp

Ansible SERVER DIAGNOSTICS

Test Connection
ansible -i hosts all -m ping -u root

Diagnostics



manage nodes via "/etc/ansible/hosts" file

Debug (debug output for playbook)
- debug: var=result verbosity=2  

Ansible REMOTE CMD (Ad Hoc)


Ping specific node
ansible -i hosts nycweb01.prod.local -m ping

Ping with wildcard
ansible -i hosts "nycweb*" -m ping

Ping all nodes with SSH user 'root'
ansible -i hosts all -m ping -u root

run a command
ansible -i hosts dev -a 'uname -a'

check Yum packages
ansible -i hosts dev -m yum 

check if Docker rpm is installed
ansible -i hosts web01.nyc.local -m shell -a "rpm -qa | grep docker"

Get facts about a box
ansible -i hosts web01.nyc.local -m setup -a 'filter=facter_*'

run command with sudo
ansible -i hosts target-host -m shell -a "cat /etc/sudoers" --sudo 

limit command to a certain group or server: add --limit *.nyc

Copy your Ansible Master's public key to the managed node

ssh-keygen  ## generate public key
ssh-copy-id <name of node>  # copy key, provide password to node

Saturday, 2 May 2020

uninstall any application in windows 10 via cmd


Below example is to uninstall onedrive


  1. Open Command Prompt as Administrator

  2. Type in taskkill /f /im OneDrive.exe to terminate any OneDrive processes and hit Enter.

  3. Type in %SystemRoot%\SysWOW64\OneDriveSetup.exe /uninstall if you’re using 64-bit Windows 10 and hit Enter.

Wednesday, 29 April 2020

k8s pod ??

A pod is the smallest object model that you can create and run. You can add labels to a pod to identify a subset to run operations on. When you are ready to scale your app, you can use the label to tell Kubernetes which Pod you need to scale. 
A pod typically represents a process in your cluster. Pods contain at least one container that runs the job and additionally might have other containers in it called sidecars for monitoring, logging, and so on. Essentially, a pod is a group of containers.

$ kubectl (create|get|apply|delete) -f Resource.yaml

Kubernetes resource model



  • Config maps: holds configuration data for pods to consume
  • Daemon sets: ensures that each node in the cluster runs this pod
  • Deployments: defines a desired state of a deployment object
  • Events: provides life cycle events on pods and other deployment objects
  • Endpoints: allows an inbound connections to reach the cluster services
  • Ingress: a collection of rules that allows inbound connections to reach the cluster services
  • Jobs: creates one or more pods and when they complete successfully, the job is marked as completed
  • Node: a worker machine in Kubernetes
  • Namespaces: multiple virtual clusters backed by the same physical cluster
  • Pods: the smallest deployable units of computing that can be created and managed in Kubernetes
  • Persistent volumes: provides an API for users and administrators to abstract details about how storage is provided from how it is consumed
  • Replica sets: ensures that a specified number of pod replicas are running at any given time
  • Secrets: holds sensitive information, such as passwords, OAuth tokens, and SSH keys
  • Service accounts: provides an identity for processes that run in a pod
  • Services: an abstraction that defines a logical set of pods and a policy by which to access them, sometimes called a microservice
  • Stateful sets: the workload API object that manages stateful applications

Sunday, 26 April 2020

Command to leave docker swarm

$ docker swarm leave --force

docker update the state of your service by using the command

docker service update

Update docker service with an updated number of replicas.

docker service update --replicas=5 --detach=true [servicename]

verify docker swarm node cluster


docker node ls

To add a worker to this docker swarm

docker swarm join \
    --token **** \
    10.0.120.3:2377

Initialize the docker swarm


docker swarm init --advertise-addr eth0

Check layers of docker image


docker image history [imagename]

Inspect changes to files or directories on a container’s filesystem

docker diff container-id

the docker push command to push your image to the Docker Hub registry:

docker push [dockerhub username]/[image name]

Tag the image with your username.

The Docker Hub naming convention is to tag your image with [dockerhub username]/[image name]. To do this, tag your previously created image python-hello-world to fit that format.

$ docker tag python-hello-world [dockerhub username]/python-hello-world

Log in to the Docker registry account by entering docker login on your terminal


$ docker login
Login with your Docker ID to push and pull images from Docker Hub. If you don't have a Docker ID, head over to https://hub.docker.com to create one.
Username: 

Saturday, 18 April 2020

python class __ or private class component



When any class component has a name starting with two underscores (__), it becomes private - this means that it can be accessed only from within the class.

python find length of stack

class Stack:
    def __init__(self):
        self.stackList = [1,2,3]

stackObject = Stack()
print(len(stackObject.stackList))

Python Stack as class



class Stack:    # defining the Stack class
    def __init__(self):    # defining the constructor function
        print("Hi!")

stackObject = Stack()    # instantiating the object

Python Stack push() pop()



stack = []

def push(val):
    stack.append(val)


def pop():
    val = stack[-1]
    del stack[-1]
    return val

push(3)
push(2)
push(1)

print(pop())
print(pop())
print(pop())

Thursday, 16 April 2020

Wednesday, 15 April 2020

Python Multiprocessing : Run Code in Parallel Using the Multiprocessing Module

import concurrent.futures
import time
start = time.perf_counter()
def do_something(seconds):
print(f'Sleeping {seconds} second(s)...')
time.sleep(seconds)
return f'Done Sleeping...{seconds}'
with concurrent.futures.ProcessPoolExecutor() as executor:
secs = [5, 4, 3, 2, 1]
results = executor.map(do_something, secs)
# for result in results:
# print(result)
finish = time.perf_counter()
print(f'Finished in {round(finish-start, 2)} second(s)')

Python Threading : Run Code Concurrently Using the Threading Module

import concurrent.futures import time start = time.perf_counter() def do_something(seconds): print(f'Sleeping {seconds} second(s)...') time.sleep(seconds) return f'Done Sleeping...{seconds}' with concurrent.futures.ThreadPoolExecutor() as executor: secs = [5, 4, 3, 2, 1] results = executor.map(do_something, secs) # for result in results: # print(result) # threads = [] # for _ in range(10): # t = threading.Thread(target=do_something, args=[1.5]) # t.start() # threads.append(t) # for thread in threads: # thread.join() finish = time.perf_counter() print(f'Finished in {round(finish-start, 2)} second(s)')

Thursday, 9 April 2020

python Math Function

import math

def sin(x):
    if 2 * x == pi:
        return 0.99999999
    else:
        return None

pi = 3.14

print(sin(pi/2))
print(math.sin(math.pi/2))

Thursday, 26 March 2020

Python Pandas to read excel .csv file and get all values under specific column and skip null value





import os
from selenium import webdriver
import time
import pandas as pd
from pandas import ExcelWriter
from pandas import ExcelFile

df = pd.read_csv(r"xxx.csv")
queue = df["Messages"].dropna().tolist()
print (queue)

Tuesday, 10 March 2020

Python Pandas to read excel .csv file and get all values under specific column




import os
from selenium import webdriver
import time
import pandas as pd
from pandas import ExcelWriter
from pandas import ExcelFile

df = pd.read_csv(r"xxx.csv")
queue = df["Messages"].tolist()
print (queue)

powershell script to trigger message in slack using web hock



    $uriSlack = "URL"
        $body = ConvertTo-Json @{
        pretext = "test"
        text = "test"
        color = "#142954"
}
try {
    Invoke-RestMethod -uri $uriSlack -Method Post -body $body -ContentType 'application/json' | Out-Null
    } catch {
    Write-Error (Get-Date) ": Update to Slack went wrong..."
    }

python script to List Files from a directory created or modified in last 30 min





$path = "Z:\"+(Get-Date).tostring("MM-dd-yyyy")
#$path
$FileList = Get-ChildItem -Path $path
$FileLists = $FileList| Where-Object {$_.LastWriteTime -gt [datetime]::Now.AddMinutes(-30)}
#$FileLists

$currenttime = (Get-Date).ToString('HH:mm')
#$currenttime

$currenttime1 = (Get-Date).AddMinutes(1).ToString('HH:mm')
#$currenttimeplus1

$currenttime2 = (Get-Date).AddMinutes(2).ToString('HH:mm')
#$currenttimeplus2

$currenttime3 = (Get-Date).AddMinutes(3).ToString('HH:mm')
#$currenttimeplus3

$currenttime4 = (Get-Date).AddMinutes(4).ToString('HH:mm')
#$currenttimeplus4

$currenttime5 = (Get-Date).AddMinutes(5).ToString('HH:mm')
#$currenttimeplus5

$currenttime6 = (Get-Date).AddMinutes(6).ToString('HH:mm')
#$currenttimeplus6

$currenttime7= (Get-Date).AddMinutes(7).ToString('HH:mm')
#$currenttimeplus7
$currenttime8 = (Get-Date).AddMinutes(8).ToString('HH:mm')
#$currenttimeplus8
$currenttime9 = (Get-Date).AddMinutes(9).ToString('HH:mm')
#$currenttimeplus9
$currenttime10 = (Get-Date).AddMinutes(10).ToString('HH:mm')
#$currenttimeplus10

#Write-Host "in for loop"
#$filecreatedtime = $tomail.CreationTime.ToString('HH:mm')
#$filecreatedtime

$counter = 0   
foreach ($tomail in $FileLists)
{
<#
Write-Host "in for loop"
Write-Host ($tomail)
Write-Host ("----------------------------------------------------------")
Write-Host ($tomail.CreationTime.ToString('HH:mm'))
Write-Host ($currenttime)
Write-Host ("----------------------------------------------------------")
#>
$counter = 0
if ($tomail.Name -match '')
{
#Write-Host $tomail.Name
if ($([DateTime]$tomail.CreationTime.ToString('HH:mm')) -match $([DateTime]$currenttime) -or $([DateTime]$currenttime1) -or $([DateTime]$currenttime2) -or $([DateTime]$currenttime3) -or $([DateTime]$currenttime4) -or $([DateTime]$currenttime5) -or $([DateTime]$currenttime6) -or $([DateTime]$currenttime7) -or $([DateTime]$currenttime8) -or $([DateTime]$currenttime9) -or $([DateTime]$currenttime10))

    {
        #Write-Host "File  found"

        $counter = $counter + 1

        $tomail.Name + "  Found  " + $tomail.CreationTime >> C:\Users\raghuvel.sekar\Desktop\LOG.txt

}
   
else
{
  #Write-Host "File not found"

  "  FileNotFound  " + $currenttime >> C:\Users\raghuvel.sekar\Desktop\LOG.txt

}
        #$counter
        Remove-Variable counter

python script to send mail using outlook 2016 with multiple attachment




 $Outlook = New-Object -ComObject Outlook.Application
 $createmail = $Outlook.CreateItem(0)
 $createmail.To =  "test@test.com"
 $createmail.Subject = "test"
 $createmail.Body = "test"
 $file = "C:\Users\raghuvel.sekar\Desktopscreenshot3.jpg"
 $file1 = "C:\Users\raghuvel.sekar\Desktop\creenshot4.jpg"
 $createmail.Attachments.Add($file)
 $createmail.Attachments.Add($file1)
 $createmail.Send()

Python to get only digits from a file and append into a list



            f = open('file2.txt', 'r')
            for line in f:
                    words = line.split()
                    for i in words:
                            if(i.isdigit()):
                                mylist.append(i)
            print (mylist)

take a screenshot with python , convert image into text and save it as a file




try:
    from PIL import Image
except ImportError:
    import Image
import pytesseract
import sys, os
import subprocess
import pyautogui


pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe'

img1 = pyautogui.screenshot(region=(372,198,1118,682))
img1.save("screenshot1.jpg")


saved_stdout = sys.stdout
sys.stdout = open('file.txt', 'w')
print (pytesseract.image_to_string(Image.open('screenshot1.jpg')))
sys.stdout.close()
sys.stdout = saved_stdout

Monday, 3 February 2020

Wednesday, 22 January 2020

ERROR : new-object : Retrieving the COM class factory for component with CLSID {0006F03A-0000-0000-C000-000000000046} failed due to the following error: 80080005 Server execution failed (Exception from HRESULT: 0x80080005 (CO_E_SERVER_EXEC_FAILURE)).



Close admin command prompt console and open with user mode 

Python ERROR : ValueError: I/O operation on closed file.



For a quick fix, save the standard stdout in a different variable, then redirect to it after that close.

# Simple image to string

saved_stdout = sys.stdout
sys.stdout = open('file.txt', 'w')
print (pytesseract.image_to_string(Image.open('Ke.png')))
sys.stdout.close()

sys.stdout = saved_stdout

Monday, 6 January 2020

python script to copy a executable file from source machine to target and execute the same file on target machine



import paramiko
import os, time, subprocess
port = "22"
username = ""
password = ""
f = open("hosts.txt", "r")
for ip in f:
       print(ip)
       #print(ip.strip())
       cmd = "sshpass -p '' scp -r /home/raghuvel.sekar/deployAgentbkp.py root@{}:/home/raghuvel.sekar".format(ip.strip())
       #print (cmd)
       jobout= subprocess.check_output(cmd, shell=True)
       time.sleep(10)
       #print (jobout)
       ssh=paramiko.SSHClient()
       ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
       ssh.connect(ip,port,username,password)
       stdin,stdout,stderr=ssh.exec_command('(cd /home/raghuvel.sekar; python test.py)')
       time.sleep(10)
       outlines=stdout.readlines()
       resp =''.join(outlines)
       print("done")

Thursday, 2 January 2020

Passing windows path as EXTRA VARS in ansible





ansible-playbook test2.yml -e user=administrator -e 'item_path=C:\\Users\\Administrator\\Desktop\\test\\sample.txt' -e type=allow -e rights=FullControl -vvvv

Git

1 git add ↳ It lets you add changes from the working directory into the staging area 2 git commit ↳ It lets you save a snapshot of currently...