Create same account in a multiple linux server

Henry
Henry used Ask the Experts™
on
Hello,

I need to run this command in a multiple linux server :

id -u user2 &>/dev/null || useradd -c "SSH account" -d /home/tools user2; echo 'password2' | passwd user2 --stdin

The idea is to create a text file with some IPs one per line and running the above command for each IP

But in somes linux servers, I can directly login as root@ip without password, but others linux servers I need to log as specific user@ip with password and switch to root

Any idea to do that ?
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Mihai BarbosTrying to tame bits. They're nasty.

Commented:
Maybe using expect. Here is a short tutorial on how to use it.
nociSoftware Engineer
Distinguished Expert 2018

Commented:
if ipfile contains:
1.1.1.1
1.1.1.2
1.1.1.3
1.1.1.4

Open in new window


then
for ip in $( cat ipfile ) 
do
  if ssh root@$ip  bash -c 'id -u user2 &>/dev/null || useradd -c "SSH account" -d /home/tools user2; echo "password2" | passwd user2 --stdin'
  then 
     echo $ip done through root
  else
      if ssh user@$ip  sudo bash -c 'id -u user2 &>/dev/null || useradd -c "SSH account" -d /home/tools user2; echo "password2" | passwd user2 --stdin'
      then 
         echo $ip done though user / sudo
      else  
         echo $ip failed
      fi
   fi
done

Open in new window


This might need some adjustment here and there, but it can be a start for your updates..
If this need to be done often, then please look into manageing server farms using a root account that can only do passwordless logon to other roots within your cloud of systems using certificates.
David FavorFractional CTO
Distinguished Expert 2018

Commented:
Easiest way to do this is to first fix every machine so you can login as root with an empty passphrase ssh key.

Trying to do this where some machines require logging in as non-root + switching to root can be done + writing all the shell code would take a good bit of time... which is why most people use root ssh logins to accomplish root tasks.

If you must login as non-root, you're going to have to play some serious games with ssh-agent or other tech.

Doing this can eat up hours of dev time, so you may require hiring someone to write this code for you as... code written will be somewhere unique to your specific runtime environments on initiating machine + all machines requiring this logic.
Duncan RoeSoftware Developer

Commented:
Using Expect you could quite easily define which hosts need what. Expect is a Tcl extension and the host defining stuff would be in Tcl: e.g.an array indexed by host name where the contents of each element are the user name to use (or could include password as well)

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial