0

I am confused as to why I'm having problems executing a history command as another user to return all that user's history - I need to loop though all users and get their history

cat /etc/passwd | awk -F: '{print $1}' > ${system}.users.txt
while read username; do
   echo $username
      sudo -u $username bash -c 'export HISTTIMEFORMAT="%F %T "; history' >../log/${username}.hist
      #sudo -u $username bash -c 'export HISTTIMEFORMAT="%F %T "; history'
done < ./${system}.users.txt

I get no history output when I run: sudo -u anotheruser history

to troubleshoot I tried: sudo -u anotheruser bash -c 'which history'

Also I ran : sudo find / -name 'history' -type f

and I get no returned executable.

Can anybody tell me why a sudo command can't be executed by another user?

1 Answer 1

1

(1) history is a shell builtin; there is no executable

(2) bash -c makes bash noninteractive, and noninteractive shells don't use history. This is not very well documented, but I need both -i and set -o history to get history into a shell with -c:

bash -ic 'set -o history; history'

(Tested in 4.1.2(1) on RedHat and 4.3.11(1) on Ubuntu)

(3) timestamps aren't written to the history file by default, so unless you've (previously) set/forced HISTTIMEFORMAT for your users or they have (previously) deliberately set it, lines/entries read from the history file will (all) have the current time

(4) sudo changes the userid and groupid but not the rest of the environment, so your command will look for the history file of the user running it, not the one in $username; add -i

(5) It might be easier to just read $5/.bash_history -- at least for userids that run bash and have a home directory, which system userids mostly won't

2
  • A second user was not getting it's history timestamped until I executed 'set -o history'. I noticed that the data is encoded above the command within my the .bash_history file without issuing 'set -o history', so for my user in ubuntu 14.04 it seems to be setup with timestamped history automatically (but like you say I need HISTTIMEFORMAT to show the timestamp). Differences between distros perhaps?
    – rupert160
    Commented May 26, 2016 at 13:14
  • 1
    @rupert160 HISTIMEFORMAT is required to either display timestamps or write them to the file. set -o history is at least for me required to get the noninteractive shell to read the file; without that it doesn't have any past history to display with or without timestamps. Commented May 26, 2016 at 23:04

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .