How to create a user in linux using python - python

How do I create a user in Linux using Python? I mean, I know about the subprocess module and thought about calling 'adduser' and passing all the parameters at once, but the 'adduser' command asks some questions like password, full name, phone and stuff. How would I answer this questions using subprocess?
I've seen module called pexpect in this question: Can I use Python as a Bash replacement?. Is there any other standard module?

Use useradd, it doesn't ask any questions but accepts many command line options.

On Ubuntu, you could use the python-libuser package

import os
import crypt
password ="p#ssw0rd"
encPass = crypt.crypt(password,"22")
os.system("useradd -p "+encPass+" johnsmith")

You could just use the built-in binaries so just call useradd or something through the subprocess module, However I don't know if there's any other modules that hook into Linux to provide such functionality.

def createUser(name,username,password):
encPass = crypt.crypt(password,"22")
return os.system("useradd -p "+encPass+ " -s "+ "/bin/bash "+ "-d "+ "/home/" + username+ " -m "+ " -c \""+ name+"\" " + username)

This is a solution where shell is false.
#!/bin/env/python
import subprocess
import traceback
import sys
def user_add(username, user_dir=None):
if user_dir:
cmd = ["sudo", "useradd", "-d", user_dir, "-m", username]
else:
cmd = ["sudo", "useradd", username]
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, error = p.communicate()
output = output.strip().decode("utf-8")
error = error.decode("utf-8")
if p.returncode != 0:
print(f"E: {error}")
raise
return output
try:
username = "user"
output = user_add(username)
print(F"Success. {username} is added")
except:
traceback.print_exc()
sys.exit(1)

Related

Input command in another terminal via python

I am writing a python for our daily build.
My python will run a script to execute build code command as below.
subprocess.call("./xxx.sh", shell=True)
There will pop up another terminal when running the script and I need to enter "make dtbs" command by myself.
I tried to use subprocess.call("make dtbs", shell=True), but it seems not work in another terminal.
Does there anyone know how to do that?
Thanks.
Eric
The quickest way:
import os
os.system("your command here")
exp:
import os
os.system('ls')
Another way, you can use subprocess's call:
from subprocess import call
call('echo "be easier said than done"', shell=True)
or:
call(['echo', 'be easier said than done'])
If you want to capture the output:
import subprocess
cmd = ['echo', 'be easier said than done']
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
o, e = proc.communicate()
print('Output: ' + o.decode('ascii'))
print('Error: ' + e.decode('ascii'))
print('code: ' + str(proc.returncode))

i want to run my python program(not script) with start command which is a method in that python program file to be executed

Hi have python program in which a start method is defined, in start method i am calling a win32serviceutil.StartService(service) method to start a service, like
import os, platform, subprocess
try:
import win32serviceutil
except:
os.system("pip install pywin32")
os.system("pip install pypiwin32")
import win32serviceutil
OS = platform.system() #will get you the platform/OS
print("You are using ", OS)
if __name__=='__main__':
service = 'WSearch'
def startByCLI():
cmd = 'net start '+service
os.system(cmd)
def startByPython():
# subprocess.check_output(["sc", "start", service], stderr=subprocess.STDOUT)
win32serviceutil.StartService(service)
if OS=='Windows':
try:
output = startByPython()
except subprocess.CalledProcessError as e:
print(e.output)
print(e.returncode)
#os.system('python test2.py')
subprocess.call("python ./install.py asadmin", shell=True)
startByCLI()
so what i actually want is i want to run the start method from command promt like this
python ./myfile.py startByPython
and it will trigger the startByPython method in myfile.py
many thanks in advance
Hey all thanks for your attention,
i wanted to run my file.py file with argument from command line like:
$ /usr/bin/python myfile.py start
i got the solution which is
def main():
# read arguments from the command line and
# check whether at least two elements were entered
if len(sys.argv) < 2:
print "Usage: python aws.py {start|stop}\n"
sys.exit(0)
else:
action = sys.argv[1]
if action == "start":
startInstance()
elif action == "stop":
stopInstance()
else:
print "Usage: python aws.py {start|stop}\n"

