Search code examples
shellexpect

Expect scripting - extracting userID


I want to get the terminal userID by using whoami command. I have given my script below, but it just returns the command name, instead of username?

How can I get terminal user id using whoami command?

My code is,

send "whoami\r"
      set timeout 5
      expect -re {([a-z]+)} {
       set jobid $expect_out(0,string)
      }
      send_user "\r\nUSER $jobid\r\n"
}

Output for the above code is,

asisdtt-exp7$ whoami
USER whoami
kandabap
asisdtt-exp7$ exit

When I hardcode the first letter of my expected userID (kandabap), I am getting the answer correct. That code is,

send "whoami\r"
      set timeout 5
      expect -re {k([a-z]+)} {
       set jobid $expect_out(0,string)
      }
      send_user "\r\nUSER $jobid\r\n"

Output,

asisdtt-exp7$ whoami
kandabap
asisdtt-exp7$ 
USER kandabap

I am very much confused.


Solution

  • I'm not sure what you're really trying to do, but this will work just fine:

    log_user 0
    spawn whoami
    expect eof
    set jobid $expect_out(buffer)
    puts "USER $jobid"
    

    Of course, none of that's really needed. You can do the same thing using plain TCL:

    puts "USER [exec whoami]"