how can I find who call my bash application - linux

This may look a silly simple question, but I can't find the appropriate method to find the caller.
I have a tool that can be used from different applications. I want to record who is using it.
Note that when sourcing, using source (or the dot shortcut), the executing program is bash (or your designated shell). In this case, only if you source 'tool', the calling history will be preserved on ${BASH_SOURCE[*]}, including the calling line on ${BASH_LINENO[*]}.
I expect BASH_SOURCE give some hint (history), however, the tool is not sourced so, there is no references to caller on 'BASH_SOURCE'.
#!/bin/bash
# this is the tool: I'm expecting to have 'client' somewhere
echo "Source ${BASH_SOURCE[*]}"
ps -axj | grep "\s$$\s"
echo "tool: ${*}"
now, this is the client caller
#!/bin/bash
# this is the client
chmod +x ./tool # I'm making this explicit
./tool this is a test
This is the result:
$ . ./client
Source ./tool
30389 17217 17217 30389 pts/1 17217 S+ 0 0:00 /bin/bash ./tool this is a test
17217 17218 17217 30389 pts/1 17217 R+ 0 0:00 ps -axj
17217 17219 17217 30389 pts/1 17217 S+ 0 0:00 grep \s17217\s
30380 30389 30389 30389 pts/1 17217 Ss 0 0:01 -bash
tool: this is a test

This might help with Linux:
#!/bin/bash
GPPID=$(ps -o ppid= -p $PPID | tr -d ' ')
cat /proc/$GPPID/comm

Would adding ps -o comm= -p $PPID to tool do what you're after?
Edit:
Adding sample output
tink#box ~/tmp$ ./client
Source ./tool
15576 15578 15576 9978 pts/3 15576 S+ 1000 0:00 /bin/bash ./tool this is a test
tool: this is a test
client

Related

How to create alias command to stop celery

Following this solution from another post I've made an alias in my .zshrc (I use ohmyzsh) to stop my celery workers:
alias stopcelery="ps auxww | grep 'celery' | awk '{print $2}' | xargs kill -9"
However when I have running celery workers, using this command fails:
➜ stopcelery
kill: invalid argument
Usage:
kill [options] <pid> [...]
Options:
<pid> [...] send signal to every <pid> listed
-<signal>, -s, --signal <signal>
specify the <signal> to be sent
-l, --list=[<signal>] list all signal names, or convert one to a name
-L, --table list all signal names in a nice table
-h, --help display this help and exit
-V, --version output version information and exit
For more details see kill(1).
The workers are still running:
➜ ps auxww | grep 'celery'
myuser 49126 67.0 0.5 189132 92280 ? S 15:59 0:02 /home/myuser/.local/share/virtualenvs/myproject-JLNbaOhA/bin/python -m celery worker -A wsgi.celery --loglevel=INFO --logfile=/tmp/celery.log --pidfile=celeryd.pid
myuser 49304 0.0 0.5 188160 85060 ? S 15:59 0:00 /home/myuser/.local/share/virtualenvs/myproject-JLNbaOhA/bin/python -m celery worker -A wsgi.celery --loglevel=INFO --logfile=/tmp/celery.log --pidfile=celeryd.pid
myuser 49305 0.0 0.5 188164 84844 ? S 15:59 0:00 /home/myuser/.local/share/virtualenvs/myproject-JLNbaOhA/bin/python -m celery worker -A wsgi.celery --loglevel=INFO --logfile=/tmp/celery.log --pidfile=celeryd.pid
myuser 49306 0.0 0.5 188168 84848 ? S 15:59 0:00 /home/myuser/.local/share/virtualenvs/myproject-JLNbaOhA/bin/python -m celery worker -A wsgi.celery --loglevel=INFO --logfile=/tmp/celery.log --pidfile=celeryd.pid
myuser 49307 0.0 0.5 188172 84844 ? S 15:59 0:00 /home/myuser/.local/share/virtualenvs/myproject-JLNbaOhA/bin/python -m celery worker -A wsgi.celery --loglevel=INFO --logfile=/tmp/celery.log --pidfile=celeryd.pid
myuser 49312 0.0 0.0 20556 2924 pts/8 S+ 15:59 0:00 grep --color=auto --exclude-dir=.bzr --exclude-dir=CVS --exclude-dir=.git --exclude-dir=.hg --exclude-dir=.svn --exclude-dir=.idea --exclude-dir=.tox celery
But using the actual command it works:
➜ ps auxww | grep 'celery' | awk '{print $2}' | xargs kill -9
kill: (48078): No such process
Indeed, checking again:
➜ ps auxww | grep 'celery'
myuser 49782 0.0 0.0 20556 664 pts/8 S+ 16:03 0:00 grep --color=auto --exclude-dir=.bzr --exclude-dir=CVS --exclude-dir=.git --exclude-dir=.hg --exclude-dir=.svn --exclude-dir=.idea --exclude-dir=.tox celery
So what is the difference, why using the alias does not having the same effect?
As #Philippe has pointed out, I forgot to escape the $ sign as I was using double quotes.

