Showing posts with label Linux. Show all posts
Showing posts with label Linux. Show all posts

Saturday, December 2, 2023

Friday, November 10, 2023

Vim search for the escaped string of a line


command! -nargs=1 SH let @/ = '\V'.escape(<q-args>, '\')|set hlsearch

nnoremap <C-y> _vg_y<Esc>:SH <C-r>"<CR>


_    go to first non-space character in line

g_   go to last non-space character in line

v    start visual selection

y     copy selection

<C-r>" paste copied selection 

Saturday, August 26, 2023

Fuzzy Finder FZF with Syntax Highlight Preview

FZF is nice cli program that allow quick file navigation that find files as you type.

BAT is nice replacement for cat with highlight features

sudo apt install fzf

sudo apt install bat

Using fzf together with batcat to source code files and preview it with syntax highlight

fzf --preview 'batcat --style=numbers --color=always --line-range :500 {}'


.bashrc

source /usr/share/doc/fzf/examples/key-bindings.bash


if type rg &> /dev/null; then

  export FZF_DEFAULT_COMMAND='rg --files'

  export FZF_DEFAULT_OPTS='-m --height 50% --border'

fi


alias findz="fzf --preview 'batcat --style=numbers --color=always --line-range :500 {}'"


_fzf_comprun() {

  local command=$1

  shift


  case "$command" in

    cd)           fzf --preview 'tree -C {} | head -200'   "$@" ;;

    export|unset) fzf --preview "eval 'echo \$'{}"         "$@" ;;

    ssh)          fzf --preview 'dig {}'                   "$@" ;;

    *)            fzf --preview 'batcat -n --color=always {}' "$@" ;;

  esac

}

export FZF_CTRL_R_OPTS="

  --preview 'echo {}' --preview-window up:3:hidden:wrap

  --bind 'ctrl-/:toggle-preview'

  --bind 'ctrl-y:execute-silent(echo -n {2..} | pbcopy)+abort'

  --color header:italic

  --header 'Press CTRL-Y to copy command into clipboard'"


export FZF_ALT_C_OPTS="--preview 'tree -C {}'"


Usage:

vim $(fzf)

Ctrl+R   # open command history

Alt+C   # show directories and cd to it

Vim **<tab>  #open file list and open with vim

cd **<tab> # open directory list and cd to it


(fzf.vim) .vimrc

command! -bang -nargs=* Rg call fzf#vim#grep("rg --column --line-number --no-heading --color=always --smart-case ".shellescape(<q-args>), 1, {'options': '--delimiter : --nth 4..'}, <bang>0)

set grepprg=rg\ --vimgrep\ --smart-case\ --follow

command! -bang -nargs=? -complete=dir Files

    \ call fzf#vim#files(<q-args>, {'options': ['--layout=reverse', '--info=inline', '--preview', '~/.vim/bundle/fzf.vim/bin/preview.sh {}']}, <bang>0)

"Open Files in the bottom

"let g:fzf_layout = { 'up':  '40%'}

"let g:fzf_layout = { 'down':  '40%'}

Monday, October 17, 2022

Show a vertical column markers in vim (very usefull to check identation)

To show a background line in the whole column 9 and 17

:set colorcolumn=9,17
or short
:set cc=9,17

To change the color to blue
:highlight ColorColumn ctermbg=blue


show line in the cursor column
exe 'set cc='.col('.')
Source: https://superuser.com/questions/249779/how-to-setup-a-line-length-marker-in-vim-gvim

Friday, July 1, 2022

Vim find and repeat search

 For example,

use

f<space>  to go to the next space

; to repeat search and go to the othe next space;


f(  find next (

;;;  go to the fourth ( 

Thursday, May 27, 2021

Copy and paste Shortcuts

Linux

COPY

To copy you may have different scenarios

  • Mode 1
    • In graphical applications you may use Ctrl + C
    • In terminal you may use Ctr + Shift + C
    • Right click menu Copy
  • Mode 2
    • In any application you can just select a text

Wednesday, March 31, 2021

C/C++ manpages quick access from VIM

Vim has by default a helpful shortcut to open the man page of the word under cursor, Shift + k, (or captital K), but very frequently we have shell commands with the same name of a C function, and for example

man printf actually opens the man page for the command, not the C function, but

man 3 printf opens the man pages of the C function, so to open this same man page in Vim, you need to use Shift + 3k (3K)

and for example readlink C function it's man 2 readlink, so in Vim it is Shift + 2k (2K)

Install C++ man pages libstdc++-10-doc


Wednesday, March 10, 2021

gdb print wchar_t *

wchar.gdb

define wchar_print 
        echo "

        set $i = 0
        while (1 == 1)
            set $c = (char)(($arg0)[$i++])
            if ($c == '\0')
                loop_break
            end
            printf "%c", $c
        end

        echo "\n
end


$ gdb -x wchar.gdb  ./myprogram
> wchar_print  mywidevar

or with modern gdb

> set target-wide-charset UTF-16
> p (wchar_t*) mywidevar


Source: https://www.generacodice.com/en/articolo/370005/How-can-I-display-Unicode-strings-while-debugging-on-linux

Tuesday, May 26, 2020

TMUX

.tmux.conf

source /usr/share/powerline/bindings/tmux/powerline.conf
set -g mouse on
set -g history-limit 30000

For the mouse work properly using Vim inside Tmux

In your .vimrc add:

set ttymouse=xterm2
set mouse=a


Atalhos TMUX

set -g status off

Type in all panes at same time
ctrl + b   : setw synchronize-panes on

ctrl + b z   maximize current pane

ctr + b t    show a clock, it can be used to ignore typing when in syncronize-panes on

Ctrl+b " — split pane horizontally.
Ctrl+b % — split pane vertically.
Ctrl+b arrow key — switch pane.
Hold Ctrl+b, don’t release it and hold one of the arrow keys — resize pane.
Ctrl+b c — (c)reate a new window.
Ctrl+b n — move to the (n)ext window.
Ctrl+b p — move to the (p)revious window.
Other thing worth knowing is that scrolling is enabled by
Ctr+b  Alt (arrow)  - resize
          Repeat Alt(arrow) - resize more times
Ctr+b Esc (arrow)  - resize
          Repeat Alt(arrow) - resize more times
Ctr+b Option (arrow)  - resize
          Repeat Option(arrow) - resize more times

C-b [    Start scroll mode, so press Arrow up or Page up

q   Exit scroll mode

C-b x          kill the current pane

C-b q          display pane numbers for a short while

C-b {          move the current pane to the previous position
C-b }          move the current pane to the next position
C-b C-o        rotate window ‘up’ (i.e. move all panes)
C-b M-o        rotate window ‘down’
C-b !          move the current pane into a new separate
               window (‘break pane’)
C-b :move-pane -t :3.2
               split window 3's pane 2 and move the current pane there


C-b c          create a new window
Switch between windows:
C-b 1 ...      switch to window 1, ..., 9, 0
C-b 9
C-b 0
C-b p          previous window
C-b n          next window
C-b l          ‘last’ (previously used) window
C-b w          choose window from a list

Disable bell in Vim, Bash

Disable bell in bash autocompletion


/etc/inputrc

 set bell-style none


 Disable bell when pressing ESC in Vim

 ~/.vimrc

set visualbell

Monday, March 16, 2020

curl multiple line request to remote host using HEREDOC and SED

$ curl -d @<(sed 's/##NOME##/'"${1}"'/' << SED_FILE
{
"nome": ##NOME##,
}
SED_FILE
) http://anywebservice.com/name/${1}

Thursday, February 27, 2020

SSH Proxy SOCKS - Raspbian / Chromium

alias proxy.on='ssh -D 1337 -q -C -N myuser@mysshserver';
alias chromium.proxy='chromium-browser --proxy-server="socks5://localhost:1337" --host-resolver-rules="MAP * ~NOTFOUND , EXCLUDE localhost"';

Call Oauth Token server and decode JWT (Json Web Token) from command line

function jwt-d() {
     sed 's/\./\n/g' <<< $(cut -d. -f1,2 <<< $1) | base64 --decode | jq
}

decode_base64_url() {
    local len=$((${#1} % 4))
    local result="$1"
    if [ $len -eq 2 ]; then
         result="$1"'=='
    elif [ $len -eq 3 ];
         then result="$1"'='
fi
#echo "$result" | tr '_-' '/+' | openssl enc -d -base64
echo "$result" | tr '_-' '/+' | base64 -d
}

decode_jwt(){

    IFS=. read -r jwt_header jwt_body jwt_trail<<<$(echo -n $1)
    echo -e "HEADER:"
    decode_base64_url ${jwt_header} | jq .
    echo -e "\nBODY:"
    decode_base64_url ${jwt_body} | jq --arg TZ $(date +"%Z") 'if .exp then (.expStr = (.exp + 3600*($TZ|tonumber) |gmtime|strftime("%d %B %Y - %H:%M:%S"))) | del (.exp) else . end | if .ia
t then (.iatStr = (.iat + 3600*($TZ|tonumber) |gmtime|strftime("%d %B %Y - %H:%M:%S"))) | del(.iat) else . end'

    echo -e "TRAIL: \n\n${jwt_trail}"
}

alias jwtd="decode_jwt"

sts_token() {
    local tk=$(curl -k -X POST 'https://geratoken.com.br/api/token' --header 'Content-Type: application/x-www-form-urlencoded' --header 'x-empresa-apikey: XXXXXXXX' --header 'x-empresa-correlationID: 123' --header 'x-empresa-flowID: 456' --data-urlencode 'client_id=XXXXXXX' --data-urlencode 'grant_type=client_credentials'
--data-urlencode 'client_secret=XXXXXXX' --cert ~/certificados/mycert.crt --key ~/certificados/mycerkey.key | jq -r .access_token)
    echo "TOKEN: " ${tk}
    jwtd ${tk}
}

Wednesday, August 14, 2019

Record and Replay Mouse and Keyboard events for User interface test automation

Record 999000 events of mouse and keyboard

$ cnee --record --events-to-record 999000 --mouse --keyboard -o /tmp/xnee.xns


Replay


$ cnee --replay -f /tmp/xnee.xns -v -e /tmp/xnee.log -ns -sp 15


Xephyr / Xnest para abrir um Xwindow dentro de outro

Tuesday, June 25, 2019

ssh multiple hops / SSH Config


ssh -tt user_b@HOSTB ssh user_c@HOSTC -p 4567

ssh -J user_b@HOSTB,user_c@HOSTC user_d@HOSTD



Exemplos de ~/.ssh/config

------------------------------------------------------------------------------------------------------- user_a@HOSTA -> user_b@HOSTB:22 -> user_c@HOSTC:4567

Host *
   ControlPersist 18000
   ControlMaster auto
   TCPKeepAlive yes
   ServerAliveInterval 30


Host c_jump1
  User user_c
  Hostname HOSTC
  Port 4567
  ControlPath /tmp/ssjump1
  ProxyCommand ssh -W %h:%p user_b@HOSTB

Host c_jump2
  User user_c
  Hostname HOSTC
  Port 4567
  ControlPath /tmp/ssjump2
  ProxyCommand ssh user_b@HOSTB exec nc %h %p

------------------------------------------------------------------------------
user_a@HOSTA -> user_b@HOSTB:22 -> user_c@HOSTC:4567 -> user_d@HOSTD:7890

Host c_jump3
  Hostname HOSTD
  User user_d
  Port 7890
  ControlPath /tmp/ssjump3
  ProxyJump user_b@HOSTB:22,user_c@HOSTC:4567


-----------------------------------------------------------------------------
# man 5 ssh_config

https://www.systutorials.com/docs/linux/man/5-ssh_config/
http://www.openssh.com/txt/release-5.4

Friday, January 25, 2019

Auto Login with Python + SSH + Expect

Python and Expect

#!/usr/bin/python                                                                                                                     
import argparse
from ConfigParser import ConfigParser
import pexpect

def main(args):
    url = args.url
    user, host = url.split('@', 1)

    cfg_file = '/home/user/bala_python.passwords'
    cfg = ConfigParser()
    cfg.read(cfg_file)
    passwd = cfg.get(user, host)

    child = pexpect.spawn('ssh {0}'.format(url))
    child.expect('password:')
    child.sendline(passwd)
    child.interact()

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Run ssh through pexpect')
    parser.add_argument('url')
    args = parser.parse_args()
    main(args)

....
bala_python.passwords
[user1]
host1 = password1
host2 = password2

[user2]
host1 = password1
host2 = password2

Monday, January 22, 2018

KDE Shortcuts

https://docs.kde.org/trunk5/en/applications/fundamentals/kbd.html


ShortcutDescription
Ctrl+QQuit
Ctrl+EscSystem Activity
Ctrl+Alt+EscForce Quit
Alt+Space / Alt+F2Run Command Interface
Alt+F4Close


ShortcutDescription
Ctrl+F10Present Windows
Ctrl+F9Present Windows on current desktop
Ctrl+F7Present Windows of current application only
Ctrl+F12Show Desktop
Ctrl+Alt+AActivate Window Demanding Attention
Alt+TabWalk through windows
Alt+Shift+TabWalk through windows (Reverse)
Alt+F3Open the Window Operations menu
Meta+Alt+UpSwitch to Window Above
Meta+Alt+DownSwitch to Window Below
Meta+Alt+LeftSwitch to Window to the Left
Meta+Alt+RightSwitch to Window to the Right

ShortcutDescription
Meta+=Zoom In
Meta+-Zoom Out
Meta+0Zoom Normal
Meta+UpPan Up
Meta+DownPan Down
Meta+LeftPan left
Meta+RightPan Right
ShortcutDescription
Meta+Q / Alt+D,Alt+AManage Activities
Meta+TabNext Activity
Meta+Shift+TabPrevious Activity
Ctrl+F1Switch to Desktop 1
Ctrl+F2Switch to Desktop 2
Ctrl+F3Switch to Desktop 3
Ctrl+F4Switch to Desktop 4

ShortcutDescription
Ctrl+Alt+LLock Screen
Ctrl+Alt+DelLeave
Ctrl+Alt+Shift+DelLogout without confirmation
Ctrl+Alt+Shift+Page DownShut Down without confirmation
Ctrl+Alt+Shift+Page UpReboot without confirmation

Friday, December 8, 2017

Remove files with special characters

user@host $ ls -i
65649 file?name
user@host $ find . -inum 65649 -exec rm {} \;
./-.txt

TCPKill - Kill connections in your system

$ tcpkill -i eno1 host 172.16.15.45
$ tcpkill -i eno1 host 172.16.15.45 and port 80
$ tcpkill -i eno1 port 80
$ tcpkill -i eno1
$ tcpkill -i eno1 no host 172.16.15.10
$ tcpkill -i wlp2s0

Wednesday, September 20, 2017

Lock Screen Without Hiding

sudo apt install xtrlock
Lock screen running any monitoring script but keep.it visible.
To autostart after no activity use
xautolock -time 5 -locker "xtrlock -f"

Blog Archive