Sometimes it is very convenient to define shell function and execute it remotely.
I will use Bash and assume that it is used by default on a remote server but do not worry as I will show you how to ensure that the proper shell is used.
Define find_setuid
function that will be used to find files with setuid permissions. It is quite simple but, at the same time, serves as an excellent example for this use case.
$ function find_setuid() { find $(echo $PATH | tr ":" " ") -user root -perm -4000 -exec ls -lh {} \;; }
I will use declare
command to get function definition.
$ declare -f find_suid find_setuid () { find $(echo $PATH | tr ":" " ") -user root -perm -4000 -exec ls -lh {} \; }
Execute find_setuid
function on remote server assuming that Bash will be used.
$ ssh cloud.sleeplessbeastie.eu "$(declare -f find_setuid); find_setuid" -rwsr-xr-x 1 root root 31K May 17 2017 /usr/bin/newgrp -rwsr-xr-x 1 root root 57K May 17 2017 /usr/bin/gpasswd -rwsr-xr-x 1 root root 133K Jun 5 2017 /usr/bin/sudo -rwsr-xr-x 1 root root 18K May 24 2017 /usr/bin/pkexec -rwsr-xr-x 1 root root 45K May 17 2017 /usr/bin/passwd -rwsr-xr-x 1 root root 40K May 17 2017 /usr/bin/chfn -rwsr-xr-x 1 root root 31K May 17 2017 /usr/bin/chsh -rwsr-xr-x 1 root root 35K Mar 7 2018 /bin/mount -rwsr-xr-x 1 root root 55K Nov 10 2016 /bin/ping -rwsr-xr-x 1 root root 22K Mar 7 2018 /bin/umount -rwsr-xr-x 1 root root 31K May 17 2017 /bin/su
Execute find_setuid
function on the remote server, ensuring that Bash will be used.
$ ssh cloud.sleeplessbeastie.eu /bin/bash -c "\"$(declare -f find_setuid);find_setuid\"" -rwsr-xr-x 1 root root 31K May 17 2017 /usr/bin/newgrp -rwsr-xr-x 1 root root 57K May 17 2017 /usr/bin/gpasswd -rwsr-xr-x 1 root root 133K Jun 5 2017 /usr/bin/sudo -rwsr-xr-x 1 root root 18K May 24 2017 /usr/bin/pkexec -rwsr-xr-x 1 root root 45K May 17 2017 /usr/bin/passwd -rwsr-xr-x 1 root root 40K May 17 2017 /usr/bin/chfn -rwsr-xr-x 1 root root 31K May 17 2017 /usr/bin/chsh -rwsr-xr-x 1 root root 35K Mar 7 2018 /bin/mount -rwsr-xr-x 1 root root 55K Nov 10 2016 /bin/ping -rwsr-xr-x 1 root root 22K Mar 7 2018 /bin/umount -rwsr-xr-x 1 root root 31K May 17 2017 /bin/su
Inspect find_setuid
function on the remote server, ensuring that Bash will be used.
$ ssh cloud.sleeplessbeastie.eu /bin/bash -vc "\"$(declare -f find_setuid)\"" find_setuid () { find /usr/local/bin /usr/bin /bin /usr/games -user root -perm -4000 -exec ls -lh {} \; }
Notice, PATH
is expanded on the remote server as expected. This is precisely why this shell function serves as an excellent example for this use case.