Page Menu
Home
c4science
Search
Configure Global Search
Log In
Files
F73218222
createUser.py
No One
Temporary
Actions
Download File
Edit File
Delete File
View Transforms
Subscribe
Mute Notifications
Award Token
Subscribers
None
File Metadata
Details
File Info
Storage
Attached
Created
Fri, Jul 19, 17:19
Size
2 KB
Mime Type
text/x-python
Expires
Sun, Jul 21, 17:19 (2 d)
Engine
blob
Format
Raw Data
Handle
19165572
Attached To
R3127 blackdynamite
createUser.py
View Options
#!/usr/bin/python
################################################################
# import getpass
import
os
import
stat
import
psycopg2
import
string
import
argparse
################################################################
from
random
import
randint
,
choice
from
psycopg2.extensions
import
ISOLATION_LEVEL_AUTOCOMMIT
################################################################
def
generatePassword
():
characters
=
string
.
ascii_letters
+
string
.
digits
password
=
""
.
join
(
choice
(
characters
)
for
x
in
range
(
randint
(
8
,
16
)))
return
password
################################################################
def
createUser
(
new_user
):
connection_params
=
dict
()
connection_params
[
"user"
]
=
'postgres'
try
:
connection
=
psycopg2
.
connect
(
**
connection_params
)
except
Exception
as
e
:
raise
Exception
(
str
(
e
)
+
'
\n
'
+
'*'
*
30
+
'
\n
cannot connect to database
\n
'
+
'*'
*
30
)
connection
.
set_isolation_level
(
ISOLATION_LEVEL_AUTOCOMMIT
)
curs
=
connection
.
cursor
()
try
:
curs
.
execute
(
'create user {0}'
.
format
(
new_user
))
except
Exception
as
e
:
print
e
try
:
curs
.
execute
(
'create database {0}'
.
format
(
new_user
))
except
Exception
as
e
:
print
e
try
:
curs
.
execute
(
'alter database {0} owner to {0}'
.
format
(
new_user
))
except
Exception
as
e
:
print
e
curs
.
execute
(
'grant create on database {0} to {0}'
.
format
(
new_user
))
password
=
generatePassword
()
curs
.
execute
(
'alter role {0} with password
\'
{1}
\'
'
.
format
(
new_user
,
password
))
fname
=
'{0}.bd'
.
format
(
new_user
)
bdconf
=
open
(
fname
,
'w'
)
bdconf
.
write
(
'password = {0}'
.
format
(
password
))
bdconf
.
close
()
os
.
chmod
(
fname
,
stat
.
S_IREAD
)
################################################################
parser
=
argparse
.
ArgumentParser
(
description
=
'User creation tool for blackdynamite'
)
parser
.
add_argument
(
"--user"
,
type
=
str
,
help
=
"name of the user to create"
,
required
=
True
)
args
=
parser
.
parse_args
()
args
=
vars
(
args
)
new_user
=
args
[
'user'
]
createUser
(
new_user
)
Event Timeline
Log In to Comment