redircet stdout to file using variable python 3

I want to redirect o/p of shell commands to file using variable "path" but it is not working
import os, socket, shutil, subprocess
host = os.popen("hostname -s").read().strip()
path = "/root/" + host
if os.path.exists(path):
print(path, "Already exists")
else:
os.mkdir("Directory", path , "Created")
os.system("uname -a" > path/'uname') # I want to redirect o/p of shell commands to file using varibale "path" but it is not working
os.system("df -hP"> path/'df')
I think the problem is the bare > and / symbols in the os.system command...
Here is a python2.7 example with os.system that does what you want
import os
path="./test_dir"
command_str="uname -a > {}/uname".format(path)
os.system(command_str)
Here's a very minimal example using subprocess.run. Also, search StackOverflow for "python shell redirect", and you'll get this result right away:
Calling an external command in Python
import subprocess
def run(filename, command):
with open(filename, 'wb') as stdout_file:
process = subprocess.run(command, stdout=subprocess.PIPE, shell=True)
stdout_file.write(process.stdout)
return process.returncode
run('test_out.txt', 'ls')

Using pexpect to get output of 'ls' command

I am trying to login as a user using pexpect and trying to print all the crons available :
import pexpect
import os, time
passwd = "mypass"
child = pexpect.spawn('su myuser')
child.expect('Password:')
child.sendline(passwd)
child.expect('$')
child.sendline('crontab -l')
i =child.expect(['%','.*$', '$' ])
print i # prints 1 here so, the shell is expected.
print child.before # this doesn't print anything though.
This code doesn't seem to be working and prints empty line.
Couldn't figure out the issue with this code
If there is any better way to list cron job of other user, given username and password
Any pointers or suggestions would be much appreciated.
If you can arrange to configure password-less sudo access, then the above simply becomes:
import subprocess
output = subprocess.check_output('sudo -u myuser crontab -l', shell=True)
If you need to continue using su, then you can pass it a command and avoid trying to parse shell prompts:
import pexpect
passwd = "mypass"
child = pexpect.spawn('su myuser -c "crontab -l"')
child.expect('Password:')
child.sendline(passwd)
child.expect(pexpect.EOF)
print child.before

How to pass password part on linux -subprocess-os

I'm trying to make a program that allows me whenever the user want, shutdown or restart the computer. I'll send this to my friends so I don't know which operating system. I'm using tkinter too,here is an example codes;
import subprocess
import os
time = "10"
if os.name == "posix":
subprocess.call(["shutdown", "-h", time])
elif os.name == "nt":
subprocess.call(["shutdown", "-s", "-t", time])
However, on linux, it's asking password to user before shutting down. So this program is useless if asking password before shutting down. I tried to use %admin ALL = NOPASSWD: /sbin/shutdown after if statement but it doesn't work either. How to pass this password thing on linux?
I don' t think that's possible, you do have to disable the password or your program is like you said going to be useless. But I could be wrong ;)
A direct call of subprocess or Popen could NOT possibly handle this, as this is an interactive to wait for the user input, you can use pexepct for this kind of interactive mode. http://pexpect.readthedocs.org/en/latest/examples.html
You should configure a passwordless /sbin/shutdown via your sudoers settings instead of hardcoding the password in your script.
It is not recommended but you can pass the password to sudo (based on sudo mount example):
#!/usr/bin/env python
from getpass import getpass
from subprocess import Popen, PIPE
command = 'shutdown -P now'.split()
sudo_password = getpass('Sudo password: ')
p = Popen(['sudo', '--stdin'] + command, stdin=PIPE, stderr=PIPE,
universal_newlines=True)
sudo_prompt = p.communicate(sudo_password + '\n')[1]
# should not get here
print('sudo return code = {}'.format(p.returncode))
print('sudo stderr = ' + sudo_prompt)

Categories