How to use grep and cut together to extract a certain text from an output using bash [duplicate]

This question already has answers here:
How to get process ID of background process?
(9 answers)
Closed 1 year ago.
Below is the output of executing two commands ads2 svcd& and ps -aux|grep ads2
nvidia#nvidia-desktop:~$ ads2 svcd&
[1] 4593
nvidia#nvidia-desktop:~$ ps -aux|grep ads2
nvidia 4593 0.5 0.0 39796 23864 pts/0 Sl 08:20 0:00 /opt/ads2/arm-
linux64/bin/ads2svcd
nvidia 4603 0.0 0.0 6092 672 pts/0 S+ 08:20 0:00 grep --color=auto ads2
nvidia#nvidia-desktop:~$
nvidia#nvidia-desktop:~$
the command ads2 svcd& runs a process related to ads2 software. with ps -aux|grep ads2 i displayed the whole processes that contains the name "ads2".
Now What i'm trying to do is to get the process number of the ads2 which in this example is 4593. So i wrote the follwing bash script:
#!/usr/bin/env bash
process="$(ps -aux|grep ads | grep 'nvidia' | cut -d' ' -f 3)"
echo "The current ads2 process is " $process
The bash script outputs the following:
nvidia#nvidia-desktop:~$ ./test.sh
The current ads2 process is
As you see the process number is not filtered. So what i'm i doing wrong?
thanks in advance
List all the processes in the current shell with $$ built-in variable
ps --forest -gp $$
PID TTY STAT TIME COMMAND
3809 pts/1 Ss 0:01 bash
4896 pts/1 T 0:00 \_ vim file.json
22965 pts/1 S+ 0:00 \_ ssh dw
3607 pts/0 Ss 0:01 bash
2500 pts/0 R+ 0:00 \_ ps --forest -gp 3607
3327 tty2 Ssl+ 0:00 /usr/lib/gdm3/gdm-x-session --run-script i3
3329 tty2 Sl+ 8:12 \_ /usr/lib/xorg/Xorg vt2 -displayfd 3 -auth /run/user/1000/gdm/Xauthority -background none -noreset -keeptty -verbose 3
3346 tty2 S+ 0:03 \_ i3
Just see the pid of them:
ps -opid --forest -gp $$
PID
3809
4896
22965
3607
2688
3327
3329
3346
If you need to use grep for any reason, use -opid,cmd with current shell:
ps -opid,cmd -gp $$ | grep vim
3851 grep --color=auto vim
4896 vim file.json
For all, just use -e
ps -e -opid,cmd | grep vim
4141 grep --color=auto vim
4896 vim file.json
The complete one, we have to ignore the grep itself:
ps -e -opid,cmd | grep vim | grep -v grep | cut -d' ' -f 2
4896
Without double grep using comm option for ps
ps -opid,comm -gp $$ | grep vim
4896 vim
of course the simplest one is pgrep
pgrep vim
4896
NOTE for variable assignment there should NOT be any space:
# wrong
ads2ProcessId = $(pgrep ads2)
# right
ads2ProcessId=$(pgrep ads2)

