0

I'm trying to write a shell script that proceses user information on a remote server via SSH. The user to be processed will be read interactively by the script.

  • My current attempt looks like this

    #!/bin/bash echo "Enter username which u want to add" read Student3 ssh root@serverIP "useradd $Student3;" awk -F: '{print $1, $3, $6, $7}' /etc/passwd | grep "^${Student3}" 

    and it creates empty output.

  • Without the grep call, the output is

    root 0 /root /bin/bash bin 1 /bin /sbin/nologin daemon 2 /sbin /sbin/nologin adm 3 /var/adm /sbin/nologin lp 4 /var/spool/lpd /sbin/nologin sync 5 /sbin /bin/sync shutdown 6 /sbin /sbin/shutdown halt 7 /sbin /sbin/halt mail 8 /var/spool/mail /sbin/nologin operator 11 /root /sbin/nologin 
  • With the grep call appended as | grep "^${Student3}", I get empty output.

1
  • You are adding a user to a remote server and then looking on your system if user is there ? Grep, by default, prints matching lines. Unclear what you want, try to put ssh root@serverIP before your awk command - you will have to work out how to escape ".
    – thecarpy
    CommentedNov 4, 2022 at 9:00

1 Answer 1

5

You are expecting the user that you added to show up in the local /etc/passwd. If it's the file on the remote system that you want to parse with awk, then you need to use ssh to access the data:

#!/bin/bash read -r -p 'Username: ' user # Add user and check the remote /etc/passwd file ssh remote "useradd '$user' && cat /etc/passwd" | awk -F : -v user="$user" '$1 == user { print $1, $3, $6, $7 }' 

That last pipeline could also be written

ssh remote "useradd '$user' && getent passwd '$user'" | awk -F : '{ print $1, $3, $6, $7 }' 

Note that you unlikely want to parse the /etc/passwd data with a regular expression like ^$user as this would match any user with a username that starts with whatever string in $user. The two variations of code above avoid this by not using a regular expression match and instead doing string comparisons of the complete username.

0

    You must log in to answer this question.

    Start asking to get answers

    Find the answer to your question by asking.

    Ask question

    Explore related questions

    See similar questions with these tags.