Showing posts with label command line. Show all posts
Showing posts with label command line. Show all posts

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

Monday, March 1, 2021

(Debug) GDB with full colored dashboard

$ pip install pygments

$ wget -P ~ https://git.io/.gdbinit

If gdb version prior to 7.7 and python prior to 2.7 execute this

$ mkdir -p ~/.gdbinit.d/
$ wget 'https://sourceware.org/git/gitweb.cgi?p=binutils-gdb.git;a=blob_plain;f=gdb/python/lib/gdb/FrameDecorator.py' -O ~/.gdbinit.d/FrameDecorator.py
$ sed -i '1s/^/python gdb.COMPLETE_EXPRESSION = gdb.COMPLETE_SYMBOL\n/' .gdbinit
$ sed -i "s/gdb_breakpoint.temporary/None/g" .gdbinit

$ cat >>~/.gdbinit <<EOF
python

import imp
gdb.FrameDecorator = imp.new_module('FrameDecorator')
gdb.FrameDecorator.FrameDecorator = FrameDecorator
end
EOF

You can also send module to be shown on different terminals

start gdb 

$ gdb my_program

in another terminal

$ tty
> /dev/pts/3

in gdb to move Registers to this other terminal 

> dashboard breakpoints -output /dev/pts/3
> dashboard variables -output /dev/pts/3
> dashboard -layout variables stack source breakpoints

to Get help 

>>> help dashboard

Wednesday, May 27, 2020

Increment version in manifest.json file

$ cat manifest.json | awk -F'["]' -v OFS='"' '/"version":/ { split($4,a,"."); $4=a[1]"."a[2]"."a[3]+1 };1' > _temp_version_ && mv _temp_version_ manifest.json

manifest.json

{
 "version":1.2.3,
...
}

---->

{
 "version":1.2.4,
...
}

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}
}

Saturday, January 25, 2020

Make your Linux Terminal and VIM statusline more visually beautiful and eye candy with Powerline






sudo apt-get install powerline python3-powerline


.bashrc
powerline-daemon -q POWERLINE_BASH_CONTINUATION=1 POWERLINE_BASH_SELECT=1 . /usr/share/powerline/bindings/bash/powerline.sh

.vimrc
python3 from powerline.vim import setup as powerline_setup 
python3 powerline_setup() 
python3 del powerline_setup 
set laststatus=2 

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

Thursday, July 4, 2019

Access Remote Webcam (Take Picture and Live Stream), Access VNC Through SSH

Take picture on remote and display locally

ssh cloud_raspi 'fswebcam tapeiga.png && cat tapeiga.png' | display

Take screenshot on remote and display locally

ssh cloud_raspi 'DISPLAY=:0 scrot tapeiga2.png && cat tapeiga2.png' | display

Live video recording on remote and live display locally

ssh cloud_raspi ffmpeg -an -f video4linux2 -s 640x480 -i /dev/video0 -r 10 -b:v 500k -f matroska - | mplayer - -idle -demuxer matroska

Turn on TV connected on HDMI, on remote

ssh cloud_raspi 'vcgencmd display_power 1'

Turn off TV connected on HDMI, on remote

ssh cloud_raspi 'vcgencmd display_power 0'

Live Record Video Locally and Live Display on Remote TV
ffmpeg -an -f video4linux2 -s 640x480 -i /dev/video0 -r 10 -b:v 500k -f matroska - | ssh cloud_raspi 'DISPLAY=:0 mplayer - -idle -demuxer matroska'

Live Record Audio Remotelly and play Locally
ssh cloud_raspi "arecord -f cd -D plughw:1 | ffmpeg -ac 1 -i - -f ogg - " | mplayer - -idle -demuxer ogg
Live Record Audio Locally and Play on Remote
arecord -f cd -D plughw:1 | ffmpeg -ac 1 -i - -f ogg - | ssh cloud_raspi 'mplayer - -idle -demuxer ogg'
or
arecord -f cd | ssh cloud_raspi 'aplay'
or
arecord -f S16_LE -r 3600 | ssh cloud_raspi 'aplay'

Connect on VNC via cloud

On remote machine start VNC Server
and start a tunnel
ssh -R 6900:localhost:5900 user@mycloudserver.com

On local machine start a tunnel
ssh -L 5900:localhost:6900 user@mycloudserver.com
and connect vnc client to localhost
vncviewer localhost




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

Transfer file through ssh connection using cat pipe

cat z.cpp | ssh user@hostname 'cat > /remote_folder/copy_of_z.cpp'

ssh user@hostname 'cat /remote_folder/copy_of_z.cpp' > z.cpp

Tuesday, February 5, 2019

Enable acess of internet connected to a VPN

nano /etc/sysctl.conf
Add or find and comment out the following line
net.ipv4.ip_forward=1
Save, close the file and run the following command to make the changes take effect.
sysctl -p
-------------
The following iptables firewall rules allow port 1723, GRE and perform NAT
iptables -I INPUT -p tcp --dport 1723 -m state --state NEW -j ACCEPT
iptables -I INPUT -p gre -j ACCEPT
iptables -t nat -I POSTROUTING -o eth0 -j MASQUERADE
In the last rule replace “eth0″ with the interface connecting to the internet on your VPN server. Finally the following rule is required to ensure websites load properly
iptables -I FORWARD -p tcp --tcp-flags SYN,RST SYN -s 172.20.1.0/24 -j TCPMSS  --clamp-mss-to-pmtu
Replace 172.20.1.0/24 with the IP address range used in the “remoteip” option in the /etc/pptpd.conf this firewall rule is used to ensure a proper MTU value is used to prevent fragmentation.

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