Why i get difference in output when i print this code directly and after storing in a variable

when I give
ps -aux|grep -w 'bash'|grep -v 'grep'|awk '{print $2}'
I get output:
32356
Also when I give
echo $(ps -aux|grep -w 'bash'|grep -v 'grep'|awk '{print $2}')
i get output:
32356 32551
Why there is difference in the outputs?
What is happening is that the $(...) syntax starts a subshell. So the ps command inside those parentheses will find both your current shell (which you can get using $$, as #tink said his their answer), and the subshell that is invoked by the parentheses.
Using ps fux and rediction into a file, you can see exactly what is happening:
ps fux | grep -w bash > a
cat a
me 11603 0.1 0.0 114408 3728 pts/1 Ss 13:37 0:00 \_ -bash
me 11955 0.0 0.0 103348 872 pts/1 S+ 13:41 0:00 \_ grep -w bash
echo $(ps fux | grep -w bash > b)
cat b
me 11603 0.1 0.0 114408 3728 pts/1 Ss+ 13:37 0:00 \_ -bash
me 11981 0.0 0.0 114408 2304 pts/1 S+ 13:41 0:00 \_ -bash
me 11983 0.0 0.0 103348 872 pts/1 S+ 13:41 0:00 \_ grep -w bash
Although #tink gave you a good solution, I hope this answer helps understand what is happening.
It would appear that you're after the pid of the shell you're currently running. That's best achieved with
echo $$ # which is a bash special variable

Cannot execute binary file - Zabbix external scripts on CentOS

Problem: We use Zabbix as monitoring system. In addition to using its built in items, we also use something called external scripts feature (this), where custom scripts can be written and called via Zabbix. The problem facing here is its getting timed out. Script is simple expect file which goes inside a device and pulls some data. This works when called via root. But when called via Zabbix user, its complaining
/usr/bin/expect: /usr/bin/expect: cannot execute binary file
Script looks like this,
#!/usr/bin/expect
set host "IP_ADDRESS"
set uname "username"
set pwd "password"
set prompt "#|>|:|\\\$";
set val ""
set domain [lindex $argv 0]
log_user 0
set timeout -1
spawn /usr/bin/ssh "$uname#$host"
expect "$uname#$host's password:"
send "$pwd\n"
sleep 1
#expect -re "$prompt"
expect ">"
sleep 1
send "show wireless rf-domain statistics detail on $domain | grep Signals\r"
sleep 1
expect ">"
set val $expect_out(buffer)
send "exit\n"
puts $val
This is named as rf_signal.exp. Its called via a wrapper shell script named rf_signal.
#!/bin/bash
val=$(/usr/bin/expect '/usr/local/etc/scripts/rf_signal.exp' $1 | grep 'RF Signals' | cut -d':' -f2 | cut -d',' -f1 | cut -d' ' -f3 | sed -e 's/\s//g')
echo "$val"
And if called as root, this works fine for example
[root#zbx-proxy2 externalscripts]# pwd
/usr/local/share/zabbix/externalscripts
[root#zbx-proxy2 externalscripts]# whoami
root
[root#zbx-proxy2 externalscripts]# /usr/local/share/zabbix/externalscripts/rf_signal DOMAIN_NAME
241
[root#zbx-proxy2 externalscripts]#
Where as if I call as zabbix user I am getting, cannot execute binary file error. With expect as a path
[root#zbx-proxy2 externalscripts]# runuser -l zabbix /usr/bin/expect /usr/local/share/zabbix/externalscripts/rf_signal
/usr/bin/expect: /usr/bin/expect: cannot execute binary file
[root#zbx-proxy2 externalscripts]#
Without expect as a path, it waits -
[root#zbx-proxy2 externalscripts]# runuser -l zabbix /usr/local/share/zabbix/externalscripts/rf_signal
PSTree command output shows it calls expect and contents inside the file
[root#zbx-proxy2 ~]# pstree -p 26295
runuser(26295)---bash(26296)---bash(26309)-+-cut(26312)
|-cut(26313)
|-cut(26314)
|-expect(26310)---ssh(26316)
|-grep(26311)
`-sed(26315)
PS details.
[root#zbx-proxy2 ~]# ps aux | grep zabbix | grep -v "proxy\|agent\|fping"
root 26295 0.0 0.0 130700 1388 pts/3 S+ 15:46 0:00 runuser -l zabbix /usr/local/share/zabbix/externalscripts/rf_signal
zabbix 26296 0.0 0.0 108184 1628 pts/3 S+ 15:46 0:00 -bash /usr/local/share/zabbix/externalscripts/rf_signal
zabbix 26309 0.0 0.0 108184 576 pts/3 S+ 15:46 0:00 -bash /usr/local/share/zabbix/externalscripts/rf_signal
zabbix 26310 0.0 0.0 115336 2260 pts/3 S+ 15:46 0:00 /usr/bin/expect /usr/local/etc/scripts/rf_signal.exp
zabbix 26311 0.0 0.0 103260 868 pts/3 S+ 15:46 0:00 grep RF Signals
zabbix 26312 0.0 0.0 100972 676 pts/3 S+ 15:46 0:00 cut -d: -f2
zabbix 26313 0.0 0.0 100972 672 pts/3 S+ 15:46 0:00 cut -d, -f1
zabbix 26314 0.0 0.0 100972 676 pts/3 S+ 15:46 0:00 cut -d -f3
zabbix 26315 0.0 0.0 105268 872 pts/3 S+ 15:46 0:00 sed -e s/\s//g
zabbix 26316 0.0 0.0 59856 3220 pts/14 Ss+ 15:46 0:00 /usr/bin/ssh username#IP_ADDRESS
root 26688 0.0 0.0 105324 912 pts/7 S+ 15:47 0:00 grep zabbix
[root#zbx-proxy2 ~]#
All the scripts have read and execute permissions to all the users. And expect/grep/cut - whatever used inside the scripts are having read/execute permissions. What could be the issue?
I would suggest you use:
su - zabbix -c "/usr/local/share/zabbix/externalscripts/rf_signal"
to run the script instead of runuser.
Usually, the zabbix user has /sbin/nologin set up as a login shell, which means you won't be able to login via ssh onto the respective server. You may check /etc/passwd on the remote server to verify this.
As an additional note, you may use expect -d to enable debug in your expect script and see where it fails. Set expect's timeout to a different value like 180 (3 minutes) as opposed to -1 otherwise it will never exit.

command in terminal and in script produce different results [duplicate]

I have a bash script (ScreamDaemon.sh) inside which a check that example of it isn't running already is added.
numscr=`ps aux | grep ScreamDaemon.sh | wc -l`;
if [ "${numscr}" -gt "2" ]; then
echo "an instance of ScreamDaemon still running";
exit 0;
fi
Normally, if there are no another copy of script running, ps aux | grep ScreamDaemon.sh | wc -l should return 2 (it should find itself and grep ScreamDaemon.sh), but it returns 3.
So, I try to analyse what happens and after adding some echoes see this:
there are lines I have added into the script
ps aux | grep ScreamDaemon.sh
ps aux | grep ScreamDaemon.sh | wc -l
str=`ps aux | grep ScreamDaemon.sh`
echo $str
numscr=`ps aux | grep ScreamDaemon.sh | wc -l`;
echo $numscr
there is an output:
pamela 27894 0.0 0.0 106100 1216 pts/1 S+ 13:41 0:00 /bin/bash ./ScreamDaemon.sh
pamela 27899 0.0 0.0 103252 844 pts/1 S+ 13:41 0:00 grep ScreamDaemon.sh
2
pamela 27894 0.0 0.0 106100 1216 pts/1 S+ 13:41 0:00 /bin/bash ./ScreamDaemon.sh pamela 27903 0.0 0.0 106100 524 pts/1 S+ 13:41 0:00 /bin/bash ./ScreamDaemon.sh pamela 27905 0.0 0.0 103252 848 pts/1 S+ 13:41 0:00 grep ScreamDaemon.sh
3
I also tried to add the sleep command right inside `ps aux | grep ScreamDaemon.sh; sleep 1m` and see from the parallel terminal how many instances ps aux|grep ScreamDaemon.sh shows:
[pamela#pm03 ~]$ ps aux | grep ScreamDaemon.sh
pamela 28394 0.0 0.0 106100 1216 pts/1 S+ 14:23 0:00 /bin/bash ./ScreamDaemon.sh
pamela 28403 0.0 0.0 106100 592 pts/1 S+ 14:23 0:00 /bin/bash ./ScreamDaemon.sh
pamela 28408 0.0 0.0 103252 848 pts/9 S+ 14:23 0:00 grep ScreamDaemon.sh
So, it seems that
str=`ps aux | grep ScreamDaemon.sh`
contrary to
ps aux | grep ScreamDaemon.sh
found two instances of ScreamDaemon.sh, but why? Where this additional copy of ScreamDaemon.sh come from?
This is an output of pstree -ap command
│ ├─sshd,27806
│ │ └─sshd,27808
│ │ └─bash,27809
│ │ └─ScreamDaemon.sh,28731 ./ScreamDaemon.sh
│ │ └─ScreamDaemon.sh,28740 ./ScreamDaemon.sh
│ │ └─sleep,28743 2m
Why can a single bash script show up multiple times in ps?
This is typical when any constructs which implicitly create a subshell are in play. For instance, in bash:
echo foo | bar
...creates a new forked copy of the shell to run the echo, with its own ps instance. Similarly:
( bar; echo done )
...creates a new subshell, has that subshell run the external command bar, and then has the subshell perform the echo.
Similarly:
foo=$(bar)
...creates a subshell for the command substitution, runs bar in there (potentially exec'ing the command and consuming the subshell, but this is not guaranteed), and reads its output into the parent.
Now, how does this answer your question? Because
result=$(ps aux | grep | wc)
...runs that ps command in a subshell, which itself creates an extra bash instance.
How can I properly ensure that only one copy of my script is running?
Use a lockfile.
See for instance:
How to prevent a script from running simultaneously?
What is the best way to ensure only one instance of a Bash script is running?
Note that I strongly suggest use of a flock-based variant.
Of course, the reason you find an additional process is because:
One process is running the sub-shell (of the command execution `..`)
included in your line: numscr=`ps aux | grep ScreamDaemon.sh | wc -l`;
that's the simplest answer.
However I would like to make some additional suggestions about your code:
First, quote your expansions, it should be: echo "$str".
Not doing so is making several lines collapse into a long one.
Second, you may use: grep [S]creamDaemon.sh to avoid matching the grep command itself.
Third, capture the command just once in a variable, then count lines from the variable. In this case it presents no problem, but for dynamic processes, one capture and the following capture to count could give different results.
Fourth, make an habit of using $(...) command substitutions instead of the more error prone (especially when Nesting) `...`.
### Using a file as the simplest way to capture the output of a command
### that is running in this shell (not a subshell).
ps aux | grep "[S]creamDaemon.sh" > "/tmp/tmpfile$$.txt"
str="$(< "/tmp/tmpfile$$.txt")" ### get the value of var "str"
rm "/tmp/tmpfile$$.txt" ### erase the file used ($$ is pid).
numscr="$(echo "$str" | wc -l)" ### count the number of lines.
echo "$numscr" ### present results.
echo "$str"
str="$( ps aux | grep "[S]creamDaemon.sh" )" ### capture var "str".
numscr="$(echo "$str" | wc -l)" ### count the number of lines.
echo "$numscr" ### present results.
echo "$str"
### The only bashim is the `$(<...)`, change to `$(cat ...)` if needed.
#CharlesDuffy covered the point of a flock quite well, please read it.

Resources