1

How do I make my python script login to a server thrugh ssh using a private key and then create a user using the given password? I tried this code but I am not able to go further like sending a "sudo adduser username"

and "sudo adduser username groupname"...

import paramiko
k = paramiko.RSAKey.from_private_key_file("/Users/whatever/Downloads/mykey.pem")
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
print "connecting"
c.connect( hostname = "www.acme.com", username = "ubuntu", pkey = k )
print "connected"
commands = [ "sudo adduser myuser" ]
for command in commands:
    print "Executing {}".format( command )
    stdin , stdout, stderr = c.exec_command(command)
    print stdout.read()
    print( "Errors")
    print stderr.read()
c.close()

Please advise me or I would really appreciate if someone could be kind enough to help me with a working example.

Thanks

1 Answer 1

1

I've tested your code by running different commands. So, please check if you are able to run simple commands like "sudo uptime". If it works fine, then follow the below instructions.

If you run "sudo adduser myuser", you will be prompted to enter more details as in below output:

sudo adduser myuser
Adding user `myuser' ...
Adding new group `myuser' (1002) ...
Adding new user `myuser' (1002) with group `myuser' ...
The home directory `/home/myuser' already exists.  Not copying from `/etc/skel'.
Enter new UNIX password:
Retype new UNIX password:
passwd: password updated successfully
Changing the user information for myuser
Enter the new value, or press ENTER for the default
        Full Name []:
        Room Number []:
        Work Phone []:
        Home Phone []:
        Other []:
Is the information correct? [Y/n] y

So, use the command "sudo useradd myuser" instead of "sudo adduser myuser" because "useradd" command will not prompt for any inputs.

Sign up to request clarification or add additional context in comments.

1 Comment

@josh: Did this answer work for you ? If yes, please accept/upvote the answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.