Sunday, April 1, 2018

PS | Script for Top equivalent command for AIX



#!/bin/sh

# If the shell script is stopped with CTRL+C, the screen
# might need to be sized correctly.

trap 'eval $(resize); exit 2' 2

# A loop to display activity.
while [ 1 ] ; do
eval $(resize)
#output=$(ps -eF "pcpu time pid user rssize comm" | grep -v TIME | sort -rn | head -$(("$LINES"-2)))
output=$(ps -eF "pcpu time pid user time etime rssize comm" | grep -v TIME | sort -rn | head -$(("$LINES"-2)))

echo ' %CPU TIME PID USER TIME ELAPSED RSS COMMAND'
echo "$output"
sleep 3
done
------------------------
ps -eof pid,cmd linux
ps -ef -o pid,args aix

ps f  # show ascii tree hierarchy
ps f -eo rss,ppid,pid,cmd   # shows memory process parent id, process id, comand and ascii hierarchy
ps faux # shows all process of all users and tree hierarchy


print all children of xrdp program
ps f -g $(ps -o sid= -p `pidof xrdp`)

pstree # show hierarchy with lines instead of slash and bars

http://meinit.nl/alternative-top-aix

Tuesday, March 6, 2018

Tcpdump

TCP Dump
----------------------------------------------------------------------------------
$ sudo tcpdump -s 0 -A host www.uol.com.br and port 80 #Show ASCII
$ sudo tcpdump -s 0 -X host www.uol.com.br and port 80 #Show Hexdump and ASCII

#Filter only packages in port range from 4210-4218, with tcp-flag Push, and do not buffer output with "-l" so I can pipe and don't freeze

$ sudo tcpdump -l -i eth0 -X -s 0 -n 'host snelnxa124 and portrange 4210-4218 and (tcp[tcpflags] & (tcp-push) != 0)'
$ sudo tcpdump -l -i eth0 -A -s 0 -n 'host snelnxa124 and portrange 4210-4218 and (tcp[tcpflags] & (tcp-push) != 0)' | grep -v Flags
$ sudo tcpdump -l -i eno1  -A -s 0 -n 'host www.ic.unicamp.br and tcp port http'

Extra
-----------------------------------------------------------------------------------
$ telnet towel.blinkenlights.nl #Star wars ascii

https://goo.gl/AwpNxV
https://fwknowledge.wordpress.com/2013/03/05/tcpdump-flags/
https://www.wains.be/pub/networking/tcpdump_advanced_filters.txt

Wednesday, February 28, 2018

Expect to login in ssh server through balabit

#!/usr/bin/expect -f

trap {
   set XZ [stty rows   ]
   set YZ [stty columns]
   stty rows $XZ columns $YZ < $spawn_out(slave,name)
} WINCH


proc getpass pwprompt {
       set oldmode [stty -echo -raw]
       send_user "\n     $pwprompt"
       set timeout -1
       expect_user -re "(.*)\n"
       send_user "\n"
       eval stty $oldmode
       return $expect_out(1,string)
}

set host [lrange $argv 0 0]

#Save Last Path ########
set last_path_file "/tmp/.save_bala_ssh_$host.txt"
if {[file exists $last_path_file]} {
       set f [open "/tmp/.save_bala_ssh_$host.txt"]
       set lp [split [read $f] "\n"]
       set last_path [lindex $lp 1]
       send_user "Last Path for host $host: $last_path\n"
       close $f
}
########################

#set user [lrange $argv 1 1]
set user "usuario_balabit"
set path [lrange $argv 1 1]
#set pass [getpass "Password: "]
set pass "senha_balabit"
set timeout -1
#spawn -noecho bash;
#send "ssh -A $host\r"
spawn ssh -t $host
set passwords { "senha1" "senha2" "senha3" }
set try 0
##
set timeout 2
expect {
       "Gateway username: " {
               send -- "$user\r"
               exp_continue
       }

       "Gateway password: " {
               send -- "$pass\r"
               exp_continue
       }

       "password:" {
               if { $try >= [llength $passwords] } {
                       send_error ">>> wrong passwords\n"
                               exit 1
               }
               send -- "[lindex $passwords $try]\r"
               incr try
               set timeout 3
               exp_continue
       }

       "denied" {
               set timeout 5
               exp_continue
       }

       timeout {
               #interact
               send_user "\nOK Cool! Finally Connected\n"
               if { $path != "" } {
                       if { $path != "-l" } {
                               send  -- "\nclear\ncd $path\n"
                       } else {
                               send  -- "\nclear\ncd $last_path\n"
                       }
               }
               #interact
               set CTRLZ \032
               interact {
                       -reset $CTRLZ {exec kill -STOP [pid]}
                       #\003   exit
                       #mostra_data {
                       #       send_user "The date is [exec date]."
                       #}
                       #foo {
                       #       send_user "bar"
                       #}
                       #\001   {send_user "you typed a control-A\n";
                       #       send "\001"
                       #}
                       #\002   {send_user "you typed a control-B\n";
                       #       send "\002"
                       #}
                       ç {
                               send "pwd\r"
                               expect "/*\n"
                               puts [open $last_path_file w] $expect_out(buffer)
                       }
               }
       }
}

Friday, December 8, 2017

Remove files with special characters

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

Blog Archive