You can use the id command:
$ ssh 192.168.0.227 logname logname: no login name
However
$ ssh 192.168.0.227 id uid=502(username) gid=100(users) groups=100(users)
In a bash script, you can strip the username from the id output with something like
$ id | cut -d "(" -f 2 | cut -d ")" -f1 username
To have a script that works both in sudo and without a terminal, you can always execute different commands conditionally.
if logname &> /dev/null ; then NAME=$( logname ) else NAME=$( id | cut -d "(" -f 2 | cut -d ")" -f1 ) fi echo $NAME
source share